fileinput.js 100 KB

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