fileinput.js 98 KB

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