fileinput.js 111 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401
  1. /*!
  2. * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2015
  3. * @version 4.2.6
  4. *
  5. * File input styled for Bootstrap 3.0 that utilizes HTML5 File Input's advanced
  6. * features including the FileReader API.
  7. *
  8. * The plugin drastically enhances the HTML file input to preview multiple files on the client before
  9. * upload. In addition it provides the ability to preview content of images, text, videos, audio, html,
  10. * flash and other objects. It also offers the ability to upload and delete files using AJAX, and add
  11. * files in batches (i.e. preview, append, or remove before upload).
  12. *
  13. * Author: Kartik Visweswaran
  14. * Copyright: 2015, Kartik Visweswaran, Krajee.com
  15. * For more JQuery plugins visit http://plugins.krajee.com
  16. * For more Yii related demos visit http://demos.krajee.com
  17. */
  18. (function ($) {
  19. "use strict";
  20. $.fn.fileinputLocales = {};
  21. var isIE = function (ver) { // check for IE versions < 11
  22. if (navigator.appName != 'Microsoft Internet Explorer') {
  23. return false;
  24. }
  25. if (ver == 10) {
  26. return RegExp('msie\\s' + ver, 'i').test(navigator.userAgent);
  27. }
  28. var div = document.createElement("div"), status;
  29. div.innerHTML = "<!--[if IE " + ver + "]> <i></i> <![endif]-->";
  30. status = div.getElementsByTagName("i").length;
  31. document.body.appendChild(div);
  32. div.parentNode.removeChild(div);
  33. return status;
  34. },
  35. handler = function ($el, event, callback, skipNS) {
  36. var ev = skipNS ? event : event + '.fileinput';
  37. $el.off(ev).on(ev, callback);
  38. },
  39. previewCache = {
  40. data: {},
  41. init: function (obj) {
  42. var content = obj.initialPreview, id = obj.id;
  43. if (content.length > 0 && !isArray(content)) {
  44. content = content.split(obj.initialPreviewDelimiter);
  45. }
  46. previewCache.data[id] = {
  47. content: content,
  48. config: obj.initialPreviewConfig,
  49. tags: obj.initialPreviewThumbTags,
  50. delimiter: obj.initialPreviewDelimiter,
  51. template: obj.previewGenericTemplate,
  52. msg: function (n) {
  53. return obj.getMsgSelected(n);
  54. },
  55. initId: obj.previewInitId,
  56. footer: obj.getLayoutTemplate('footer'),
  57. isDelete: obj.initialPreviewShowDelete,
  58. caption: obj.initialCaption,
  59. actions: function (showUpload, showDelete, disabled, url, key) {
  60. return obj.renderFileActions(showUpload, showDelete, disabled, url, key);
  61. }
  62. };
  63. },
  64. fetch: function (id) {
  65. return previewCache.data[id].content.filter(function (n) {
  66. return n !== null;
  67. });
  68. },
  69. count: function (id, all) {
  70. return !!previewCache.data[id] && !!previewCache.data[id].content ?
  71. (all ? previewCache.data[id].content.length : previewCache.fetch(id).length) : 0;
  72. },
  73. get: function (id, i, isDisabled) {
  74. var ind = 'init_' + i, data = previewCache.data[id], config = data.config[i],
  75. previewId = data.initId + '-' + ind, out, $tmp, frameClass = ' file-preview-initial';
  76. isDisabled = isDisabled === undefined ? true : isDisabled;
  77. if (data.content[i] === null) {
  78. return '';
  79. }
  80. if (!isEmpty(config) && !isEmpty(config.frameClass)) {
  81. frameClass += ' ' + config.frameClass;
  82. }
  83. out = data.template
  84. .replace(/\{previewId\}/g, previewId)
  85. .replace(/\{frameClass\}/g, frameClass)
  86. .replace(/\{fileindex\}/g, ind)
  87. .replace(/\{content\}/g, data.content[i])
  88. .replace(/\{footer\}/g, previewCache.footer(id, i, isDisabled));
  89. if (data.tags.length && data.tags[i]) {
  90. out = replaceTags(out, data.tags[i]);
  91. }
  92. if (!isEmpty(config) && !isEmpty(config.frameAttr)) {
  93. $tmp = $(document.createElement('div')).html(out);
  94. $tmp.find('.file-preview-initial').attr(config.frameAttr);
  95. out = $tmp.html();
  96. $tmp.remove();
  97. }
  98. return out;
  99. },
  100. add: function (id, content, config, tags, append) {
  101. var data = $.extend(true, {}, previewCache.data[id]), index;
  102. if (!isArray(content)) {
  103. content = content.split(data.delimiter);
  104. }
  105. if (append) {
  106. index = data.content.push(content) - 1;
  107. data.config[index] = config;
  108. data.tags[index] = tags;
  109. } else {
  110. index = content.length;
  111. data.content = content;
  112. data.config = config;
  113. data.tags = tags;
  114. }
  115. previewCache.data[id] = data;
  116. return index;
  117. },
  118. set: function (id, content, config, tags, append) {
  119. var data = $.extend(true, {}, previewCache.data[id]), i;
  120. if (!isArray(content)) {
  121. content = content.split(data.delimiter);
  122. }
  123. if (append) {
  124. for (i = 0; i < content.length; i++) {
  125. data.content.push(content[i]);
  126. }
  127. for (i = 0; i < config.length; i++) {
  128. data.config.push(config[i]);
  129. }
  130. for (i = 0; i < tags.length; i++) {
  131. data.tags.push(tags[i]);
  132. }
  133. } else {
  134. data.content = content;
  135. data.config = config;
  136. data.tags = tags;
  137. }
  138. previewCache.data[id] = data;
  139. },
  140. unset: function (id, index) {
  141. var chk = previewCache.count(id);
  142. if (!chk) {
  143. return;
  144. }
  145. if (chk === 1) {
  146. previewCache.data[id].content = [];
  147. previewCache.data[id].config = [];
  148. return;
  149. }
  150. previewCache.data[id].content[index] = null;
  151. previewCache.data[id].config[index] = null;
  152. },
  153. out: function (id) {
  154. var html = '', data = previewCache.data[id], caption, len = previewCache.count(id, true);
  155. if (len === 0) {
  156. return {content: '', caption: ''};
  157. }
  158. for (var i = 0; i < len; i++) {
  159. html += previewCache.get(id, i);
  160. }
  161. caption = data.msg(previewCache.count(id));
  162. return {content: html, caption: caption};
  163. },
  164. footer: function (id, i, isDisabled) {
  165. var data = previewCache.data[id];
  166. isDisabled = isDisabled === undefined ? true : isDisabled;
  167. if (data.config.length === 0 || isEmpty(data.config[i])) {
  168. return '';
  169. }
  170. var config = data.config[i],
  171. caption = isSet('caption', config) ? config.caption : '',
  172. width = isSet('width', config) ? config.width : 'auto',
  173. url = isSet('url', config) ? config.url : false,
  174. key = isSet('key', config) ? config.key : null,
  175. disabled = (url === false) && isDisabled,
  176. actions = data.isDelete ? data.actions(false, true, disabled, url, key) : '',
  177. footer = data.footer.replace(/\{actions\}/g, actions);
  178. return footer.replace(/\{caption\}/g, caption)
  179. .replace(/\{width\}/g, width)
  180. .replace(/\{indicator\}/g, '')
  181. .replace(/\{indicatorTitle\}/g, '');
  182. }
  183. },
  184. getNum = function (num, def) {
  185. def = def || 0;
  186. if (typeof num === "number") {
  187. return num;
  188. }
  189. if (typeof num === "string") {
  190. num = parseFloat(num);
  191. }
  192. return isNaN(num) ? def : num;
  193. },
  194. hasFileAPISupport = function () {
  195. return window.File && window.FileReader;
  196. },
  197. hasDragDropSupport = function () {
  198. var $div = document.createElement('div');
  199. return !isIE(9) && ($div.draggable !== undefined || ($div.ondragstart !== undefined && $div.ondrop !== undefined));
  200. },
  201. hasFileUploadSupport = function () {
  202. return hasFileAPISupport() && window.FormData;
  203. },
  204. addCss = function ($el, css) {
  205. $el.removeClass(css).addClass(css);
  206. },
  207. STYLE_SETTING = 'style="width:{width};height:{height};"',
  208. OBJECT_PARAMS = ' <param name="controller" value="true" />\n' +
  209. ' <param name="allowFullScreen" value="true" />\n' +
  210. ' <param name="allowScriptAccess" value="always" />\n' +
  211. ' <param name="autoPlay" value="false" />\n' +
  212. ' <param name="autoStart" value="false" />\n' +
  213. ' <param name="quality" value="high" />\n',
  214. DEFAULT_PREVIEW = '<div class="file-preview-other">\n' +
  215. ' <span class="{previewFileIconClass}">{previewFileIcon}</span>\n' +
  216. '</div>',
  217. defaultFileActionSettings = {
  218. removeIcon: '<i class="glyphicon glyphicon-trash text-danger"></i>',
  219. removeClass: 'btn btn-xs btn-default',
  220. removeTitle: 'Remove file',
  221. uploadIcon: '<i class="glyphicon glyphicon-upload text-info"></i>',
  222. uploadClass: 'btn btn-xs btn-default',
  223. uploadTitle: 'Upload file',
  224. indicatorNew: '<i class="glyphicon glyphicon-hand-down text-warning"></i>',
  225. indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign text-success"></i>',
  226. indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>',
  227. indicatorLoading: '<i class="glyphicon glyphicon-hand-up text-muted"></i>',
  228. indicatorNewTitle: 'Not uploaded yet',
  229. indicatorSuccessTitle: 'Uploaded',
  230. indicatorErrorTitle: 'Upload Error',
  231. indicatorLoadingTitle: 'Uploading ...'
  232. },
  233. tMain1 = '{preview}\n' +
  234. '<div class="kv-upload-progress hide"></div>\n' +
  235. '<div class="input-group {class}">\n' +
  236. ' {caption}\n' +
  237. ' <div class="input-group-btn">\n' +
  238. ' {remove}\n' +
  239. ' {cancel}\n' +
  240. ' {upload}\n' +
  241. ' {browse}\n' +
  242. ' </div>\n' +
  243. '</div>',
  244. tMain2 = '{preview}\n<div class="kv-upload-progress hide"></div>\n{remove}\n{cancel}\n{upload}\n{browse}\n',
  245. tPreview = '<div class="file-preview {class}">\n' +
  246. ' <div class="close fileinput-remove">&times;</div>\n' +
  247. ' <div class="{dropClass}">\n' +
  248. ' <div class="file-preview-thumbnails">\n' +
  249. ' </div>\n' +
  250. ' <div class="clearfix"></div>' +
  251. ' <div class="file-preview-status text-center text-success"></div>\n' +
  252. ' <div class="kv-fileinput-error"></div>\n' +
  253. ' </div>\n' +
  254. '</div>',
  255. tIcon = '<span class="glyphicon glyphicon-file kv-caption-icon"></span>',
  256. tCaption = '<div tabindex="500" class="form-control file-caption {class}">\n' +
  257. ' <div class="file-caption-name"></div>\n' +
  258. '</div>\n',
  259. tBtnDefault = '<button type="{type}" tabindex="500" title="{title}" class="{css}"{status}>{icon}{label}</button>',
  260. tBtnLink = '<a href="{href}" tabindex="500" title="{title}" class="{css}"{status}>{icon}{label}</a>',
  261. tBtnBrowse = '<div tabindex="500" class="{css}"{status}>{icon}{label}</div>',
  262. tModal = '<div id="{id}" class="file-preview-detail-modal modal fade" tabindex="-1">\n' +
  263. ' <div class="modal-dialog modal-lg">\n' +
  264. ' <div class="modal-content">\n' +
  265. ' <div class="modal-header">\n' +
  266. ' <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>\n' +
  267. ' <h3 class="modal-title">{heading} <small>{title}</small></h3>\n' +
  268. ' </div>\n' +
  269. ' <div class="modal-body">\n' +
  270. ' <pre>{body}</pre>\n' +
  271. ' </div>\n' +
  272. ' </div>\n' +
  273. ' </div>\n' +
  274. '</div>',
  275. tProgress = '<div class="progress">\n' +
  276. ' <div class="{class}" role="progressbar"' +
  277. ' aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' +
  278. ' {percent}%\n' +
  279. ' </div>\n' +
  280. '</div>',
  281. tFooter = '<div class="file-thumbnail-footer">\n' +
  282. ' <div class="file-footer-caption" title="{caption}">{caption}</div>\n' +
  283. ' {actions}\n' +
  284. '</div>',
  285. tActions = '<div class="file-actions">\n' +
  286. ' <div class="file-footer-buttons">\n' +
  287. ' {upload}{delete}{other}' +
  288. ' </div>\n' +
  289. ' <div class="file-upload-indicator" title="{indicatorTitle}">{indicator}</div>\n' +
  290. ' <div class="clearfix"></div>\n' +
  291. '</div>',
  292. tActionDelete = '<button type="button" class="kv-file-remove {removeClass}" ' +
  293. 'title="{removeTitle}"{dataUrl}{dataKey}>{removeIcon}</button>\n',
  294. tActionUpload = '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">' +
  295. ' {uploadIcon}\n</button>\n',
  296. tZoom = '<button type="button" class="btn btn-default btn-xs btn-block" title="{zoomTitle}: {caption}" onclick="{dialog}">\n' +
  297. ' {zoomInd}\n' +
  298. '</button>\n',
  299. tGeneric = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  300. ' {content}\n' +
  301. ' {footer}\n' +
  302. '</div>\n',
  303. tHtml = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  304. ' <object class="file-object" data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  305. ' ' + DEFAULT_PREVIEW + '\n' +
  306. ' </object>\n' +
  307. ' {footer}\n' +
  308. '</div>',
  309. tImage = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  310. ' <img src="{data}" class="file-preview-image" title="{caption}" alt="{caption}" ' + STYLE_SETTING + '>\n' +
  311. ' {footer}\n' +
  312. '</div>\n',
  313. tText = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  314. ' <pre class="file-preview-text" title="{caption}" ' + STYLE_SETTING + '>{data}</pre>\n' +
  315. ' {zoom}\n' +
  316. ' {footer}\n' +
  317. '</div>',
  318. tVideo = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  319. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  320. ' <video width="{width}" height="{height}" controls>\n' +
  321. ' <source src="{data}" type="{type}">\n' +
  322. ' ' + DEFAULT_PREVIEW + '\n' +
  323. ' </video>\n' +
  324. ' {footer}\n' +
  325. '</div>\n',
  326. tAudio = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  327. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  328. ' <audio controls>\n' +
  329. ' <source src="' + '{data}' + '" type="{type}">\n' +
  330. ' ' + DEFAULT_PREVIEW + '\n' +
  331. ' </audio>\n' +
  332. ' {footer}\n' +
  333. '</div>',
  334. tFlash = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  335. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  336. ' <object class="file-object" type="application/x-shockwave-flash" width="{width}" height="{height}" data="{data}">\n' +
  337. OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' +
  338. ' </object>\n' +
  339. ' {footer}\n' +
  340. '</div>\n',
  341. tObject = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  342. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  343. ' <object class="file-object" data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  344. ' <param name="movie" value="{caption}" />\n' +
  345. OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' +
  346. ' </object>\n' +
  347. ' {footer}\n' +
  348. '</div>',
  349. tOther = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  350. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  351. ' <div class="file-preview-other-frame">\n' +
  352. ' ' + DEFAULT_PREVIEW + '\n' +
  353. ' </div>\n' +
  354. ' <div class="file-preview-other-footer">{footer}</div>\n' +
  355. '</div>',
  356. defaultLayoutTemplates = {
  357. main1: tMain1,
  358. main2: tMain2,
  359. preview: tPreview,
  360. zoom: tZoom,
  361. icon: tIcon,
  362. caption: tCaption,
  363. modal: tModal,
  364. progress: tProgress,
  365. footer: tFooter,
  366. actions: tActions,
  367. actionDelete: tActionDelete,
  368. actionUpload: tActionUpload,
  369. btnDefault: tBtnDefault,
  370. btnLink: tBtnLink,
  371. btnBrowse: tBtnBrowse
  372. },
  373. defaultPreviewTemplates = {
  374. generic: tGeneric,
  375. html: tHtml,
  376. image: tImage,
  377. text: tText,
  378. video: tVideo,
  379. audio: tAudio,
  380. flash: tFlash,
  381. object: tObject,
  382. other: tOther
  383. },
  384. defaultPreviewTypes = ['image', 'html', 'text', 'video', 'audio', 'flash', 'object'],
  385. defaultPreviewSettings = {
  386. image: {width: "auto", height: "160px"},
  387. html: {width: "213px", height: "160px"},
  388. text: {width: "160px", height: "136px"},
  389. video: {width: "213px", height: "160px"},
  390. audio: {width: "213px", height: "80px"},
  391. flash: {width: "213px", height: "160px"},
  392. object: {width: "160px", height: "160px"},
  393. other: {width: "160px", height: "160px"}
  394. },
  395. defaultFileTypeSettings = {
  396. image: function (vType, vName) {
  397. return (vType !== undefined) ? vType.match('image.*') : vName.match(/\.(gif|png|jpe?g)$/i);
  398. },
  399. html: function (vType, vName) {
  400. return (vType !== undefined) ? vType === 'text/html' : vName.match(/\.(htm|html)$/i);
  401. },
  402. text: function (vType, vName) {
  403. return (vType !== undefined && vType.match('text.*')) || vName.match(/\.(txt|md|csv|nfo|ini|json|php|js|css)$/i);
  404. },
  405. video: function (vType, vName) {
  406. return (vType !== undefined && vType.match(/\.video\/(ogg|mp4|webm|3gp)$/i)) || vName.match(/\.(og?|mp4|webm|3gp)$/i);
  407. },
  408. audio: function (vType, vName) {
  409. return (vType !== undefined && vType.match(/\.audio\/(ogg|mp3|wav)$/i)) || vName.match(/\.(ogg|mp3|wav)$/i);
  410. },
  411. flash: function (vType, vName) {
  412. return (vType !== undefined && vType === 'application/x-shockwave-flash') || vName.match(/\.(swf)$/i);
  413. },
  414. object: function () {
  415. return true;
  416. },
  417. other: function () {
  418. return true;
  419. }
  420. },
  421. isEmpty = function (value, trim) {
  422. return value === undefined || value === null || value.length === 0 || (trim && $.trim(value) === '');
  423. },
  424. isArray = function (a) {
  425. return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]';
  426. },
  427. isSet = function (needle, haystack) {
  428. return (typeof haystack === 'object' && needle in haystack);
  429. },
  430. getElement = function (options, param, value) {
  431. return (isEmpty(options) || isEmpty(options[param])) ? value : $(options[param]);
  432. },
  433. uniqId = function () {
  434. return Math.round(new Date().getTime() + (Math.random() * 100));
  435. },
  436. htmlEncode = function (str) {
  437. return str.replace(/\&/g, '&amp;')
  438. .replace(/\</g, '&lt;')
  439. .replace(/\>/g, '&gt;')
  440. .replace(/\"/g, '&quot;')
  441. .replace(/\'/g, '&apos;');
  442. },
  443. replaceTags = function (str, tags) {
  444. var out = str;
  445. if (!tags) {
  446. return out;
  447. }
  448. $.each(tags, function (key, value) {
  449. if (typeof value === "function") {
  450. value = value();
  451. }
  452. out = out.split(key).join(value);
  453. });
  454. return out;
  455. },
  456. objUrl = window.URL || window.webkitURL,
  457. FileInput = function (element, options) {
  458. var self = this;
  459. self.$element = $(element);
  460. if (!self.validate()) {
  461. return;
  462. }
  463. self.isPreviewable = hasFileAPISupport();
  464. self.isIE9 = isIE(9);
  465. self.isIE10 = isIE(10);
  466. if (self.isPreviewable || self.isIE9) {
  467. self.init(options);
  468. self.listen();
  469. } else {
  470. self.$element.removeClass('file-loading');
  471. }
  472. };
  473. FileInput.prototype = {
  474. constructor: FileInput,
  475. validate: function () {
  476. var self = this, $exception;
  477. if (self.$element.attr('type') === 'file') {
  478. return true;
  479. }
  480. $exception = '<div class="help-block alert alert-warning">' +
  481. '<h4>Invalid Input Type</h4>' +
  482. 'You must set an input <code>type = file</code> for <b>bootstrap-fileinput</b> plugin to initialize.' +
  483. '</div>';
  484. self.$element.after($exception);
  485. return false;
  486. },
  487. init: function (options) {
  488. var self = this, $el = self.$element, t;
  489. $.each(options, function (key, value) {
  490. switch (key) {
  491. case 'minFileCount':
  492. case 'maxFileCount':
  493. case 'maxFileSize':
  494. self[key] = getNum(value);
  495. break;
  496. default:
  497. self[key] = value;
  498. break;
  499. }
  500. });
  501. self.fileInputCleared = false;
  502. self.fileBatchCompleted = true;
  503. if (!self.isPreviewable) {
  504. self.showPreview = false;
  505. }
  506. self.uploadFileAttr = !isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data';
  507. self.reader = null;
  508. self.formdata = {};
  509. self.filestack = [];
  510. self.ajaxRequests = [];
  511. self.isError = false;
  512. self.ajaxAborted = false;
  513. self.cancelling = false;
  514. self.dropZoneEnabled = hasDragDropSupport() && self.dropZoneEnabled;
  515. self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly');
  516. self.isUploadable = hasFileUploadSupport() && !isEmpty(self.uploadUrl);
  517. self.slug = typeof options.slugCallback === "function" ? options.slugCallback : self.slugDefault;
  518. self.mainTemplate = self.showCaption ? self.getLayoutTemplate('main1') : self.getLayoutTemplate('main2');
  519. self.captionTemplate = self.getLayoutTemplate('caption');
  520. self.previewGenericTemplate = self.getPreviewTemplate('generic');
  521. if (isEmpty(self.$element.attr('id'))) {
  522. self.$element.attr('id', uniqId());
  523. }
  524. if (self.$container === undefined) {
  525. self.$container = self.createContainer();
  526. } else {
  527. self.refreshContainer();
  528. }
  529. self.$progress = self.$container.find('.kv-upload-progress');
  530. self.$btnUpload = self.$container.find('.fileinput-upload');
  531. self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption'));
  532. self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name'));
  533. self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview'));
  534. self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails'));
  535. self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status'));
  536. self.$errorContainer = getElement(options, 'elErrorContainer',
  537. self.$previewContainer.find('.kv-fileinput-error'));
  538. if (!isEmpty(self.msgErrorClass)) {
  539. addCss(self.$errorContainer, self.msgErrorClass);
  540. }
  541. self.$errorContainer.hide();
  542. self.fileActionSettings = $.extend(defaultFileActionSettings, options.fileActionSettings);
  543. self.previewInitId = "preview-" + uniqId();
  544. self.id = self.$element.attr('id');
  545. previewCache.init(self);
  546. self.initPreview(true);
  547. self.initPreviewDeletes();
  548. self.options = options;
  549. self.setFileDropZoneTitle();
  550. self.uploadCount = 0;
  551. self.uploadPercent = 0;
  552. self.$element.removeClass('file-loading');
  553. t = self.getLayoutTemplate('progress');
  554. self.progressTemplate = t.replace('{class}', self.progressClass);
  555. self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass);
  556. if (self.$element.attr('disabled')) {
  557. self.disable();
  558. }
  559. },
  560. parseError: function (jqXHR, errorThrown, fileName) {
  561. var self = this, errMsg = $.trim(errorThrown + ''),
  562. dot = errMsg.slice(-1) === '.' ? '' : '.',
  563. text = jqXHR.responseJSON !== undefined && jqXHR.responseJSON.error !== undefined ?
  564. jqXHR.responseJSON.error : jqXHR.responseText;
  565. if (self.cancelling && self.msgUploadAborted) {
  566. errMsg = self.msgUploadAborted;
  567. }
  568. if (self.showAjaxErrorDetails && text) {
  569. text = $.trim(text.replace(/\n\s*\n/g, '\n'));
  570. text = text.length > 0 ? '<pre>' + text + '</pre>' : '';
  571. errMsg += dot + text;
  572. } else {
  573. errMsg += dot;
  574. }
  575. self.cancelling = false;
  576. return fileName ? '<b>' + fileName + ': </b>' + errMsg : errMsg;
  577. },
  578. raise: function (event, params) {
  579. var self = this, e = $.Event(event);
  580. if (params !== undefined) {
  581. self.$element.trigger(e, params);
  582. } else {
  583. self.$element.trigger(e);
  584. }
  585. if (e.isDefaultPrevented()) {
  586. return false;
  587. }
  588. if (!e.result) {
  589. return e.result;
  590. }
  591. switch (event) {
  592. // ignore these events
  593. case 'filebatchuploadcomplete':
  594. case 'filebatchuploadsuccess':
  595. case 'fileuploaded':
  596. case 'fileclear':
  597. case 'filecleared':
  598. case 'filereset':
  599. case 'fileerror':
  600. case 'filefoldererror':
  601. case 'fileuploaderror':
  602. case 'filebatchuploaderror':
  603. case 'filedeleteerror':
  604. case 'filecustomerror':
  605. case 'filesuccessremove':
  606. break;
  607. // receive data response via `filecustomerror` event`
  608. default:
  609. self.ajaxAborted = e.result;
  610. break;
  611. }
  612. return true;
  613. },
  614. getLayoutTemplate: function (t) {
  615. var self = this,
  616. template = isSet(t, self.layoutTemplates) ? self.layoutTemplates[t] : defaultLayoutTemplates[t];
  617. if (isEmpty(self.customLayoutTags)) {
  618. return template;
  619. }
  620. return replaceTags(template, self.customLayoutTags);
  621. },
  622. getPreviewTemplate: function (t) {
  623. var self = this,
  624. template = isSet(t, self.previewTemplates) ? self.previewTemplates[t] : defaultPreviewTemplates[t];
  625. if (isEmpty(self.customPreviewTags)) {
  626. return template;
  627. }
  628. return replaceTags(template, self.customPreviewTags);
  629. },
  630. parseFilePreviewIcon: function (content, fname) {
  631. var self = this, ext, icn = self.previewFileIcon;
  632. if (fname && fname.indexOf('.') > -1) {
  633. ext = fname.split('.').pop();
  634. if (self.previewFileIconSettings && self.previewFileIconSettings[ext]) {
  635. icn = self.previewFileIconSettings[ext];
  636. }
  637. if (self.previewFileExtSettings) {
  638. $.each(self.previewFileExtSettings, function (key, func) {
  639. if (self.previewFileIconSettings[key] && func(ext)) {
  640. icn = self.previewFileIconSettings[key];
  641. }
  642. });
  643. }
  644. }
  645. if (content.indexOf('{previewFileIcon}') > -1) {
  646. return content.replace(/\{previewFileIconClass\}/g, self.previewFileIconClass).replace(/\{previewFileIcon\}/g, icn);
  647. }
  648. return content;
  649. },
  650. getOutData: function (jqXHR, responseData, filesData) {
  651. var self = this;
  652. jqXHR = jqXHR || {};
  653. responseData = responseData || {};
  654. filesData = filesData || self.filestack.slice(0) || {};
  655. return {
  656. form: self.formdata,
  657. files: filesData,
  658. extra: self.getExtraData(),
  659. response: responseData,
  660. reader: self.reader,
  661. jqXHR: jqXHR
  662. };
  663. },
  664. listen: function () {
  665. var self = this, $el = self.$element, $cap = self.$captionContainer, $btnFile = self.$btnFile,
  666. $form = $el.closest('form'), $cont = self.$container;
  667. handler($el, 'change', $.proxy(self.change, self));
  668. handler($btnFile, 'click', function () {
  669. self.raise('filebrowse');
  670. if (self.isError && !self.isUploadable) {
  671. self.clear();
  672. }
  673. $cap.focus();
  674. });
  675. handler($form, 'reset', $.proxy(self.reset, self));
  676. handler($cont.find('.fileinput-remove:not([disabled])'), 'click', $.proxy(self.clear, self));
  677. handler($cont.find('.fileinput-cancel'), 'click', $.proxy(self.cancel, self));
  678. if (self.isUploadable && self.dropZoneEnabled && self.showPreview) {
  679. self.initDragDrop();
  680. }
  681. if (!self.isUploadable) {
  682. handler($form, 'submit', $.proxy(self.submitForm, self));
  683. }
  684. handler(self.$container.find('.fileinput-upload'), 'click', function (e) {
  685. var $btn = $(this), $form, isEnabled = !$btn.hasClass('disabled') && isEmpty($btn.attr('disabled'));
  686. if (!self.isUploadable) {
  687. if (isEnabled && $btn.attr('type') !== 'submit') {
  688. $form = $btn.closest('form');
  689. // downgrade to normal form submit if possible
  690. if ($form.length) {
  691. $form.trigger('submit');
  692. }
  693. e.preventDefault();
  694. }
  695. return;
  696. }
  697. e.preventDefault();
  698. if (isEnabled) {
  699. self.upload();
  700. }
  701. });
  702. },
  703. submitForm: function () {
  704. var self = this, $el = self.$element, files = $el.get(0).files;
  705. if (files && self.minFileCount > 0 && self.getFileCount(files.length) < self.minFileCount) {
  706. self.noFilesError({});
  707. return false;
  708. }
  709. return !self.abort({});
  710. },
  711. abort: function (params) {
  712. var self = this, data;
  713. if (self.ajaxAborted && typeof self.ajaxAborted === "object" && self.ajaxAborted.message !== undefined) {
  714. data = $.extend(self.getOutData(), params);
  715. data.abortData = self.ajaxAborted.data || {};
  716. data.abortMessage = self.ajaxAborted.message;
  717. self.cancel();
  718. self.setProgress(100);
  719. self.showUploadError(self.ajaxAborted.message, data, 'filecustomerror');
  720. return true;
  721. }
  722. return false;
  723. },
  724. noFilesError: function (params) {
  725. var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle,
  726. msg = self.msgFilesTooLess.replace('{n}', self.minFileCount).replace('{files}', label),
  727. $error = self.$errorContainer;
  728. self.addError(msg);
  729. self.isError = true;
  730. self.updateFileDetails(0);
  731. $error.fadeIn(800);
  732. self.raise('fileerror', [params]);
  733. self.clearFileInput();
  734. addCss(self.$container, 'has-error');
  735. },
  736. setProgress: function (p) {
  737. var self = this, pct = Math.min(p, 100),
  738. template = pct < 100 ? self.progressTemplate : self.progressCompleteTemplate;
  739. if (!isEmpty(template)) {
  740. self.$progress.html(template.replace(/\{percent\}/g, pct));
  741. }
  742. },
  743. upload: function () {
  744. var self = this, totLen = self.getFileStack().length, params = {},
  745. i, outData, len, hasExtraData = !$.isEmptyObject(self.getExtraData());
  746. if (self.minFileCount > 0 && self.getFileCount(totLen) < self.minFileCount) {
  747. self.noFilesError(params);
  748. return;
  749. }
  750. if (!self.isUploadable || self.isDisabled || (totLen === 0 && !hasExtraData)) {
  751. return;
  752. }
  753. self.resetUpload();
  754. self.$progress.removeClass('hide');
  755. self.uploadCount = 0;
  756. self.uploadPercent = 0;
  757. self.lock();
  758. self.setProgress(0);
  759. if (totLen === 0 && hasExtraData) {
  760. self.uploadExtraOnly();
  761. return;
  762. }
  763. len = self.filestack.length;
  764. self.hasInitData = false;
  765. if (self.uploadAsync && self.showPreview) {
  766. outData = self.getOutData();
  767. self.raise('filebatchpreupload', [outData]);
  768. self.fileBatchCompleted = false;
  769. self.uploadCache = {content: [], config: [], tags: [], append: true};
  770. for (i = 0; i < len; i += 1) {
  771. if (self.filestack[i] !== undefined) {
  772. self.uploadSingle(i, self.filestack, true);
  773. }
  774. }
  775. return;
  776. }
  777. self.uploadBatch();
  778. },
  779. lock: function () {
  780. var self = this;
  781. self.resetErrors();
  782. self.disable();
  783. if (self.showRemove) {
  784. addCss(self.$container.find('.fileinput-remove'), 'hide');
  785. }
  786. if (self.showCancel) {
  787. self.$container.find('.fileinput-cancel').removeClass('hide');
  788. }
  789. self.raise('filelock', [self.filestack, self.getExtraData()]);
  790. },
  791. unlock: function (reset) {
  792. var self = this;
  793. if (reset === undefined) {
  794. reset = true;
  795. }
  796. self.enable();
  797. if (self.showCancel) {
  798. addCss(self.$container.find('.fileinput-cancel'), 'hide');
  799. }
  800. if (self.showRemove) {
  801. self.$container.find('.fileinput-remove').removeClass('hide');
  802. }
  803. if (reset) {
  804. self.resetFileStack();
  805. }
  806. self.raise('fileunlock', [self.filestack, self.getExtraData()]);
  807. },
  808. resetFileStack: function () {
  809. var self = this, i = 0, newstack = [];
  810. self.getThumbs().each(function () {
  811. var $thumb = $(this), ind = $thumb.attr('data-fileindex'),
  812. file = self.filestack[ind];
  813. if (ind === -1) {
  814. return;
  815. }
  816. if (file !== undefined) {
  817. newstack[i] = file;
  818. $thumb.attr({
  819. 'id': self.previewInitId + '-' + i,
  820. 'data-fileindex': i
  821. });
  822. i += 1;
  823. } else {
  824. $thumb.attr({
  825. 'id': 'uploaded-' + uniqId(),
  826. 'data-fileindex': '-1'
  827. });
  828. }
  829. });
  830. self.filestack = newstack;
  831. },
  832. destroy: function () {
  833. var self = this, $cont = self.$container;
  834. $cont.find('.file-drop-zone').off();
  835. self.$element.insertBefore($cont).off('.fileinput').removeData();
  836. $cont.off().remove();
  837. },
  838. refresh: function (options) {
  839. var self = this, $el = self.$element;
  840. options = options ? $.extend(self.options, options) : self.options;
  841. self.destroy();
  842. $el.fileinput(options);
  843. if ($el.val()) {
  844. $el.trigger('change.fileinput');
  845. }
  846. },
  847. initDragDrop: function () {
  848. var self = this, $zone = self.$container.find('.file-drop-zone'),
  849. allEvents = 'dragenter.fileinput dragover.fileinput drop.fileinput';
  850. handler($zone, 'dragenter.fileinput dragover.fileinput', function (e) {
  851. var hasFiles = $.inArray('Files', e.originalEvent.dataTransfer.types) > -1;
  852. e.stopPropagation();
  853. e.preventDefault();
  854. if (self.isDisabled || !hasFiles) {
  855. e.originalEvent.dataTransfer.effectAllowed = 'none';
  856. e.originalEvent.dataTransfer.dropEffect = 'none';
  857. return;
  858. }
  859. addCss($(this), 'highlighted');
  860. }, true);
  861. handler($zone, 'dragleave', function (e) {
  862. e.stopPropagation();
  863. e.preventDefault();
  864. if (self.isDisabled) {
  865. return;
  866. }
  867. $(this).removeClass('highlighted');
  868. });
  869. handler($zone, 'drop', function (e) {
  870. e.preventDefault();
  871. if (self.isDisabled || isEmpty(e.originalEvent.dataTransfer.files)) {
  872. return;
  873. }
  874. self.change(e, 'dragdrop');
  875. $(this).removeClass('highlighted');
  876. });
  877. handler($(document), allEvents, function (e) {
  878. e.stopPropagation();
  879. e.preventDefault();
  880. }, true);
  881. },
  882. setFileDropZoneTitle: function () {
  883. var self = this, $zone = self.$container.find('.file-drop-zone');
  884. $zone.find('.' + self.dropZoneTitleClass).remove();
  885. if (!self.isUploadable || !self.showPreview || $zone.length === 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled) {
  886. return;
  887. }
  888. if ($zone.find('.file-preview-frame').length === 0) {
  889. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + self.dropZoneTitle + '</div>');
  890. }
  891. self.$container.removeClass('file-input-new');
  892. addCss(self.$container, 'file-input-ajax-new');
  893. },
  894. initFileActions: function () {
  895. var self = this;
  896. self.$preview.find('.kv-file-remove').each(function () {
  897. var $el = $(this), $frame = $el.closest('.file-preview-frame'), hasError,
  898. id = $frame.attr('id'), ind = $frame.attr('data-fileindex'), n, cap, status;
  899. handler($el, 'click', function (event) {
  900. status = self.raise('filepreremove', [id, ind]);
  901. if (status === false || !self.validateMinCount()) {
  902. return false;
  903. }
  904. hasError = $frame.hasClass('file-preview-error');
  905. self.cleanMemory($frame);
  906. $frame.fadeOut('slow', function () {
  907. self.filestack[ind] = undefined;
  908. self.clearObjects($frame);
  909. $frame.remove();
  910. if (id && hasError) {
  911. self.$errorContainer.find('li[data-file-id="' + id + '"]').fadeOut('fast', function() {
  912. $(this).remove();
  913. if (!self.$errorContainer.find('li').length &&
  914. !self.$preview.find('.file-preview-frame.file-preview-error').length) {
  915. self.resetErrors();
  916. }
  917. });
  918. }
  919. var filestack = self.getFileStack(true), len = filestack.length, chk = previewCache.count(self.id),
  920. hasThumb = self.showPreview && self.$preview.find('.file-preview-frame').length;
  921. self.clearFileInput();
  922. if (len === 0 && chk === 0 && !hasThumb) {
  923. self.reset();
  924. } else {
  925. n = chk + len;
  926. cap = n > 1 ? self.getMsgSelected(n) : (filestack[0] ? filestack[0].name : '');
  927. self.setCaption(cap);
  928. }
  929. self.raise('fileremoved', [id, ind]);
  930. });
  931. });
  932. });
  933. self.$preview.find('.kv-file-upload').each(function () {
  934. var $el = $(this);
  935. handler($el, 'click', function () {
  936. var $frame = $el.closest('.file-preview-frame'),
  937. ind = $frame.attr('data-fileindex');
  938. if (!$frame.hasClass('file-preview-error')) {
  939. self.uploadSingle(ind, self.filestack, false);
  940. }
  941. });
  942. });
  943. },
  944. getMsgSelected: function (n) {
  945. var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural;
  946. return self.msgSelected.replace('{n}', n).replace('{files}', strFiles);
  947. },
  948. renderFileFooter: function (caption, width) {
  949. var self = this, config = self.fileActionSettings, footer, out,
  950. template = self.getLayoutTemplate('footer');
  951. if (self.isUploadable) {
  952. footer = template.replace(/\{actions\}/g, self.renderFileActions(true, true, false, false, false));
  953. out = footer.replace(/\{caption\}/g, caption)
  954. .replace(/\{width\}/g, width)
  955. .replace(/\{indicator\}/g, config.indicatorNew)
  956. .replace(/\{indicatorTitle\}/g, config.indicatorNewTitle);
  957. } else {
  958. out = template.replace(/\{actions\}/g, '')
  959. .replace(/\{caption\}/g, caption)
  960. .replace(/\{width\}/g, width)
  961. .replace(/\{indicator\}/g, '')
  962. .replace(/\{indicatorTitle\}/g, '');
  963. }
  964. out = replaceTags(out, self.previewThumbTags);
  965. return out;
  966. },
  967. renderFileActions: function (showUpload, showDelete, disabled, url, key) {
  968. if (!showUpload && !showDelete) {
  969. return '';
  970. }
  971. var self = this,
  972. vUrl = url === false ? '' : ' data-url="' + url + '"',
  973. vKey = key === false ? '' : ' data-key="' + key + '"',
  974. btnDelete = self.getLayoutTemplate('actionDelete'),
  975. btnUpload = '',
  976. template = self.getLayoutTemplate('actions'),
  977. otherButtons = self.otherActionButtons.replace(/\{dataKey\}/g, vKey),
  978. config = self.fileActionSettings,
  979. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  980. btnDelete = btnDelete
  981. .replace(/\{removeClass\}/g, removeClass)
  982. .replace(/\{removeIcon\}/g, config.removeIcon)
  983. .replace(/\{removeTitle\}/g, config.removeTitle)
  984. .replace(/\{dataUrl\}/g, vUrl)
  985. .replace(/\{dataKey\}/g, vKey);
  986. if (showUpload) {
  987. btnUpload = self.getLayoutTemplate('actionUpload')
  988. .replace(/\{uploadClass\}/g, config.uploadClass)
  989. .replace(/\{uploadIcon\}/g, config.uploadIcon)
  990. .replace(/\{uploadTitle\}/g, config.uploadTitle);
  991. }
  992. return template
  993. .replace(/\{delete\}/g, btnDelete)
  994. .replace(/\{upload\}/g, btnUpload)
  995. .replace(/\{other\}/g, otherButtons);
  996. },
  997. setThumbStatus: function ($thumb, status) {
  998. var self = this, icon = 'indicator' + status, msg = icon + 'Title',
  999. css = 'file-preview-' + status.toLowerCase(),
  1000. $indicator = $thumb.find('.file-upload-indicator'),
  1001. config = self.fileActionSettings;
  1002. $thumb.removeClass('file-preview-success file-preview-error file-preview-loading');
  1003. if (status === 'Error') {
  1004. $thumb.find('.kv-file-upload').attr('disabled', true);
  1005. addCss($thumb, 'btn disabled');
  1006. }
  1007. $indicator.html(config[icon]);
  1008. $indicator.attr('title', config[msg]);
  1009. $thumb.addClass(css);
  1010. },
  1011. clearPreview: function () {
  1012. var self = this, $thumbs = !self.showUploadedThumbs ? self.$preview.find('.file-preview-frame') :
  1013. self.$preview.find('.file-preview-frame:not(.file-preview-success)');
  1014. $thumbs.remove();
  1015. if (!self.$preview.find('.file-preview-frame').length || !self.showPreview) {
  1016. self.resetUpload();
  1017. }
  1018. },
  1019. initPreview: function (isInit) {
  1020. var self = this, cap = self.initialCaption || '', out;
  1021. if (!previewCache.count(self.id)) {
  1022. self.clearPreview();
  1023. if (isInit) {
  1024. self.setCaption(cap);
  1025. } else {
  1026. self.initCaption();
  1027. }
  1028. return;
  1029. }
  1030. out = previewCache.out(self.id);
  1031. cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
  1032. self.$preview.html(out.content);
  1033. self.setCaption(cap);
  1034. if (!isEmpty(out.content)) {
  1035. self.$container.removeClass('file-input-new');
  1036. }
  1037. },
  1038. initPreviewDeletes: function () {
  1039. var self = this, deleteExtraData = self.deleteExtraData || {},
  1040. resetProgress = function () {
  1041. var hasFiles = self.isUploadable ? previewCache.count(self.id) : self.$element.get(0).files.length;
  1042. if (self.$preview.find('.kv-file-remove').length === 0 && !hasFiles) {
  1043. self.reset();
  1044. self.initialCaption = '';
  1045. }
  1046. };
  1047. self.$preview.find('.kv-file-remove').each(function () {
  1048. var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key');
  1049. if (isEmpty(vUrl) || vKey === undefined) {
  1050. return;
  1051. }
  1052. var $frame = $el.closest('.file-preview-frame'), cache = previewCache.data[self.id],
  1053. settings, params, index = $frame.data('fileindex'), config, extraData;
  1054. index = parseInt(index.replace('init_', ''));
  1055. config = isEmpty(cache.config) && isEmpty(cache.config[index]) ? null : cache.config[index];
  1056. extraData = isEmpty(config) || isEmpty(config.extra) ? deleteExtraData : config.extra;
  1057. if (typeof extraData === "function") {
  1058. extraData = extraData();
  1059. }
  1060. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  1061. settings = $.extend({
  1062. url: vUrl,
  1063. type: 'POST',
  1064. dataType: 'json',
  1065. data: $.extend({key: vKey}, extraData),
  1066. beforeSend: function (jqXHR) {
  1067. self.ajaxAborted = false;
  1068. self.raise('filepredelete', [vKey, jqXHR, extraData]);
  1069. if (self.ajaxAborted) {
  1070. jqXHR.abort();
  1071. } else {
  1072. addCss($frame, 'file-uploading');
  1073. addCss($el, 'disabled');
  1074. }
  1075. },
  1076. success: function (data, textStatus, jqXHR) {
  1077. var n, cap;
  1078. if (isEmpty(data) || isEmpty(data.error)) {
  1079. previewCache.unset(self.id, index);
  1080. n = previewCache.count(self.id);
  1081. cap = n > 0 ? self.getMsgSelected(n) : '';
  1082. self.raise('filedeleted', [vKey, jqXHR, extraData]);
  1083. self.setCaption(cap);
  1084. } else {
  1085. params.jqXHR = jqXHR;
  1086. params.response = data;
  1087. self.showError(data.error, params, 'filedeleteerror');
  1088. $frame.removeClass('file-uploading');
  1089. $el.removeClass('disabled');
  1090. resetProgress();
  1091. return;
  1092. }
  1093. $frame.removeClass('file-uploading').addClass('file-deleted');
  1094. $frame.fadeOut('slow', function () {
  1095. self.clearObjects($frame);
  1096. $frame.remove();
  1097. resetProgress();
  1098. if (!n && self.getFileStack().length === 0) {
  1099. self.setCaption('');
  1100. self.reset();
  1101. }
  1102. });
  1103. },
  1104. error: function (jqXHR, textStatus, errorThrown) {
  1105. var errMsg = self.parseError(jqXHR, errorThrown);
  1106. params.jqXHR = jqXHR;
  1107. params.response = {};
  1108. self.showError(errMsg, params, 'filedeleteerror');
  1109. $frame.removeClass('file-uploading');
  1110. resetProgress();
  1111. }
  1112. }, self.ajaxDeleteSettings);
  1113. handler($el, 'click', function () {
  1114. if (!self.validateMinCount()) {
  1115. return false;
  1116. }
  1117. $.ajax(settings);
  1118. });
  1119. });
  1120. },
  1121. clearObjects: function ($el) {
  1122. $el.find('video audio').each(function () {
  1123. this.pause();
  1124. $(this).remove();
  1125. });
  1126. $el.find('img object div').each(function () {
  1127. $(this).remove();
  1128. });
  1129. },
  1130. clearFileInput: function () {
  1131. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  1132. if (isEmpty($el.val())) {
  1133. return;
  1134. }
  1135. // Fix for IE ver < 11, that does not clear file inputs
  1136. // Requires a sequence of steps to prevent IE crashing but
  1137. // still allow clearing of the file input.
  1138. if (self.isIE9 || self.isIE10) {
  1139. $srcFrm = $el.closest('form');
  1140. $tmpFrm = $(document.createElement('form'));
  1141. $tmpEl = $(document.createElement('div'));
  1142. $el.before($tmpEl);
  1143. if ($srcFrm.length) {
  1144. $srcFrm.after($tmpFrm);
  1145. } else {
  1146. $tmpEl.after($tmpFrm);
  1147. }
  1148. $tmpFrm.append($el).trigger('reset');
  1149. $tmpEl.before($el).remove();
  1150. $tmpFrm.remove();
  1151. } else { // normal input clear behavior for other sane browsers
  1152. $el.val('');
  1153. }
  1154. self.fileInputCleared = true;
  1155. },
  1156. resetUpload: function () {
  1157. var self = this;
  1158. self.uploadCache = {content: [], config: [], tags: [], append: true};
  1159. self.uploadCount = 0;
  1160. self.uploadPercent = 0;
  1161. self.$btnUpload.removeAttr('disabled');
  1162. self.setProgress(0);
  1163. addCss(self.$progress, 'hide');
  1164. self.resetErrors(false);
  1165. self.ajaxAborted = false;
  1166. self.ajaxRequests = [];
  1167. },
  1168. cancel: function () {
  1169. var self = this, xhr = self.ajaxRequests, len = xhr.length, i;
  1170. if (len > 0) {
  1171. for (i = 0; i < len; i += 1) {
  1172. self.cancelling = true;
  1173. xhr[i].abort();
  1174. }
  1175. }
  1176. self.getThumbs().each(function () {
  1177. var $thumb = $(this), ind = $thumb.attr('data-fileindex');
  1178. $thumb.removeClass('file-uploading');
  1179. if (self.filestack[ind] !== undefined) {
  1180. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  1181. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  1182. }
  1183. self.unlock();
  1184. });
  1185. },
  1186. cleanMemory: function ($thumb) {
  1187. var data = $thumb.is('img') ? $thumb.attr('src') : $thumb.find('source').attr('src');
  1188. objUrl.revokeObjectURL(data);
  1189. },
  1190. hasInitialPreview: function () {
  1191. var self = this;
  1192. return !self.overwriteInitial && previewCache.count(self.id);
  1193. },
  1194. clear: function () {
  1195. var self = this, cap;
  1196. self.$btnUpload.removeAttr('disabled');
  1197. self.getThumbs().find('video,audio,img').each(function () {
  1198. self.cleanMemory($(this));
  1199. });
  1200. self.resetUpload();
  1201. self.filestack = [];
  1202. self.clearFileInput();
  1203. self.resetErrors(true);
  1204. self.raise('fileclear');
  1205. if (self.hasInitialPreview()) {
  1206. self.showFileIcon();
  1207. self.resetPreview();
  1208. self.initPreviewDeletes();
  1209. self.$container.removeClass('file-input-new');
  1210. } else {
  1211. self.getThumbs().each(function () {
  1212. self.clearObjects($(this));
  1213. });
  1214. if (self.isUploadable) {
  1215. previewCache.data[self.id] = {};
  1216. }
  1217. self.$preview.html('');
  1218. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  1219. self.setCaption(cap);
  1220. self.$caption.attr('title', '');
  1221. addCss(self.$container, 'file-input-new');
  1222. }
  1223. if (self.$container.find('.file-preview-frame').length === 0) {
  1224. if (!self.initCaption()) {
  1225. self.$captionContainer.find('.kv-caption-icon').hide();
  1226. }
  1227. }
  1228. self.hideFileIcon();
  1229. self.raise('filecleared');
  1230. self.$captionContainer.focus();
  1231. self.setFileDropZoneTitle();
  1232. },
  1233. resetPreview: function () {
  1234. var self = this, out, cap;
  1235. if (previewCache.count(self.id)) {
  1236. out = previewCache.out(self.id);
  1237. self.$preview.html(out.content);
  1238. cap = self.initialCaption ? self.initialCaption : out.caption;
  1239. self.setCaption(cap);
  1240. } else {
  1241. self.clearPreview();
  1242. self.initCaption();
  1243. }
  1244. },
  1245. resetPreviewThumbs: function (isAjax) {
  1246. var self = this, out;
  1247. if (isAjax) {
  1248. self.clearPreview();
  1249. self.filestack = [];
  1250. return;
  1251. }
  1252. if (self.hasInitialPreview()) {
  1253. out = previewCache.out(self.id);
  1254. self.$preview.html(out.content);
  1255. self.setCaption(out.caption);
  1256. self.initPreviewDeletes();
  1257. } else {
  1258. self.clearPreview();
  1259. }
  1260. },
  1261. reset: function () {
  1262. var self = this;
  1263. self.resetPreview();
  1264. self.$container.find('.fileinput-filename').text('');
  1265. self.raise('filereset');
  1266. addCss(self.$container, 'file-input-new');
  1267. if (self.$preview.find('.file-preview-frame').length || self.isUploadable && self.dropZoneEnabled) {
  1268. self.$container.removeClass('file-input-new');
  1269. }
  1270. self.setFileDropZoneTitle();
  1271. self.filestack = [];
  1272. self.formdata = {};
  1273. },
  1274. disable: function () {
  1275. var self = this;
  1276. self.isDisabled = true;
  1277. self.raise('filedisabled');
  1278. self.$element.attr('disabled', 'disabled');
  1279. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  1280. self.$container.find(".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").attr("disabled",
  1281. true);
  1282. self.initDragDrop();
  1283. },
  1284. enable: function () {
  1285. var self = this;
  1286. self.isDisabled = false;
  1287. self.raise('fileenabled');
  1288. self.$element.removeAttr('disabled');
  1289. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  1290. self.$container.find(".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").removeAttr("disabled");
  1291. self.initDragDrop();
  1292. },
  1293. getThumbs: function (css) {
  1294. css = css || '';
  1295. return this.$preview.find('.file-preview-frame:not(.file-preview-initial)' + css);
  1296. },
  1297. getExtraData: function (previewId, index) {
  1298. var self = this, data = self.uploadExtraData;
  1299. if (typeof self.uploadExtraData === "function") {
  1300. data = self.uploadExtraData(previewId, index);
  1301. }
  1302. return data;
  1303. },
  1304. uploadExtra: function (previewId, index) {
  1305. var self = this, data = self.getExtraData(previewId, index);
  1306. if (data.length === 0) {
  1307. return;
  1308. }
  1309. $.each(data, function (key, value) {
  1310. self.formdata.append(key, value);
  1311. });
  1312. },
  1313. initXhr: function (xhrobj, factor) {
  1314. var self = this;
  1315. if (xhrobj.upload) {
  1316. xhrobj.upload.addEventListener('progress', function (event) {
  1317. var pct = 0, position = event.loaded || event.position, total = event.total;
  1318. if (event.lengthComputable) {
  1319. pct = Math.ceil(position / total * factor);
  1320. }
  1321. self.uploadPercent = Math.max(pct, self.uploadPercent);
  1322. self.setProgress(self.uploadPercent);
  1323. }, false);
  1324. }
  1325. return xhrobj;
  1326. },
  1327. ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, previewId, index) {
  1328. var self = this, settings;
  1329. self.raise('filepreajax', [previewId, index]);
  1330. self.uploadExtra(previewId, index);
  1331. settings = $.extend({
  1332. xhr: function () {
  1333. var xhrobj = $.ajaxSettings.xhr();
  1334. return self.initXhr(xhrobj, 98);
  1335. },
  1336. url: self.uploadUrl,
  1337. type: 'POST',
  1338. dataType: 'json',
  1339. data: self.formdata,
  1340. cache: false,
  1341. processData: false,
  1342. contentType: false,
  1343. beforeSend: fnBefore,
  1344. success: fnSuccess,
  1345. complete: fnComplete,
  1346. error: fnError
  1347. }, self.ajaxSettings);
  1348. self.ajaxRequests.push($.ajax(settings));
  1349. },
  1350. initUploadSuccess: function (out, $thumb, allFiles) {
  1351. var self = this, append, data, index, $newThumb, content, config, tags;
  1352. if (typeof out !== 'object' || $.isEmptyObject(out)) {
  1353. return;
  1354. }
  1355. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  1356. self.hasInitData = true;
  1357. content = out.initialPreview || [];
  1358. config = out.initialPreviewConfig || [];
  1359. tags = out.initialPreviewThumbTags || [];
  1360. append = out.append === undefined || out.append ? true : false;
  1361. self.overwriteInitial = false;
  1362. if ($thumb !== undefined && !allFiles) {
  1363. index = previewCache.add(self.id, content, config[0], tags[0], append);
  1364. data = previewCache.get(self.id, index, false);
  1365. $newThumb = $(data).hide();
  1366. $thumb.after($newThumb).fadeOut('slow', function () {
  1367. $newThumb.fadeIn('slow').css('display:inline-block');
  1368. self.initPreviewDeletes();
  1369. self.clearFileInput();
  1370. $thumb.remove();
  1371. });
  1372. } else {
  1373. if (allFiles) {
  1374. self.uploadCache.content.push(content[0]);
  1375. self.uploadCache.config.push(config[0]);
  1376. self.uploadCache.tags.push(tags[0]);
  1377. self.uploadCache.append = append;
  1378. } else {
  1379. previewCache.set(self.id, content, config, tags, append);
  1380. self.initPreview();
  1381. self.initPreviewDeletes();
  1382. }
  1383. }
  1384. }
  1385. },
  1386. initSuccessThumbs: function () {
  1387. var self = this;
  1388. self.getThumbs('.file-preview-success').each(function () {
  1389. var $thumb = $(this), $remove = $thumb.find('.kv-file-remove');
  1390. $remove.removeAttr('disabled');
  1391. handler($remove, 'click', function () {
  1392. var out = self.raise('filesuccessremove', [$thumb.attr('id'), $thumb.data('fileindex')]);
  1393. self.cleanMemory($thumb);
  1394. if (out === false) {
  1395. return;
  1396. }
  1397. $thumb.fadeOut('slow', function () {
  1398. $thumb.remove();
  1399. if (!self.$preview.find('.file-preview-frame').length) {
  1400. self.reset();
  1401. }
  1402. });
  1403. });
  1404. });
  1405. },
  1406. uploadSingle: function (i, files, allFiles) {
  1407. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  1408. previewId = self.previewInitId + "-" + i, $thumb = $('#' + previewId + ':not(.file-preview-initial)'),
  1409. pct, chkComplete, $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove'),
  1410. updateProgress, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1411. resetActions, fnBefore, fnSuccess, fnComplete, fnError, params = {id: previewId, index: i};
  1412. self.formdata = formdata;
  1413. if (total === 0 || !hasPostData || $btnUpload.hasClass('disabled') || self.abort(params)) {
  1414. return;
  1415. }
  1416. chkComplete = function () {
  1417. var $thumbs = self.getThumbs('.file-uploading');
  1418. if ($thumbs.length > 0 || self.fileBatchCompleted) {
  1419. return;
  1420. }
  1421. self.fileBatchCompleted = true;
  1422. setTimeout(function () {
  1423. previewCache.set(self.id, self.uploadCache.content, self.uploadCache.config, self.uploadCache.tags,
  1424. self.uploadCache.append);
  1425. if (self.hasInitData) {
  1426. self.initPreview();
  1427. self.initPreviewDeletes();
  1428. }
  1429. self.setProgress(100);
  1430. self.unlock();
  1431. self.clearFileInput();
  1432. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1433. }, 100);
  1434. };
  1435. updateProgress = function () {
  1436. if (!allFiles || total === 0 || self.uploadPercent >= 100) {
  1437. return;
  1438. }
  1439. self.uploadCount += 1;
  1440. pct = 80 + Math.ceil(self.uploadCount * 20 / total);
  1441. self.uploadPercent = Math.max(pct, self.uploadPercent);
  1442. self.setProgress(self.uploadPercent);
  1443. self.initPreviewDeletes();
  1444. };
  1445. resetActions = function () {
  1446. $btnUpload.removeAttr('disabled');
  1447. $btnDelete.removeAttr('disabled');
  1448. $thumb.removeClass('file-uploading');
  1449. };
  1450. fnBefore = function (jqXHR) {
  1451. outData = self.getOutData(jqXHR);
  1452. if (!$thumb.hasClass('file-preview-success')) {
  1453. self.setThumbStatus($thumb, 'Loading');
  1454. addCss($thumb, 'file-uploading');
  1455. }
  1456. $btnUpload.attr('disabled', true);
  1457. $btnDelete.attr('disabled', true);
  1458. if (!allFiles) {
  1459. self.lock();
  1460. }
  1461. self.raise('filepreupload', [outData, previewId, i]);
  1462. params = $.extend(params, outData);
  1463. if (self.abort(params)) {
  1464. jqXHR.abort();
  1465. self.setProgress(100);
  1466. }
  1467. };
  1468. fnSuccess = function (data, textStatus, jqXHR) {
  1469. outData = self.getOutData(jqXHR, data);
  1470. params = $.extend(params, outData);
  1471. setTimeout(function () {
  1472. if (isEmpty(data) || isEmpty(data.error)) {
  1473. self.setThumbStatus($thumb, 'Success');
  1474. $btnUpload.hide();
  1475. self.filestack[i] = undefined;
  1476. self.raise('fileuploaded', [outData, previewId, i]);
  1477. self.initUploadSuccess(data, $thumb, allFiles);
  1478. if (!allFiles) {
  1479. self.resetFileStack();
  1480. }
  1481. } else {
  1482. self.setThumbStatus($thumb, 'Error');
  1483. self.showUploadError(data.error, params);
  1484. }
  1485. }, 100);
  1486. };
  1487. fnComplete = function () {
  1488. setTimeout(function () {
  1489. updateProgress();
  1490. resetActions();
  1491. if (!allFiles) {
  1492. self.unlock(false);
  1493. } else {
  1494. chkComplete();
  1495. }
  1496. self.initSuccessThumbs();
  1497. }, 100);
  1498. };
  1499. fnError = function (jqXHR, textStatus, errorThrown) {
  1500. var errMsg = self.parseError(jqXHR, errorThrown, (allFiles ? files[i].name : null));
  1501. self.setThumbStatus($thumb, 'Error');
  1502. params = $.extend(params, self.getOutData(jqXHR));
  1503. self.showUploadError(errMsg, params);
  1504. };
  1505. formdata.append(self.uploadFileAttr, files[i]);
  1506. formdata.append('file_id', i);
  1507. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, previewId, i);
  1508. },
  1509. uploadBatch: function () {
  1510. var self = this, files = self.filestack, total = files.length, params = {},
  1511. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1512. setAllUploaded, fnBefore, fnSuccess, fnComplete, fnError;
  1513. self.formdata = new FormData();
  1514. if (total === 0 || !hasPostData || self.abort(params)) {
  1515. return;
  1516. }
  1517. setAllUploaded = function () {
  1518. $.each(files, function (key) {
  1519. self.filestack[key] = undefined;
  1520. });
  1521. self.clearFileInput();
  1522. };
  1523. fnBefore = function (jqXHR) {
  1524. self.lock();
  1525. var outData = self.getOutData(jqXHR);
  1526. if (self.showPreview) {
  1527. self.getThumbs().each(function () {
  1528. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  1529. $btnDelete = $thumb.find('.kv-file-remove');
  1530. if (!$thumb.hasClass('file-preview-success')) {
  1531. self.setThumbStatus($thumb, 'Loading');
  1532. addCss($thumb, 'file-uploading');
  1533. }
  1534. $btnUpload.attr('disabled', true);
  1535. $btnDelete.attr('disabled', true);
  1536. });
  1537. }
  1538. self.raise('filebatchpreupload', [outData]);
  1539. if (self.abort(outData)) {
  1540. jqXHR.abort();
  1541. self.setProgress(100);
  1542. }
  1543. };
  1544. fnSuccess = function (data, textStatus, jqXHR) {
  1545. var outData = self.getOutData(jqXHR, data), $thumbs = self.getThumbs(), key = 0,
  1546. keys = isEmpty(data) || isEmpty(data.errorkeys) ? [] : data.errorkeys;
  1547. if (isEmpty(data) || isEmpty(data.error)) {
  1548. self.raise('filebatchuploadsuccess', [outData]);
  1549. setAllUploaded();
  1550. if (self.showPreview) {
  1551. $thumbs.each(function () {
  1552. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload');
  1553. $thumb.find('.kv-file-upload').hide();
  1554. self.setThumbStatus($thumb, 'Success');
  1555. $thumb.removeClass('file-uploading');
  1556. $btnUpload.removeAttr('disabled');
  1557. });
  1558. self.initUploadSuccess(data);
  1559. } else {
  1560. self.reset();
  1561. }
  1562. } else {
  1563. if (self.showPreview) {
  1564. $thumbs.each(function () {
  1565. var $thumb = $(this), $btnDelete = $thumb.find('.kv-file-remove'),
  1566. $btnUpload = $thumb.find('.kv-file-upload');
  1567. $thumb.removeClass('file-uploading');
  1568. $btnUpload.removeAttr('disabled');
  1569. $btnDelete.removeAttr('disabled');
  1570. if (keys.length === 0) {
  1571. self.setThumbStatus($thumb, 'Error');
  1572. return;
  1573. }
  1574. if ($.inArray(key, keys) !== -1) {
  1575. self.setThumbStatus($thumb, 'Error');
  1576. } else {
  1577. $thumb.find('.kv-file-upload').hide();
  1578. self.setThumbStatus($thumb, 'Success');
  1579. self.filestack[key] = undefined;
  1580. }
  1581. key++;
  1582. });
  1583. self.initUploadSuccess(data);
  1584. }
  1585. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1586. }
  1587. };
  1588. fnComplete = function () {
  1589. self.setProgress(100);
  1590. self.unlock();
  1591. self.initSuccessThumbs();
  1592. self.clearFileInput();
  1593. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1594. };
  1595. fnError = function (jqXHR, textStatus, errorThrown) {
  1596. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1597. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1598. self.uploadFileCount = total - 1;
  1599. if (!self.showPreview) {
  1600. return;
  1601. }
  1602. self.getThumbs().each(function () {
  1603. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1604. $thumb.removeClass('file-uploading');
  1605. if (self.filestack[key] !== undefined) {
  1606. self.setThumbStatus($thumb, 'Error');
  1607. }
  1608. });
  1609. self.getThumbs().removeClass('file-uploading');
  1610. self.getThumbs(' .kv-file-upload').removeAttr('disabled');
  1611. self.getThumbs(' .kv-file-delete').removeAttr('disabled');
  1612. };
  1613. $.each(files, function (key, data) {
  1614. if (!isEmpty(files[key])) {
  1615. self.formdata.append(self.uploadFileAttr, data);
  1616. }
  1617. });
  1618. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1619. },
  1620. uploadExtraOnly: function () {
  1621. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  1622. self.formdata = new FormData();
  1623. if (self.abort(params)) {
  1624. return;
  1625. }
  1626. fnBefore = function (jqXHR) {
  1627. self.lock();
  1628. var outData = self.getOutData(jqXHR);
  1629. self.raise('filebatchpreupload', [outData]);
  1630. self.setProgress(50);
  1631. params.data = outData;
  1632. params.xhr = jqXHR;
  1633. if (self.abort(params)) {
  1634. jqXHR.abort();
  1635. self.setProgress(100);
  1636. }
  1637. };
  1638. fnSuccess = function (data, textStatus, jqXHR) {
  1639. var outData = self.getOutData(jqXHR, data);
  1640. if (isEmpty(data) || isEmpty(data.error)) {
  1641. self.raise('filebatchuploadsuccess', [outData]);
  1642. self.clearFileInput();
  1643. self.initUploadSuccess(data);
  1644. } else {
  1645. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1646. }
  1647. };
  1648. fnComplete = function () {
  1649. self.setProgress(100);
  1650. self.unlock();
  1651. self.clearFileInput();
  1652. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1653. };
  1654. fnError = function (jqXHR, textStatus, errorThrown) {
  1655. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1656. params.data = outData;
  1657. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1658. };
  1659. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1660. },
  1661. hideFileIcon: function () {
  1662. if (this.overwriteInitial) {
  1663. this.$captionContainer.find('.kv-caption-icon').hide();
  1664. }
  1665. },
  1666. showFileIcon: function () {
  1667. this.$captionContainer.find('.kv-caption-icon').show();
  1668. },
  1669. addError: function (msg) {
  1670. var self = this, $error = self.$errorContainer;
  1671. if (msg && $error.length) {
  1672. $error.html(self.errorCloseButton + msg);
  1673. $error.find('.kv-error-close').off('click').on('click', function () {
  1674. $error.fadeOut('slow');
  1675. });
  1676. }
  1677. },
  1678. resetErrors: function (fade) {
  1679. var self = this, $error = self.$errorContainer;
  1680. self.isError = false;
  1681. self.$container.removeClass('has-error');
  1682. $error.html('');
  1683. if (fade) {
  1684. $error.fadeOut('slow');
  1685. } else {
  1686. $error.hide();
  1687. }
  1688. },
  1689. showFolderError: function (folders) {
  1690. var self = this, $error = self.$errorContainer;
  1691. if (!folders) {
  1692. return;
  1693. }
  1694. self.addError(self.msgFoldersNotAllowed.replace(/\{n\}/g, folders));
  1695. $error.fadeIn(800);
  1696. addCss(self.$container, 'has-error');
  1697. self.raise('filefoldererror', [folders]);
  1698. },
  1699. showUploadError: function (msg, params, event) {
  1700. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror',
  1701. e = params && params.id ? '<li data-file-id="' + params.id + '">' + msg + '</li>' : '<li>' + msg + '</li>';
  1702. if ($error.find('ul').length === 0) {
  1703. self.addError('<ul>' + e + '</ul>');
  1704. } else {
  1705. $error.find('ul').append(e);
  1706. }
  1707. $error.fadeIn(800);
  1708. self.raise(ev, [params]);
  1709. self.$container.removeClass('file-input-new');
  1710. addCss(self.$container, 'has-error');
  1711. return true;
  1712. },
  1713. showError: function (msg, params, event) {
  1714. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  1715. params = params || {};
  1716. params.reader = self.reader;
  1717. self.addError(msg);
  1718. $error.fadeIn(800);
  1719. self.raise(ev, [params]);
  1720. if (!self.isUploadable) {
  1721. self.clearFileInput();
  1722. }
  1723. self.$container.removeClass('file-input-new');
  1724. addCss(self.$container, 'has-error');
  1725. self.$btnUpload.attr('disabled', true);
  1726. return true;
  1727. },
  1728. errorHandler: function (evt, caption) {
  1729. var self = this, err = evt.target.error;
  1730. switch (err.code) {
  1731. case err.NOT_FOUND_ERR:
  1732. self.showError(self.msgFileNotFound.replace('{name}', caption));
  1733. break;
  1734. case err.SECURITY_ERR:
  1735. self.showError(self.msgFileSecured.replace('{name}', caption));
  1736. break;
  1737. case err.NOT_READABLE_ERR:
  1738. self.showError(self.msgFileNotReadable.replace('{name}', caption));
  1739. break;
  1740. case err.ABORT_ERR:
  1741. self.showError(self.msgFilePreviewAborted.replace('{name}', caption));
  1742. break;
  1743. default:
  1744. self.showError(self.msgFilePreviewError.replace('{name}', caption));
  1745. }
  1746. },
  1747. parseFileType: function (file) {
  1748. var self = this, isValid, vType, cat, i;
  1749. for (i = 0; i < defaultPreviewTypes.length; i += 1) {
  1750. cat = defaultPreviewTypes[i];
  1751. isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  1752. vType = isValid(file.type, file.name) ? cat : '';
  1753. if (!isEmpty(vType)) {
  1754. return vType;
  1755. }
  1756. }
  1757. return 'other';
  1758. },
  1759. previewDefault: function (file, previewId, isDisabled) {
  1760. if (!this.showPreview) {
  1761. return;
  1762. }
  1763. var self = this, data = objUrl.createObjectURL(file), frameClass = '', fname = file ? file.name : '',
  1764. config = self.previewSettings.other || defaultPreviewSettings.other,
  1765. footer = self.renderFileFooter(file.name, config.width),
  1766. ind = previewId.slice(previewId.lastIndexOf('-') + 1),
  1767. previewOtherTemplate = self.parseFilePreviewIcon(self.getPreviewTemplate('other'), fname);
  1768. if (isDisabled === true) {
  1769. frameClass = ' btn disabled';
  1770. if (!self.isUploadable) {
  1771. footer += '<div class="file-other-error" title="' + self.fileActionSettings.indicatorErrorTitle +
  1772. '">' + self.fileActionSettings.indicatorError + '</div>';
  1773. }
  1774. }
  1775. self.$preview.append("\n" + previewOtherTemplate
  1776. .replace(/\{previewId\}/g, previewId)
  1777. .replace(/\{frameClass\}/g, frameClass)
  1778. .replace(/\{fileindex\}/g, ind)
  1779. .replace(/\{caption\}/g, self.slug(file.name))
  1780. .replace(/\{width\}/g, config.width)
  1781. .replace(/\{height\}/g, config.height)
  1782. .replace(/\{type\}/g, file.type)
  1783. .replace(/\{data\}/g, data)
  1784. .replace(/\{footer\}/g, footer));
  1785. if (isDisabled === true && self.isUploadable) {
  1786. self.setThumbStatus($('#' + previewId), 'Error');
  1787. }
  1788. },
  1789. previewFile: function (i, file, theFile, previewId, data) {
  1790. if (!this.showPreview) {
  1791. return;
  1792. }
  1793. var self = this, cat = self.parseFileType(file), fname = file ? file.name : '', caption = self.slug(fname),
  1794. content, strText, types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes,
  1795. tmplt = self.getPreviewTemplate(cat), chkTypes = types && types.indexOf(cat) >= 0, id,
  1796. config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat],
  1797. chkMimes = mimes && mimes.indexOf(file.type) !== -1,
  1798. footer = self.renderFileFooter(caption, config.width), modal = '',
  1799. ind = previewId.slice(previewId.lastIndexOf('-') + 1);
  1800. if (chkTypes || chkMimes) {
  1801. tmplt = self.parseFilePreviewIcon(tmplt, fname.split('.').pop());
  1802. if (cat === 'text') {
  1803. strText = htmlEncode(theFile.target.result);
  1804. id = 'text-' + uniqId();
  1805. content = tmplt.replace(/\{zoom\}/g, self.getLayoutTemplate('zoom'));
  1806. modal = self.getLayoutTemplate('modal').replace('{id}', id)
  1807. .replace(/\{title\}/g, caption)
  1808. .replace(/\{body\}/g, strText).replace(/\{heading\}/g, self.msgZoomModalHeading);
  1809. content = content.replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption)
  1810. .replace(/\{width\}/g, config.width).replace(/\{height\}/g, config.height)
  1811. .replace(/\{frameClass\}/g, '').replace(/\{zoomInd\}/g, self.zoomIndicator)
  1812. .replace(/\{footer\}/g, footer).replace(/\{fileindex\}/g, ind)
  1813. .replace(/\{type\}/g, file.type).replace(/\{zoomTitle\}/g, self.msgZoomTitle)
  1814. .replace(/\{dialog\}/g, "$('#" + id + "').modal('show')")
  1815. .replace(/\{data\}/g, strText) + modal;
  1816. } else {
  1817. content = tmplt.replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption)
  1818. .replace(/\{frameClass\}/g, '').replace(/\{type\}/g, file.type).replace(/\{fileindex\}/g, ind)
  1819. .replace(/\{width\}/g, config.width).replace(/\{height\}/g, config.height)
  1820. .replace(/\{footer\}/g, footer).replace(/\{data\}/g, data);
  1821. }
  1822. self.$preview.append("\n" + content);
  1823. self.validateImage(i, previewId, caption);
  1824. } else {
  1825. self.previewDefault(file, previewId);
  1826. }
  1827. },
  1828. slugDefault: function (text) {
  1829. return isEmpty(text) ? '' : text.split(/(\\|\/)/g).pop().replace(/[^\w\u00C0-\u017F\-.\\\/ ]+/g, '');
  1830. },
  1831. getFileStack: function (skipNull) {
  1832. var self = this;
  1833. return self.filestack.filter(function (n) {
  1834. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  1835. });
  1836. },
  1837. readFiles: function (files) {
  1838. this.reader = new FileReader();
  1839. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  1840. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  1841. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  1842. settings = self.fileTypeSettings, ctr = self.filestack.length, readFile,
  1843. throwError = function (msg, file, previewId, index) {
  1844. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  1845. p2 = {id: previewId, index: index, file: file, files: files};
  1846. self.previewDefault(file, previewId, true);
  1847. if (self.isUploadable) {
  1848. self.filestack.push(undefined);
  1849. }
  1850. setTimeout(readFile(index + 1), 100);
  1851. self.initFileActions();
  1852. return self.isUploadable ? self.showUploadError(msg, p1) : self.showError(msg, p2);
  1853. };
  1854. readFile = function (i) {
  1855. if (isEmpty($el.attr('multiple'))) {
  1856. numFiles = 1;
  1857. }
  1858. if (i >= numFiles) {
  1859. if (self.isUploadable && self.filestack.length > 0) {
  1860. self.raise('filebatchselected', [self.getFileStack()]);
  1861. } else {
  1862. self.raise('filebatchselected', [files]);
  1863. }
  1864. $container.removeClass('loading');
  1865. $status.html('');
  1866. return;
  1867. }
  1868. var node = ctr + i, previewId = previewInitId + "-" + node, isText, file = files[i],
  1869. caption = self.slug(file.name), fileSize = (file.size || 0) / 1000, checkFile, fileExtExpr = '',
  1870. previewData = objUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk,
  1871. fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '),
  1872. fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', ');
  1873. if (!isEmpty(fileExt)) {
  1874. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  1875. }
  1876. fileSize = fileSize.toFixed(2);
  1877. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  1878. msg = self.msgSizeTooLarge.replace('{name}', caption)
  1879. .replace('{size}', fileSize)
  1880. .replace('{maxSize}', self.maxFileSize);
  1881. self.isError = throwError(msg, file, previewId, i);
  1882. return;
  1883. }
  1884. if (!isEmpty(fileTypes) && isArray(fileTypes)) {
  1885. for (j = 0; j < fileTypes.length; j += 1) {
  1886. typ = fileTypes[j];
  1887. checkFile = settings[typ];
  1888. chk = (checkFile !== undefined && checkFile(file.type, caption));
  1889. fileCount += isEmpty(chk) ? 0 : chk.length;
  1890. }
  1891. if (fileCount === 0) {
  1892. msg = self.msgInvalidFileType.replace('{name}', caption).replace('{types}', strTypes);
  1893. self.isError = throwError(msg, file, previewId, i);
  1894. return;
  1895. }
  1896. }
  1897. if (fileCount === 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) {
  1898. chk = caption.match(fileExtExpr);
  1899. fileCount += isEmpty(chk) ? 0 : chk.length;
  1900. if (fileCount === 0) {
  1901. msg = self.msgInvalidFileExtension.replace('{name}', caption).replace('{extensions}',
  1902. strExt);
  1903. self.isError = throwError(msg, file, previewId, i);
  1904. return;
  1905. }
  1906. }
  1907. if (!self.showPreview) {
  1908. self.filestack.push(file);
  1909. setTimeout(readFile(i + 1), 100);
  1910. self.raise('fileloaded', [file, previewId, i, reader]);
  1911. return;
  1912. }
  1913. if ($preview.length > 0 && FileReader !== undefined) {
  1914. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  1915. $container.addClass('loading');
  1916. reader.onerror = function (evt) {
  1917. self.errorHandler(evt, caption);
  1918. };
  1919. reader.onload = function (theFile) {
  1920. self.previewFile(i, file, theFile, previewId, previewData);
  1921. self.initFileActions();
  1922. };
  1923. reader.onloadend = function () {
  1924. msg = msgProgress
  1925. .replace('{index}', i + 1).replace('{files}', numFiles)
  1926. .replace('{percent}', 50).replace('{name}', caption);
  1927. setTimeout(function () {
  1928. $status.html(msg);
  1929. self.updateFileDetails(numFiles);
  1930. readFile(i + 1);
  1931. }, 100);
  1932. self.raise('fileloaded', [file, previewId, i, reader]);
  1933. };
  1934. reader.onprogress = function (data) {
  1935. if (data.lengthComputable) {
  1936. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  1937. msg = msgProgress.replace('{index}', i + 1).replace('{files}', numFiles)
  1938. .replace('{percent}', progress).replace('{name}', caption);
  1939. setTimeout(function () {
  1940. $status.html(msg);
  1941. }, 100);
  1942. }
  1943. };
  1944. isText = isSet('text', settings) ? settings.text : defaultFileTypeSettings.text;
  1945. if (isText(file.type, caption)) {
  1946. reader.readAsText(file, self.textEncoding);
  1947. } else {
  1948. reader.readAsArrayBuffer(file);
  1949. }
  1950. } else {
  1951. self.previewDefault(file, previewId);
  1952. setTimeout(function () {
  1953. readFile(i + 1);
  1954. self.updateFileDetails(numFiles);
  1955. }, 100);
  1956. self.raise('fileloaded', [file, previewId, i, reader]);
  1957. }
  1958. self.filestack.push(file);
  1959. }
  1960. readFile(0);
  1961. self.updateFileDetails(numFiles, false);
  1962. },
  1963. updateFileDetails: function (numFiles) {
  1964. var self = this, $el = self.$element, fileStack = self.getFileStack(),
  1965. name = $el.val() || (fileStack.length && fileStack[0].name) || '', label = self.slug(name),
  1966. n = self.isUploadable ? fileStack.length : numFiles,
  1967. nFiles = previewCache.count(self.id) + n,
  1968. log = n > 1 ? self.getMsgSelected(nFiles) : label;
  1969. if (self.isError) {
  1970. self.$previewContainer.removeClass('loading');
  1971. self.$previewStatus.html('');
  1972. self.$captionContainer.find('.kv-caption-icon').hide();
  1973. } else {
  1974. self.showFileIcon();
  1975. }
  1976. self.setCaption(log, self.isError);
  1977. self.$container.removeClass('file-input-new file-input-ajax-new');
  1978. if (arguments.length === 1) {
  1979. self.raise('fileselect', [numFiles, label]);
  1980. }
  1981. if (previewCache.count(self.id)) {
  1982. self.initPreviewDeletes();
  1983. }
  1984. },
  1985. validateMinCount: function () {
  1986. var self = this, len = self.isUploadable ? self.getFileStack().length : self.$element.get(0).files.length;
  1987. if (self.validateInitialCount && self.minFileCount > 0 && self.getFileCount(len - 1) < self.minFileCount) {
  1988. self.noFilesError({});
  1989. return false;
  1990. }
  1991. return true;
  1992. },
  1993. getFileCount: function (fileCount) {
  1994. var self = this, addCount = 0;
  1995. if (self.validateInitialCount && !self.overwriteInitial) {
  1996. addCount = previewCache.count(self.id);
  1997. fileCount += addCount;
  1998. }
  1999. return fileCount;
  2000. },
  2001. change: function (e) {
  2002. var self = this, $el = self.$element;
  2003. if (!self.isUploadable && isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix
  2004. self.fileInputCleared = false;
  2005. return;
  2006. }
  2007. self.fileInputCleared = false;
  2008. var tfiles, msg, total, isDragDrop = arguments.length > 1,
  2009. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files,
  2010. isSingleUpload = isEmpty($el.attr('multiple')), i = 0, f, n, folders = 0,
  2011. ctr = self.filestack.length, isAjaxUpload = self.isUploadable, len,
  2012. flagSingle = (isSingleUpload && ctr > 0),
  2013. throwError = function (mesg, file, previewId, index) {
  2014. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  2015. p2 = {id: previewId, index: index, file: file, files: files};
  2016. return self.isUploadable ? self.showUploadError(mesg, p1) : self.showError(mesg, p2);
  2017. };
  2018. self.reader = null;
  2019. self.resetUpload();
  2020. self.hideFileIcon();
  2021. if (self.isUploadable) {
  2022. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  2023. }
  2024. if (isDragDrop) {
  2025. tfiles = [];
  2026. while (files[i]) {
  2027. f = files[i];
  2028. if (!f.type && f.size % 4096 === 0) {
  2029. folders++;
  2030. } else {
  2031. tfiles.push(f);
  2032. }
  2033. i++;
  2034. }
  2035. } else {
  2036. if (e.target.files === undefined) {
  2037. tfiles = e.target && e.target.value ? [
  2038. {name: e.target.value.replace(/^.+\\/, '')}
  2039. ] : [];
  2040. } else {
  2041. tfiles = e.target.files;
  2042. }
  2043. }
  2044. if (isEmpty(tfiles) || tfiles.length === 0) {
  2045. if (!isAjaxUpload) {
  2046. self.clear();
  2047. }
  2048. self.showFolderError(folders);
  2049. self.raise('fileselectnone');
  2050. return;
  2051. }
  2052. self.resetErrors();
  2053. len = tfiles.length;
  2054. total = self.isUploadable ? self.getFileStack().length + len : len;
  2055. total = self.getFileCount(total);
  2056. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  2057. if (!self.autoReplace || len > self.maxFileCount) {
  2058. n = (self.autoReplace && len > self.maxFileCount) ? len : total;
  2059. msg = self.msgFilesTooMany.replace('{m}', self.maxFileCount).replace('{n}', n);
  2060. self.isError = throwError(msg, null, null, null);
  2061. self.$captionContainer.find('.kv-caption-icon').hide();
  2062. self.setCaption('', true);
  2063. self.$container.removeClass('file-input-new file-input-ajax-new');
  2064. return;
  2065. }
  2066. if (total > self.maxFileCount) {
  2067. self.resetPreviewThumbs(isAjaxUpload);
  2068. }
  2069. } else {
  2070. if (!isAjaxUpload || flagSingle) {
  2071. self.resetPreviewThumbs(false);
  2072. if (flagSingle) {
  2073. self.filestack = [];
  2074. }
  2075. } else {
  2076. if (isAjaxUpload && ctr === 0 && (!previewCache.count(self.id) || self.overwriteInitial)) {
  2077. self.resetPreviewThumbs(true);
  2078. }
  2079. }
  2080. }
  2081. if (self.isPreviewable) {
  2082. self.readFiles(tfiles);
  2083. } else {
  2084. self.updateFileDetails(1);
  2085. }
  2086. self.showFolderError(folders);
  2087. },
  2088. validateImage: function (i, previewId, fname) {
  2089. var self = this, $preview = self.$preview, params, w1, w2,
  2090. $thumb = $preview.find("#" + previewId), $img = $thumb.find('img');
  2091. fname = fname || 'Untitled';
  2092. if (!$img.length) {
  2093. return;
  2094. }
  2095. handler($img, 'load', function () {
  2096. w1 = $thumb.width();
  2097. w2 = $preview.width();
  2098. if (w1 > w2) {
  2099. $img.css('width', '100%');
  2100. $thumb.css('width', '97%');
  2101. }
  2102. params = {ind: i, id: previewId};
  2103. self.checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
  2104. self.checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
  2105. self.checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
  2106. self.checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
  2107. self.raise('fileimageloaded', [previewId]);
  2108. objUrl.revokeObjectURL($img.attr('src'));
  2109. });
  2110. },
  2111. checkDimensions: function (i, chk, $img, $thumb, fname, type, params) {
  2112. var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max',
  2113. limit = self[tag + 'Image' + type], $imgEl, isValid;
  2114. if (isEmpty(limit) || !$img.length) {
  2115. return;
  2116. }
  2117. $imgEl = $img[0];
  2118. dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height;
  2119. isValid = chk === 'Small' ? dim >= limit : dim <= limit;
  2120. if (isValid) {
  2121. return;
  2122. }
  2123. msg = self['msgImage' + type + chk].replace('{name}', fname).replace('{size}', limit);
  2124. self.showUploadError(msg, params);
  2125. self.setThumbStatus($thumb, 'Error');
  2126. self.filestack[i] = null;
  2127. },
  2128. initCaption: function () {
  2129. var self = this, cap = self.initialCaption || '';
  2130. if (self.overwriteInitial || isEmpty(cap)) {
  2131. self.$caption.html('');
  2132. return false;
  2133. }
  2134. self.setCaption(cap);
  2135. return true;
  2136. },
  2137. setCaption: function (content, isError) {
  2138. var self = this, title, out;
  2139. if (isError) {
  2140. title = $('<div>' + self.msgValidationError + '</div>').text();
  2141. out = '<span class="' + self.msgValidationErrorClass + '">' +
  2142. self.msgValidationErrorIcon + title + '</span>';
  2143. } else {
  2144. if (isEmpty(content) || self.$caption.length === 0) {
  2145. return;
  2146. }
  2147. title = $('<div>' + content + '</div>').text();
  2148. out = self.getLayoutTemplate('icon') + title;
  2149. }
  2150. self.$caption.html(out);
  2151. self.$caption.attr('title', title);
  2152. self.$captionContainer.find('.file-caption-ellipsis').attr('title', title);
  2153. },
  2154. initBrowse: function ($container) {
  2155. var self = this;
  2156. self.$btnFile = $container.find('.btn-file');
  2157. self.$btnFile.append(self.$element);
  2158. },
  2159. createContainer: function () {
  2160. var self = this,
  2161. $container = $(document.createElement("div"))
  2162. .attr({"class": 'file-input file-input-new'})
  2163. .html(self.renderMain());
  2164. self.$element.before($container);
  2165. self.initBrowse($container);
  2166. return $container;
  2167. },
  2168. refreshContainer: function () {
  2169. var self = this, $container = self.$container;
  2170. $container.before(self.$element);
  2171. $container.html(self.renderMain());
  2172. self.initBrowse($container);
  2173. },
  2174. renderMain: function () {
  2175. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : '',
  2176. preview = self.showPreview ? self.getLayoutTemplate('preview').replace(/\{class\}/g, self.previewClass)
  2177. .replace(/\{dropClass\}/g, dropCss) : '',
  2178. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  2179. caption = self.captionTemplate.replace(/\{class\}/g, css + ' kv-fileinput-caption');
  2180. return self.mainTemplate.replace(/\{class\}/g, self.mainClass)
  2181. .replace(/\{preview\}/g, preview)
  2182. .replace(/\{caption\}/g, caption)
  2183. .replace(/\{upload\}/g, self.renderButton('upload'))
  2184. .replace(/\{remove\}/g, self.renderButton('remove'))
  2185. .replace(/\{cancel\}/g, self.renderButton('cancel'))
  2186. .replace(/\{browse\}/g, self.renderButton('browse'));
  2187. },
  2188. renderButton: function (type) {
  2189. var self = this, tmplt = self.getLayoutTemplate('btnDefault'), css = self[type + 'Class'],
  2190. title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'],
  2191. status = self.isDisabled ? ' disabled' : '', btnType = 'button';
  2192. switch (type) {
  2193. case 'remove':
  2194. if (!self.showRemove) {
  2195. return '';
  2196. }
  2197. break;
  2198. case 'cancel':
  2199. if (!self.showCancel) {
  2200. return '';
  2201. }
  2202. css += ' hide';
  2203. break;
  2204. case 'upload':
  2205. if (!self.showUpload) {
  2206. return '';
  2207. }
  2208. if (self.isUploadable && !self.isDisabled) {
  2209. tmplt = self.getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl);
  2210. } else {
  2211. btnType = 'submit';
  2212. }
  2213. break;
  2214. case 'browse':
  2215. tmplt = self.getLayoutTemplate('btnBrowse');
  2216. break;
  2217. default:
  2218. return '';
  2219. }
  2220. css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button';
  2221. return tmplt.replace('{type}', btnType)
  2222. .replace('{css}', css)
  2223. .replace('{title}', title)
  2224. .replace('{status}', status)
  2225. .replace('{icon}', icon)
  2226. .replace('{label}', label);
  2227. }
  2228. };
  2229. //FileInput plugin definition
  2230. $.fn.fileinput = function (option) {
  2231. if (!hasFileAPISupport() && !isIE(9)) {
  2232. return;
  2233. }
  2234. var args = Array.apply(null, arguments), retvals = [];
  2235. args.shift();
  2236. this.each(function () {
  2237. var $this = $(this), data = $this.data('fileinput'), defaults,
  2238. options = typeof option === 'object' && option,
  2239. lang = options.language || $this.data('language') || 'en';
  2240. if (!data) {
  2241. defaults = $.extend({}, $.fn.fileinput.defaults);
  2242. if (lang !== 'en' && !isEmpty($.fn.fileinputLocales[lang])) {
  2243. defaults = $.extend(defaults, $.fn.fileinputLocales[lang]);
  2244. }
  2245. data = new FileInput(this, $.extend(defaults, options, $this.data()));
  2246. $this.data('fileinput', data);
  2247. }
  2248. if (typeof option === 'string') {
  2249. retvals.push(data[option].apply(data, args));
  2250. }
  2251. });
  2252. switch (retvals.length) {
  2253. case 0:
  2254. return this;
  2255. case 1:
  2256. return retvals[0];
  2257. default:
  2258. return retvals;
  2259. }
  2260. };
  2261. $.fn.fileinput.defaults = {
  2262. language: 'en',
  2263. showCaption: true,
  2264. showPreview: true,
  2265. showRemove: true,
  2266. showUpload: true,
  2267. showCancel: true,
  2268. showUploadedThumbs: true,
  2269. autoReplace: false,
  2270. mainClass: '',
  2271. previewClass: '',
  2272. captionClass: '',
  2273. mainTemplate: null,
  2274. initialCaption: '',
  2275. initialPreview: [],
  2276. initialPreviewDelimiter: '*$$*',
  2277. initialPreviewConfig: [],
  2278. initialPreviewThumbTags: [],
  2279. previewThumbTags: {},
  2280. initialPreviewShowDelete: true,
  2281. deleteUrl: '',
  2282. deleteExtraData: {},
  2283. overwriteInitial: true,
  2284. layoutTemplates: defaultLayoutTemplates,
  2285. previewTemplates: defaultPreviewTemplates,
  2286. allowedPreviewTypes: defaultPreviewTypes,
  2287. allowedPreviewMimeTypes: null,
  2288. allowedFileTypes: null,
  2289. allowedFileExtensions: null,
  2290. customLayoutTags: {},
  2291. customPreviewTags: {},
  2292. previewSettings: defaultPreviewSettings,
  2293. fileTypeSettings: defaultFileTypeSettings,
  2294. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  2295. previewFileIconClass: 'file-icon-4x',
  2296. previewFileIconSettings: {},
  2297. previewFileExtSettings: {},
  2298. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  2299. browseClass: 'btn btn-primary',
  2300. removeIcon: '<i class="glyphicon glyphicon-trash"></i> ',
  2301. removeClass: 'btn btn-default',
  2302. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  2303. cancelClass: 'btn btn-default',
  2304. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  2305. uploadClass: 'btn btn-default',
  2306. uploadUrl: null,
  2307. uploadAsync: true,
  2308. uploadExtraData: {},
  2309. minImageWidth: null,
  2310. minImageHeight: null,
  2311. maxImageWidth: null,
  2312. maxImageHeight: null,
  2313. maxFileSize: 0,
  2314. minFileCount: 0,
  2315. maxFileCount: 0,
  2316. validateInitialCount: false,
  2317. msgValidationErrorClass: 'text-danger',
  2318. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  2319. msgErrorClass: 'file-error-message',
  2320. progressClass: "progress-bar progress-bar-success progress-bar-striped active",
  2321. progressCompleteClass: "progress-bar progress-bar-success",
  2322. previewFileType: 'image',
  2323. zoomIndicator: '<i class="glyphicon glyphicon-zoom-in"></i>',
  2324. elCaptionContainer: null,
  2325. elCaptionText: null,
  2326. elPreviewContainer: null,
  2327. elPreviewImage: null,
  2328. elPreviewStatus: null,
  2329. elErrorContainer: null,
  2330. errorCloseButton: '<span class="close kv-error-close">&times;</span>',
  2331. slugCallback: null,
  2332. dropZoneEnabled: true,
  2333. dropZoneTitleClass: 'file-drop-zone-title',
  2334. fileActionSettings: {},
  2335. otherActionButtons: '',
  2336. textEncoding: 'UTF-8',
  2337. ajaxSettings: {},
  2338. ajaxDeleteSettings: {},
  2339. showAjaxErrorDetails: true
  2340. };
  2341. $.fn.fileinputLocales.en = {
  2342. fileSingle: 'file',
  2343. filePlural: 'files',
  2344. browseLabel: 'Browse &hellip;',
  2345. removeLabel: 'Remove',
  2346. removeTitle: 'Clear selected files',
  2347. cancelLabel: 'Cancel',
  2348. cancelTitle: 'Abort ongoing upload',
  2349. uploadLabel: 'Upload',
  2350. uploadTitle: 'Upload selected files',
  2351. msgZoomTitle: 'View details',
  2352. msgZoomModalHeading: 'Detailed Preview',
  2353. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
  2354. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
  2355. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
  2356. msgFileNotFound: 'File "{name}" not found!',
  2357. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  2358. msgFileNotReadable: 'File "{name}" is not readable.',
  2359. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  2360. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  2361. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  2362. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  2363. msgUploadAborted: 'The file upload was aborted',
  2364. msgValidationError: 'File Upload Error',
  2365. msgLoading: 'Loading file {index} of {files} &hellip;',
  2366. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  2367. msgSelected: '{n} {files} selected',
  2368. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  2369. msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
  2370. msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
  2371. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
  2372. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
  2373. dropZoneTitle: 'Drag & drop files here &hellip;'
  2374. };
  2375. $.extend($.fn.fileinput.defaults, $.fn.fileinputLocales.en);
  2376. $.fn.fileinput.Constructor = FileInput;
  2377. /**
  2378. * Convert automatically file inputs with class 'file'
  2379. * into a bootstrap fileinput control.
  2380. */
  2381. $(document).ready(function () {
  2382. var $input = $('input.file[type=file]');
  2383. if ($input.length) {
  2384. $input.fileinput();
  2385. }
  2386. });
  2387. })(window.jQuery);