fileinput.js 96 KB

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