fileinput.js 99 KB

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