fileinput.js 123 KB

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