fileinput.js 96 KB

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