fileinput.js 146 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228
  1. /*!
  2. * bootstrap-fileinput v4.3.2
  3. * http://plugins.krajee.com/file-input
  4. *
  5. * Author: Kartik Visweswaran
  6. * Copyright: 2014 - 2016, Kartik Visweswaran, Krajee.com
  7. *
  8. * Licensed under the BSD 3-Clause
  9. * https://github.com/kartik-v/bootstrap-fileinput/blob/master/LICENSE.md
  10. */
  11. (function (factory) {
  12. "use strict";
  13. if (typeof define === 'function' && define.amd) { // jshint ignore:line
  14. // AMD. Register as an anonymous module.
  15. define(['jquery'], factory); // jshint ignore:line
  16. } else { // noinspection JSUnresolvedVariable
  17. if (typeof module === 'object' && module.exports) { // jshint ignore:line
  18. // Node/CommonJS
  19. // noinspection JSUnresolvedVariable
  20. module.exports = factory(require('jquery')); // jshint ignore:line
  21. } else {
  22. // Browser globals
  23. factory(window.jQuery);
  24. }
  25. }
  26. }(function ($) {
  27. "use strict";
  28. $.fn.fileinputLocales = {};
  29. $.fn.fileinputThemes = {};
  30. var NAMESPACE, MODAL_ID, STYLE_SETTING, OBJECT_PARAMS, DEFAULT_PREVIEW, objUrl, compare, isIE, isEdge, handler,
  31. previewCache, getNum, hasFileAPISupport, hasDragDropSupport, hasFileUploadSupport, addCss, tMain1, tMain2,
  32. tPreview, tFileIcon, tClose, tCaption, tBtnDefault, tBtnLink, tBtnBrowse, tModalMain, tModal, tProgress, tSize,
  33. tFooter, tActions, tActionDelete, tActionUpload, tActionZoom, tActionDrag, tTagBef, tTagBef1, tTagBef2, tTagAft,
  34. tGeneric, tHtml, tImage, tText, tVideo, tAudio, tFlash, tObject, tPdf, tOther, defaultFileActionSettings,
  35. defaultLayoutTemplates, defaultPreviewTemplates, defaultPreviewZoomSettings, defaultPreviewTypes, getElement,
  36. defaultPreviewSettings, defaultFileTypeSettings, isEmpty, isArray, ifSet, uniqId, htmlEncode, replaceTags,
  37. cleanMemory, findFileName, checkFullScreen, toggleFullScreen, moveArray, FileInput;
  38. NAMESPACE = '.fileinput';
  39. MODAL_ID = 'kvFileinputModal';
  40. STYLE_SETTING = 'style="width:{width};height:{height};"';
  41. OBJECT_PARAMS = '<param name="controller" value="true" />\n' +
  42. '<param name="allowFullScreen" value="true" />\n' +
  43. '<param name="allowScriptAccess" value="always" />\n' +
  44. '<param name="autoPlay" value="false" />\n' +
  45. '<param name="autoStart" value="false" />\n' +
  46. '<param name="quality" value="high" />\n';
  47. DEFAULT_PREVIEW = '<div class="file-preview-other">\n' +
  48. '<span class="{previewFileIconClass}">{previewFileIcon}</span>\n' +
  49. '</div>';
  50. //noinspection JSUnresolvedVariable
  51. objUrl = window.URL || window.webkitURL;
  52. compare = function (input, str, exact) {
  53. return input !== undefined && (exact ? input === str : input.match(str));
  54. };
  55. isIE = function (ver) {
  56. // check for IE versions < 11
  57. if (navigator.appName !== 'Microsoft Internet Explorer') {
  58. return false;
  59. }
  60. if (ver === 10) {
  61. return new RegExp('msie\\s' + ver, 'i').test(navigator.userAgent);
  62. }
  63. var div = document.createElement("div"), status;
  64. div.innerHTML = "<!--[if IE " + ver + "]> <i></i> <![endif]-->";
  65. status = div.getElementsByTagName("i").length;
  66. document.body.appendChild(div);
  67. div.parentNode.removeChild(div);
  68. return status;
  69. };
  70. isEdge = function () {
  71. return new RegExp('Edge\/[0-9]+', 'i').test(navigator.userAgent);
  72. };
  73. handler = function ($el, event, callback, skipNS) {
  74. var ev = skipNS ? event : event.split(' ').join(NAMESPACE + ' ') + NAMESPACE;
  75. $el.off(ev).on(ev, callback);
  76. };
  77. previewCache = {
  78. data: {},
  79. init: function (obj) {
  80. var content = obj.initialPreview, id = obj.id;
  81. if (content.length > 0 && !isArray(content)) {
  82. content = content.split(obj.initialPreviewDelimiter);
  83. }
  84. previewCache.data[id] = {
  85. content: content,
  86. config: obj.initialPreviewConfig,
  87. tags: obj.initialPreviewThumbTags,
  88. delimiter: obj.initialPreviewDelimiter,
  89. previewFileType: obj.initialPreviewFileType,
  90. previewAsData: obj.initialPreviewAsData,
  91. template: obj.previewGenericTemplate,
  92. showZoom: obj.fileActionSettings.showZoom,
  93. showDrag: obj.fileActionSettings.showDrag,
  94. getSize: function(size) {
  95. return obj._getSize(size);
  96. },
  97. parseTemplate: function (cat, data, fname, ftype, pId, ftr, ind, size) {
  98. var fc = ' file-preview-initial';
  99. return obj._generatePreviewTemplate(cat, data, fname, ftype, pId, false, null, fc, ftr, ind);
  100. },
  101. msg: function (n) {
  102. return obj._getMsgSelected(n);
  103. },
  104. initId: obj.previewInitId,
  105. footer: obj._getLayoutTemplate('footer').replace(/\{progress}/g, obj._renderThumbProgress()),
  106. isDelete: obj.initialPreviewShowDelete,
  107. caption: obj.initialCaption,
  108. actions: function (showUpload, showDelete, showZoom, showDrag, disabled, url, key) {
  109. return obj._renderFileActions(showUpload, showDelete, showZoom, showDrag, disabled, url, key, true);
  110. }
  111. };
  112. },
  113. fetch: function (id) {
  114. return previewCache.data[id].content.filter(function (n) {
  115. return n !== null;
  116. });
  117. },
  118. count: function (id, all) {
  119. return !!previewCache.data[id] && !!previewCache.data[id].content ?
  120. (all ? previewCache.data[id].content.length : previewCache.fetch(id).length) : 0;
  121. },
  122. get: function (id, i, isDisabled) {
  123. var ind = 'init_' + i, data = previewCache.data[id], config = data.config[i], content = data.content[i],
  124. previewId = data.initId + '-' + ind, out, $tmp, frameClass = ' file-preview-initial', cat, cap, ftr,
  125. ftype, asData = ifSet('previewAsData', config, data.previewAsData);
  126. isDisabled = isDisabled === undefined ? true : isDisabled;
  127. /** @namespace config.frameAttr */
  128. /** @namespace config.frameClass */
  129. /** @namespace config.filetype */
  130. if (!content) {
  131. return '';
  132. }
  133. if (config && config.frameClass) {
  134. frameClass += ' ' + config.frameClass;
  135. }
  136. if (asData) {
  137. cat = data.previewAsData ? ifSet('type', config, data.previewFileType || 'generic') : 'generic';
  138. cap = ifSet('caption', config);
  139. ftr = previewCache.footer(id, i, isDisabled, (config && config.size || null));
  140. ftype = ifSet('filetype', config, cat);
  141. out = data.parseTemplate(cat, content, cap, ftype, previewId, ftr, ind, null);
  142. } else {
  143. out = data.template
  144. .replace(/\{previewId}/g, previewId).replace(/\{frameClass}/g, frameClass)
  145. .replace(/\{fileindex}/g, ind).replace(/\{content}/g, data.content[i])
  146. .replace(/\{template}/g, ifSet('type', config, data.previewFileType))
  147. .replace(/\{footer}/g, previewCache.footer(id, i, isDisabled, (config && config.size || null)));
  148. }
  149. if (data.tags.length && data.tags[i]) {
  150. out = replaceTags(out, data.tags[i]);
  151. }
  152. if (!isEmpty(config) && !isEmpty(config.frameAttr)) {
  153. $tmp = $(document.createElement('div')).html(out);
  154. $tmp.find('.file-preview-initial').attr(config.frameAttr);
  155. out = $tmp.html();
  156. $tmp.remove();
  157. }
  158. return out;
  159. },
  160. add: function (id, content, config, tags, append) {
  161. var data = $.extend(true, {}, previewCache.data[id]), index;
  162. if (!isArray(content)) {
  163. content = content.split(data.delimiter);
  164. }
  165. if (append) {
  166. index = data.content.push(content) - 1;
  167. data.config[index] = config;
  168. data.tags[index] = tags;
  169. } else {
  170. index = content.length - 1;
  171. data.content = content;
  172. data.config = config;
  173. data.tags = tags;
  174. }
  175. previewCache.data[id] = data;
  176. return index;
  177. },
  178. set: function (id, content, config, tags, append) {
  179. var data = $.extend(true, {}, previewCache.data[id]), i, chk;
  180. if (!content || !content.length) {
  181. return;
  182. }
  183. if (!isArray(content)) {
  184. content = content.split(data.delimiter);
  185. }
  186. chk = content.filter(function (n) {
  187. return n !== null;
  188. });
  189. if (!chk.length) {
  190. return;
  191. }
  192. if (data.content === undefined) {
  193. data.content = [];
  194. }
  195. if (data.config === undefined) {
  196. data.config = [];
  197. }
  198. if (data.tags === undefined) {
  199. data.tags = [];
  200. }
  201. if (append) {
  202. for (i = 0; i < content.length; i++) {
  203. if (content[i]) {
  204. data.content.push(content[i]);
  205. }
  206. }
  207. for (i = 0; i < config.length; i++) {
  208. if (config[i]) {
  209. data.config.push(config[i]);
  210. }
  211. }
  212. for (i = 0; i < tags.length; i++) {
  213. if (tags[i]) {
  214. data.tags.push(tags[i]);
  215. }
  216. }
  217. } else {
  218. data.content = content;
  219. data.config = config;
  220. data.tags = tags;
  221. }
  222. previewCache.data[id] = data;
  223. },
  224. unset: function (id, index) {
  225. var chk = previewCache.count(id);
  226. if (!chk) {
  227. return;
  228. }
  229. if (chk === 1) {
  230. previewCache.data[id].content = [];
  231. previewCache.data[id].config = [];
  232. previewCache.data[id].tags = [];
  233. return;
  234. }
  235. previewCache.data[id].content[index] = null;
  236. previewCache.data[id].config[index] = null;
  237. previewCache.data[id].tags[index] = null;
  238. },
  239. out: function (id) {
  240. var html = '', data = previewCache.data[id], caption, len = previewCache.count(id, true);
  241. if (len === 0) {
  242. return {content: '', caption: ''};
  243. }
  244. for (var i = 0; i < len; i++) {
  245. html += previewCache.get(id, i);
  246. }
  247. caption = data.msg(previewCache.count(id));
  248. return {content: '<div class="file-initial-thumbs">' + html + '</div>', caption: caption};
  249. },
  250. footer: function (id, i, isDisabled, size) {
  251. var data = previewCache.data[id];
  252. isDisabled = isDisabled === undefined ? true : isDisabled;
  253. if (data.config.length === 0 || isEmpty(data.config[i])) {
  254. return '';
  255. }
  256. var config = data.config[i], caption = ifSet('caption', config), width = ifSet('width', config, 'auto'),
  257. url = ifSet('url', config, false), key = ifSet('key', config, null),
  258. showDel = ifSet('showDelete', config, true), showZoom = ifSet('showZoom', config, data.showZoom),
  259. showDrag = ifSet('showDrag', config, data.showDrag), disabled = (url === false) && isDisabled,
  260. actions = data.isDelete ? data.actions(false, showDel, showZoom, showDrag, disabled, url, key) : '',
  261. footer = data.footer.replace(/\{actions}/g, actions);
  262. return footer.replace(/\{caption}/g, caption).replace(/\{size}/g, data.getSize(size))
  263. .replace(/\{width}/g, width).replace(/\{indicator}/g, '').replace(/\{indicatorTitle}/g, '');
  264. }
  265. };
  266. getNum = function (num, def) {
  267. def = def || 0;
  268. if (typeof num === "number") {
  269. return num;
  270. }
  271. if (typeof num === "string") {
  272. num = parseFloat(num);
  273. }
  274. return isNaN(num) ? def : num;
  275. };
  276. hasFileAPISupport = function () {
  277. return !!(window.File && window.FileReader);
  278. };
  279. hasDragDropSupport = function () {
  280. var div = document.createElement('div');
  281. /** @namespace div.draggable */
  282. /** @namespace div.ondragstart */
  283. /** @namespace div.ondrop */
  284. return !isIE(9) && !isEdge() && // Fix for MS Edge drag & drop support bug
  285. (div.draggable !== undefined || (div.ondragstart !== undefined && div.ondrop !== undefined));
  286. };
  287. hasFileUploadSupport = function () {
  288. return hasFileAPISupport() && window.FormData;
  289. };
  290. addCss = function ($el, css) {
  291. $el.removeClass(css).addClass(css);
  292. };
  293. defaultFileActionSettings = {
  294. showRemove: true,
  295. showUpload: true,
  296. showZoom: true,
  297. showDrag: true,
  298. removeIcon: '<i class="glyphicon glyphicon-trash text-danger"></i>',
  299. removeClass: 'btn btn-xs btn-default',
  300. removeTitle: 'Remove file',
  301. uploadIcon: '<i class="glyphicon glyphicon-upload text-info"></i>',
  302. uploadClass: 'btn btn-xs btn-default',
  303. uploadTitle: 'Upload file',
  304. zoomIcon: '<i class="glyphicon glyphicon-zoom-in"></i>',
  305. zoomClass: 'btn btn-xs btn-default',
  306. zoomTitle: 'View Details',
  307. dragIcon: '<i class="glyphicon glyphicon-menu-hamburger"></i>',
  308. dragClass: 'text-info',
  309. dragTitle: 'Move / Rearrange',
  310. dragSettings: {},
  311. indicatorNew: '<i class="glyphicon glyphicon-hand-down text-warning"></i>',
  312. indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign text-success"></i>',
  313. indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>',
  314. indicatorLoading: '<i class="glyphicon glyphicon-hand-up text-muted"></i>',
  315. indicatorNewTitle: 'Not uploaded yet',
  316. indicatorSuccessTitle: 'Uploaded',
  317. indicatorErrorTitle: 'Upload Error',
  318. indicatorLoadingTitle: 'Uploading ...'
  319. };
  320. tMain1 = '{preview}\n' +
  321. '<div class="kv-upload-progress hide"></div>\n' +
  322. '<div class="input-group {class}">\n' +
  323. ' {caption}\n' +
  324. ' <div class="input-group-btn">\n' +
  325. ' {remove}\n' +
  326. ' {cancel}\n' +
  327. ' {upload}\n' +
  328. ' {browse}\n' +
  329. ' </div>\n' +
  330. '</div>';
  331. tMain2 = '{preview}\n<div class="kv-upload-progress hide"></div>\n{remove}\n{cancel}\n{upload}\n{browse}\n';
  332. tPreview = '<div class="file-preview {class}">\n' +
  333. ' {close}' +
  334. ' <div class="{dropClass}">\n' +
  335. ' <div class="file-preview-thumbnails">\n' +
  336. ' </div>\n' +
  337. ' <div class="clearfix"></div>' +
  338. ' <div class="file-preview-status text-center text-success"></div>\n' +
  339. ' <div class="kv-fileinput-error"></div>\n' +
  340. ' </div>\n' +
  341. '</div>';
  342. tClose = '<div class="close fileinput-remove">&times;</div>\n';
  343. tFileIcon = '<i class="glyphicon glyphicon-file kv-caption-icon"></i>';
  344. tCaption = '<div tabindex="500" class="form-control file-caption {class}">\n' +
  345. ' <div class="file-caption-name"></div>\n' +
  346. '</div>\n';
  347. //noinspection HtmlUnknownAttribute
  348. tBtnDefault = '<button type="{type}" tabindex="500" title="{title}" class="{css}" {status}>{icon} {label}</button>';
  349. tBtnLink = '<a href="{href}" tabindex="500" title="{title}" class="{css}" {status}>{icon} {label}</a>';
  350. tBtnBrowse = '<div tabindex="500" class="{css}" {status}>{icon} {label}</div>';
  351. tModalMain = '<div id="' + MODAL_ID + '" class="file-zoom-dialog modal fade" tabindex="-1" aria-labelledby="' +
  352. MODAL_ID + 'Label"></div>';
  353. tModal = '<div class="modal-dialog modal-lg" role="document">\n' +
  354. ' <div class="modal-content">\n' +
  355. ' <div class="modal-header">\n' +
  356. ' <div class="kv-zoom-actions pull-right">{toggleheader}{fullscreen}{borderless}{close}</div>\n' +
  357. ' <h3 class="modal-title">{heading} <small><span class="kv-zoom-title"></span></small></h3>\n' +
  358. ' </div>\n' +
  359. ' <div class="modal-body">\n' +
  360. ' <div class="floating-buttons"></div>\n' +
  361. ' <div class="kv-zoom-body file-zoom-content"></div>\n' + '{prev} {next}\n' +
  362. ' </div>\n' +
  363. ' </div>\n' +
  364. '</div>\n';
  365. tProgress = '<div class="progress">\n' +
  366. ' <div class="{class}" role="progressbar"' +
  367. ' aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' +
  368. ' {percent}%\n' +
  369. ' </div>\n' +
  370. '</div>';
  371. tSize = ' <br><samp>({sizeText})</samp>';
  372. tFooter = '<div class="file-thumbnail-footer">\n' +
  373. ' <div class="file-footer-caption" title="{caption}">{caption}{size}</div>\n' +
  374. ' {progress} {actions}\n' +
  375. '</div>';
  376. tActions = '<div class="file-actions">\n' +
  377. ' <div class="file-footer-buttons">\n' +
  378. ' {upload} {delete} {zoom} {other}' +
  379. ' </div>\n' +
  380. ' {drag}\n' +
  381. ' <div class="file-upload-indicator" title="{indicatorTitle}">{indicator}</div>\n' +
  382. ' <div class="clearfix"></div>\n' +
  383. '</div>';
  384. tActionDelete = '<button type="button" class="kv-file-remove {removeClass}" ' +
  385. 'title="{removeTitle}" {dataUrl}{dataKey}>{removeIcon}</button>\n';
  386. tActionUpload = '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">' +
  387. '{uploadIcon}</button>';
  388. tActionZoom = '<button type="button" class="kv-file-zoom {zoomClass}" title="{zoomTitle}">{zoomIcon}</button>';
  389. tActionDrag = '<span class="file-drag-handle {dragClass}" title="{dragTitle}">{dragIcon}</span>';
  390. tTagBef = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  391. ' data-template="{template}"';
  392. tTagBef1 = tTagBef + '><div class="kv-file-content">\n';
  393. tTagBef2 = tTagBef + ' title="{caption}" ' + STYLE_SETTING + '><div class="kv-file-content">\n';
  394. tTagAft = '</div>{footer}\n</div>\n';
  395. tGeneric = '{content}\n';
  396. tHtml = '<div class="kv-preview-data file-preview-html" title="{caption}" ' + STYLE_SETTING + '>{data}</div>\n';
  397. tImage = '<img src="{data}" class="kv-preview-data file-preview-image" title="{caption}" alt="{caption}" ' +
  398. STYLE_SETTING + '>\n';
  399. tText = '<textarea class="kv-preview-data file-preview-text" title="{caption}" readonly ' + STYLE_SETTING +
  400. '>{data}</textarea>\n';
  401. tVideo = '<video class="kv-preview-data" width="{width}" height="{height}" controls>\n' +
  402. '<source src="{data}" type="{type}">\n' + DEFAULT_PREVIEW + '\n</video>\n';
  403. tAudio = '<audio class="kv-preview-data" controls>\n<source src="' + '{data}' + '" type="{type}">\n' +
  404. DEFAULT_PREVIEW + '\n</audio>\n';
  405. tFlash = '<object class="kv-preview-data file-object" type="application/x-shockwave-flash" ' +
  406. 'width="{width}" height="{height}" data="{data}">\n' + OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n</object>\n';
  407. tObject = '<object class="kv-preview-data file-object" data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  408. '<param name="movie" value="{caption}" />\n' + OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n</object>\n';
  409. tPdf = '<embed class="kv-preview-data" src="{data}" width="{width}" height="{height}" type="application/pdf">\n';
  410. tOther = '<div class="kv-preview-data file-preview-other-frame">\n' + DEFAULT_PREVIEW + '\n</div>\n';
  411. defaultLayoutTemplates = {
  412. main1: tMain1,
  413. main2: tMain2,
  414. preview: tPreview,
  415. close: tClose,
  416. fileIcon: tFileIcon,
  417. caption: tCaption,
  418. modalMain: tModalMain,
  419. modal: tModal,
  420. progress: tProgress,
  421. size: tSize,
  422. footer: tFooter,
  423. actions: tActions,
  424. actionDelete: tActionDelete,
  425. actionUpload: tActionUpload,
  426. actionZoom: tActionZoom,
  427. actionDrag: tActionDrag,
  428. btnDefault: tBtnDefault,
  429. btnLink: tBtnLink,
  430. btnBrowse: tBtnBrowse
  431. };
  432. defaultPreviewTemplates = {
  433. generic: tTagBef1 + tGeneric + tTagAft,
  434. html: tTagBef1 + tHtml + tTagAft,
  435. image: tTagBef1 + tImage + tTagAft,
  436. text: tTagBef1 + tText + tTagAft,
  437. video: tTagBef2 + tVideo + tTagAft,
  438. audio: tTagBef2 + tAudio + tTagAft,
  439. flash: tTagBef2 + tFlash + tTagAft,
  440. object: tTagBef2 + tObject + tTagAft,
  441. pdf: tTagBef2 + tPdf + tTagAft,
  442. other: tTagBef2 + tOther + tTagAft
  443. };
  444. defaultPreviewTypes = ['image', 'html', 'text', 'video', 'audio', 'flash', 'object'];
  445. defaultPreviewSettings = {
  446. image: {width: "auto", height: "160px"},
  447. html: {width: "213px", height: "160px"},
  448. text: {width: "213px", height: "160px"},
  449. video: {width: "213px", height: "160px"},
  450. audio: {width: "213px", height: "80px"},
  451. flash: {width: "213px", height: "160px"},
  452. object: {width: "160px", height: "160px"},
  453. pdf: {width: "160px", height: "160px"},
  454. other: {width: "160px", height: "160px"}
  455. };
  456. defaultPreviewZoomSettings = {
  457. image: {width: "auto", height: "100%"},
  458. html: {width: "100%", height: "100%", 'min-height': "480px"},
  459. text: {width: "100%", height: "100%", 'min-height': "480px"},
  460. video: {width: "auto", height: "100%", 'max-width': "100%"},
  461. audio: {width: "100%", height: "30px"},
  462. flash: {width: "auto", height: "480px"},
  463. object: {width: "auto", height: "480px"},
  464. pdf: {width: "100%", height: "100%", 'min-height': "480px"},
  465. other: {width: "auto", height: "100%", 'min-height': "480px"}
  466. };
  467. defaultFileTypeSettings = {
  468. image: function (vType, vName) {
  469. return compare(vType, 'image.*') || compare(vName, /\.(gif|png|jpe?g)$/i);
  470. },
  471. html: function (vType, vName) {
  472. return compare(vType, 'text/html') || compare(vName, /\.(htm|html)$/i);
  473. },
  474. text: function (vType, vName) {
  475. return compare(vType, 'text.*') || compare(vType, /\.(xml|javascript)$/i) ||
  476. compare(vName, /\.(txt|md|csv|nfo|ini|json|php|js|css)$/i);
  477. },
  478. video: function (vType, vName) {
  479. return compare(vType, 'video.*') && (compare(vType, /(ogg|mp4|mp?g|webm|3gp)$/i) ||
  480. compare(vName, /\.(og?|mp4|webm|mp?g|3gp)$/i));
  481. },
  482. audio: function (vType, vName) {
  483. return compare(vType, 'audio.*') && (compare(vType, /(ogg|mp3|mp?g|wav)$/i) ||
  484. compare(vName, /\.(og?|mp3|mp?g|wav)$/i));
  485. },
  486. flash: function (vType, vName) {
  487. return compare(vType, 'application/x-shockwave-flash', true) || compare(vName, /\.(swf)$/i);
  488. },
  489. pdf: function (vType, vName) {
  490. return compare(vType, 'application/pdf', true) || compare(vName, /\.(pdf)$/i);
  491. },
  492. object: function () {
  493. return true;
  494. },
  495. other: function () {
  496. return true;
  497. }
  498. };
  499. isEmpty = function (value, trim) {
  500. return value === undefined || value === null || value.length === 0 || (trim && $.trim(value) === '');
  501. };
  502. isArray = function (a) {
  503. return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]';
  504. };
  505. ifSet = function (needle, haystack, def) {
  506. def = def || '';
  507. return (typeof haystack === 'object' && needle in haystack) ? haystack[needle] : def;
  508. };
  509. getElement = function (options, param, value) {
  510. return (isEmpty(options) || isEmpty(options[param])) ? value : $(options[param]);
  511. };
  512. uniqId = function () {
  513. return Math.round(new Date().getTime() + (Math.random() * 100));
  514. };
  515. htmlEncode = function (str) {
  516. return str.replace(/&/g, '&amp;')
  517. .replace(/</g, '&lt;')
  518. .replace(/>/g, '&gt;')
  519. .replace(/"/g, '&quot;')
  520. .replace(/'/g, '&apos;');
  521. };
  522. replaceTags = function (str, tags) {
  523. var out = str;
  524. if (!tags) {
  525. return out;
  526. }
  527. $.each(tags, function (key, value) {
  528. if (typeof value === "function") {
  529. value = value();
  530. }
  531. out = out.split(key).join(value);
  532. });
  533. return out;
  534. };
  535. cleanMemory = function ($thumb) {
  536. var data = $thumb.is('img') ? $thumb.attr('src') : $thumb.find('source').attr('src');
  537. /** @namespace objUrl.revokeObjectURL */
  538. objUrl.revokeObjectURL(data);
  539. };
  540. findFileName = function (filePath) {
  541. var sepIndex = filePath.lastIndexOf('/');
  542. if (sepIndex === -1) {
  543. sepIndex = filePath.lastIndexOf('\\');
  544. }
  545. return filePath.split(filePath.substring(sepIndex, sepIndex + 1)).pop();
  546. };
  547. checkFullScreen = function () {
  548. //noinspection JSUnresolvedVariable
  549. return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement ||
  550. document.msFullscreenElement;
  551. };
  552. toggleFullScreen = function (maximize) {
  553. if (maximize && !checkFullScreen()) {
  554. /** @namespace document.documentElement.requestFullscreen */
  555. /** @namespace document.documentElement.msRequestFullscreen */
  556. /** @namespace document.documentElement.mozRequestFullScreen */
  557. /** @namespace document.documentElement.webkitRequestFullscreen */
  558. /** @namespace Element.ALLOW_KEYBOARD_INPUT */
  559. if (document.documentElement.requestFullscreen) {
  560. document.documentElement.requestFullscreen();
  561. } else if (document.documentElement.msRequestFullscreen) {
  562. document.documentElement.msRequestFullscreen();
  563. } else if (document.documentElement.mozRequestFullScreen) {
  564. document.documentElement.mozRequestFullScreen();
  565. } else if (document.documentElement.webkitRequestFullscreen) {
  566. document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
  567. }
  568. } else {
  569. /** @namespace document.exitFullscreen */
  570. /** @namespace document.msExitFullscreen */
  571. /** @namespace document.mozCancelFullScreen */
  572. /** @namespace document.webkitExitFullscreen */
  573. if (document.exitFullscreen) {
  574. document.exitFullscreen();
  575. } else if (document.msExitFullscreen) {
  576. document.msExitFullscreen();
  577. } else if (document.mozCancelFullScreen) {
  578. document.mozCancelFullScreen();
  579. } else if (document.webkitExitFullscreen) {
  580. document.webkitExitFullscreen();
  581. }
  582. }
  583. };
  584. moveArray = function (arr, oldIndex, newIndex) {
  585. if (newIndex >= arr.length) {
  586. var k = newIndex - arr.length;
  587. while ((k--) + 1) {
  588. arr.push(undefined);
  589. }
  590. }
  591. arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]);
  592. return arr;
  593. };
  594. FileInput = function (element, options) {
  595. var self = this;
  596. self.$element = $(element);
  597. if (!self._validate()) {
  598. return;
  599. }
  600. self.isPreviewable = hasFileAPISupport();
  601. self.isIE9 = isIE(9);
  602. self.isIE10 = isIE(10);
  603. if (self.isPreviewable || self.isIE9) {
  604. self._init(options);
  605. self._listen();
  606. } else {
  607. self.$element.removeClass('file-loading');
  608. }
  609. };
  610. FileInput.prototype = {
  611. constructor: FileInput,
  612. _init: function (options) {
  613. var self = this, $el = self.$element, t;
  614. $.each(options, function (key, value) {
  615. switch (key) {
  616. case 'minFileCount':
  617. case 'maxFileCount':
  618. case 'maxFileSize':
  619. self[key] = getNum(value);
  620. break;
  621. default:
  622. self[key] = value;
  623. break;
  624. }
  625. });
  626. if (isEmpty(self.allowedPreviewTypes)) {
  627. self.allowedPreviewTypes = defaultPreviewTypes;
  628. }
  629. self.fileInputCleared = false;
  630. self.fileBatchCompleted = true;
  631. if (!self.isPreviewable) {
  632. self.showPreview = false;
  633. }
  634. self.uploadFileAttr = !isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data';
  635. self.reader = null;
  636. self.formdata = {};
  637. self.clearStack();
  638. self.uploadCount = 0;
  639. self.uploadStatus = {};
  640. self.uploadLog = [];
  641. self.uploadAsyncCount = 0;
  642. self.loadedImages = [];
  643. self.totalImagesCount = 0;
  644. self.ajaxRequests = [];
  645. self.isError = false;
  646. self.ajaxAborted = false;
  647. self.cancelling = false;
  648. t = self._getLayoutTemplate('progress');
  649. self.progressTemplate = t.replace('{class}', self.progressClass);
  650. self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass);
  651. self.progressErrorTemplate = t.replace('{class}', self.progressErrorClass);
  652. self.dropZoneEnabled = hasDragDropSupport() && self.dropZoneEnabled;
  653. self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly');
  654. self.isUploadable = hasFileUploadSupport() && !isEmpty(self.uploadUrl);
  655. self.slug = typeof options.slugCallback === "function" ? options.slugCallback : self._slugDefault;
  656. self.mainTemplate = self.showCaption ? self._getLayoutTemplate('main1') : self._getLayoutTemplate('main2');
  657. self.captionTemplate = self._getLayoutTemplate('caption');
  658. self.previewGenericTemplate = self._getPreviewTemplate('generic');
  659. if (self.resizeImage && (self.maxImageWidth || self.maxImageHeight)) {
  660. self.imageCanvas = document.createElement('canvas');
  661. self.imageCanvasContext = self.imageCanvas.getContext('2d');
  662. }
  663. if (isEmpty(self.$element.attr('id'))) {
  664. self.$element.attr('id', uniqId());
  665. }
  666. if (self.$container === undefined) {
  667. self.$container = self._createContainer();
  668. } else {
  669. self._refreshContainer();
  670. }
  671. self.$dropZone = self.$container.find('.file-drop-zone');
  672. self.$progress = self.$container.find('.kv-upload-progress');
  673. self.$btnUpload = self.$container.find('.fileinput-upload');
  674. self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption'));
  675. self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name'));
  676. self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview'));
  677. self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails'));
  678. self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status'));
  679. self.$errorContainer = getElement(options, 'elErrorContainer',
  680. self.$previewContainer.find('.kv-fileinput-error'));
  681. if (!isEmpty(self.msgErrorClass)) {
  682. addCss(self.$errorContainer, self.msgErrorClass);
  683. }
  684. self.$errorContainer.hide();
  685. self.fileActionSettings = $.extend(true, defaultFileActionSettings, options.fileActionSettings);
  686. self.previewInitId = "preview-" + uniqId();
  687. self.id = self.$element.attr('id');
  688. previewCache.init(self);
  689. self._initPreview(true);
  690. self._initPreviewActions();
  691. self.options = options;
  692. self._setFileDropZoneTitle();
  693. self.$element.removeClass('file-loading');
  694. if (self.$element.attr('disabled')) {
  695. self.disable();
  696. }
  697. self._initZoom();
  698. },
  699. _validate: function () {
  700. var self = this, $exception;
  701. if (self.$element.attr('type') === 'file') {
  702. return true;
  703. }
  704. $exception = '<div class="help-block alert alert-warning">' +
  705. '<h4>Invalid Input Type</h4>' +
  706. 'You must set an input <code>type = file</code> for <b>bootstrap-fileinput</b> plugin to initialize.' +
  707. '</div>';
  708. self.$element.after($exception);
  709. return false;
  710. },
  711. _errorsExist: function () {
  712. var self = this, $err;
  713. if (self.$errorContainer.find('li').length) {
  714. return true;
  715. }
  716. $err = $(document.createElement('div')).html(self.$errorContainer.html());
  717. $err.find('span.kv-error-close').remove();
  718. $err.find('ul').remove();
  719. return $.trim($err.text()).length ? true : false;
  720. },
  721. _errorHandler: function (evt, caption) {
  722. var self = this, err = evt.target.error;
  723. /** @namespace err.NOT_FOUND_ERR */
  724. /** @namespace err.SECURITY_ERR */
  725. /** @namespace err.NOT_READABLE_ERR */
  726. if (err.code === err.NOT_FOUND_ERR) {
  727. self._showError(self.msgFileNotFound.replace('{name}', caption));
  728. } else if (err.code === err.SECURITY_ERR) {
  729. self._showError(self.msgFileSecured.replace('{name}', caption));
  730. } else if (err.code === err.NOT_READABLE_ERR) {
  731. self._showError(self.msgFileNotReadable.replace('{name}', caption));
  732. } else if (err.code === err.ABORT_ERR) {
  733. self._showError(self.msgFilePreviewAborted.replace('{name}', caption));
  734. } else {
  735. self._showError(self.msgFilePreviewError.replace('{name}', caption));
  736. }
  737. },
  738. _addError: function (msg) {
  739. var self = this, $error = self.$errorContainer;
  740. if (msg && $error.length) {
  741. $error.html(self.errorCloseButton + msg);
  742. handler($error.find('.kv-error-close'), 'click', function () {
  743. $error.fadeOut('slow');
  744. });
  745. }
  746. },
  747. _resetErrors: function (fade) {
  748. var self = this, $error = self.$errorContainer;
  749. self.isError = false;
  750. self.$container.removeClass('has-error');
  751. $error.html('');
  752. if (fade) {
  753. $error.fadeOut('slow');
  754. } else {
  755. $error.hide();
  756. }
  757. },
  758. _showFolderError: function (folders) {
  759. var self = this, $error = self.$errorContainer, msg;
  760. if (!folders) {
  761. return;
  762. }
  763. msg = self.msgFoldersNotAllowed.replace(/\{n}/g, folders);
  764. self._addError(msg);
  765. addCss(self.$container, 'has-error');
  766. $error.fadeIn(800);
  767. self._raise('filefoldererror', [folders, msg]);
  768. },
  769. _showUploadError: function (msg, params, event) {
  770. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror', e = params && params.id ?
  771. '<li data-file-id="' + params.id + '">' + msg + '</li>' : '<li>' + msg + '</li>';
  772. if ($error.find('ul').length === 0) {
  773. self._addError('<ul>' + e + '</ul>');
  774. } else {
  775. $error.find('ul').append(e);
  776. }
  777. $error.fadeIn(800);
  778. self._raise(ev, [params, msg]);
  779. self.$container.removeClass('file-input-new');
  780. addCss(self.$container, 'has-error');
  781. return true;
  782. },
  783. _showError: function (msg, params, event) {
  784. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  785. params = params || {};
  786. params.reader = self.reader;
  787. self._addError(msg);
  788. $error.fadeIn(800);
  789. self._raise(ev, [params, msg]);
  790. if (!self.isUploadable) {
  791. self._clearFileInput();
  792. }
  793. self.$container.removeClass('file-input-new');
  794. addCss(self.$container, 'has-error');
  795. self.$btnUpload.attr('disabled', true);
  796. return true;
  797. },
  798. _noFilesError: function (params) {
  799. var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle,
  800. msg = self.msgFilesTooLess.replace('{n}', self.minFileCount).replace('{files}', label),
  801. $error = self.$errorContainer;
  802. self._addError(msg);
  803. self.isError = true;
  804. self._updateFileDetails(0);
  805. $error.fadeIn(800);
  806. self._raise('fileerror', [params, msg]);
  807. self._clearFileInput();
  808. addCss(self.$container, 'has-error');
  809. },
  810. _parseError: function (jqXHR, errorThrown, fileName) {
  811. /** @namespace jqXHR.responseJSON */
  812. var self = this, errMsg = $.trim(errorThrown + ''),
  813. dot = errMsg.slice(-1) === '.' ? '' : '.',
  814. text = jqXHR.responseJSON !== undefined && jqXHR.responseJSON.error !== undefined ?
  815. jqXHR.responseJSON.error : jqXHR.responseText;
  816. if (self.cancelling && self.msgUploadAborted) {
  817. errMsg = self.msgUploadAborted;
  818. }
  819. if (self.showAjaxErrorDetails && text) {
  820. text = $.trim(text.replace(/\n\s*\n/g, '\n'));
  821. text = text.length > 0 ? '<pre>' + text + '</pre>' : '';
  822. errMsg += dot + text;
  823. } else {
  824. errMsg += dot;
  825. }
  826. self.cancelling = false;
  827. return fileName ? '<b>' + fileName + ': </b>' + errMsg : errMsg;
  828. },
  829. _parseFileType: function (file) {
  830. var self = this, isValid, vType, cat, i;
  831. for (i = 0; i < defaultPreviewTypes.length; i += 1) {
  832. cat = defaultPreviewTypes[i];
  833. isValid = ifSet(cat, self.fileTypeSettings, defaultFileTypeSettings[cat]);
  834. vType = isValid(file.type, file.name) ? cat : '';
  835. if (!isEmpty(vType)) {
  836. return vType;
  837. }
  838. }
  839. return 'other';
  840. },
  841. _parseFilePreviewIcon: function (content, fname) {
  842. var self = this, ext, icn = self.previewFileIcon;
  843. if (fname && fname.indexOf('.') > -1) {
  844. ext = fname.split('.').pop();
  845. if (self.previewFileIconSettings && self.previewFileIconSettings[ext]) {
  846. icn = self.previewFileIconSettings[ext];
  847. }
  848. if (self.previewFileExtSettings) {
  849. $.each(self.previewFileExtSettings, function (key, func) {
  850. if (self.previewFileIconSettings[key] && func(ext)) {
  851. icn = self.previewFileIconSettings[key];
  852. return;
  853. }
  854. });
  855. }
  856. }
  857. if (content.indexOf('{previewFileIcon}') > -1) {
  858. return content.replace(/\{previewFileIconClass}/g, self.previewFileIconClass).replace(
  859. /\{previewFileIcon}/g, icn);
  860. }
  861. return content;
  862. },
  863. _raise: function (event, params) {
  864. var self = this, e = $.Event(event);
  865. if (params !== undefined) {
  866. self.$element.trigger(e, params);
  867. } else {
  868. self.$element.trigger(e);
  869. }
  870. if (e.isDefaultPrevented()) {
  871. return false;
  872. }
  873. if (!e.result) {
  874. return e.result;
  875. }
  876. switch (event) {
  877. // ignore these events
  878. case 'filebatchuploadcomplete':
  879. case 'filebatchuploadsuccess':
  880. case 'fileuploaded':
  881. case 'fileclear':
  882. case 'filecleared':
  883. case 'filereset':
  884. case 'fileerror':
  885. case 'filefoldererror':
  886. case 'fileuploaderror':
  887. case 'filebatchuploaderror':
  888. case 'filedeleteerror':
  889. case 'filecustomerror':
  890. case 'filesuccessremove':
  891. break;
  892. // receive data response via `filecustomerror` event`
  893. default:
  894. self.ajaxAborted = e.result;
  895. break;
  896. }
  897. return true;
  898. },
  899. _listenFullScreen: function (isFullScreen) {
  900. var self = this, $modal = self.$modal, $btnFull, $btnBord;
  901. if (!$modal || !$modal.length) {
  902. return;
  903. }
  904. $btnFull = $modal && $modal.find('.btn-fullscreen');
  905. $btnBord = $modal && $modal.find('.btn-borderless');
  906. if (!$btnFull.length || !$btnBord.length) {
  907. return;
  908. }
  909. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  910. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  911. if (isFullScreen) {
  912. $btnFull.addClass('active').attr('aria-pressed', 'true');
  913. } else {
  914. $btnBord.addClass('active').attr('aria-pressed', 'true');
  915. }
  916. if ($modal.hasClass('file-zoom-fullscreen')) {
  917. self._maximizeZoomDialog();
  918. } else {
  919. if (isFullScreen) {
  920. self._maximizeZoomDialog();
  921. } else {
  922. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  923. }
  924. }
  925. },
  926. _listen: function () {
  927. var self = this, $el = self.$element, $form = $el.closest('form'), $cont = self.$container;
  928. handler($el, 'change', $.proxy(self._change, self));
  929. handler(self.$btnFile, 'click', $.proxy(self._browse, self));
  930. handler($form, 'reset', $.proxy(self.reset, self));
  931. handler($cont.find('.fileinput-remove:not([disabled])'), 'click', $.proxy(self.clear, self));
  932. handler($cont.find('.fileinput-cancel'), 'click', $.proxy(self.cancel, self));
  933. self._initDragDrop();
  934. if (!self.isUploadable) {
  935. handler($form, 'submit', $.proxy(self._submitForm, self));
  936. }
  937. handler(self.$container.find('.fileinput-upload'), 'click', $.proxy(self._uploadClick, self));
  938. handler($(window), 'resize', function () {
  939. self._listenFullScreen(screen.width === window.innerWidth && screen.height === window.innerHeight);
  940. });
  941. handler($(document), 'webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange',
  942. function () {
  943. self._listenFullScreen(checkFullScreen());
  944. });
  945. },
  946. _initDragDrop: function () {
  947. var self = this, $zone = self.$dropZone;
  948. if (self.isUploadable && self.dropZoneEnabled && self.showPreview) {
  949. handler($zone, 'dragenter dragover', $.proxy(self._zoneDragEnter, self));
  950. handler($zone, 'dragleave', $.proxy(self._zoneDragLeave, self));
  951. handler($zone, 'drop', $.proxy(self._zoneDrop, self));
  952. handler($(document), 'dragenter dragover drop', self._zoneDragDropInit);
  953. }
  954. },
  955. _zoneDragDropInit: function (e) {
  956. e.stopPropagation();
  957. e.preventDefault();
  958. },
  959. _zoneDragEnter: function (e) {
  960. var self = this, hasFiles = $.inArray('Files', e.originalEvent.dataTransfer.types) > -1;
  961. self._zoneDragDropInit(e);
  962. if (self.isDisabled || !hasFiles) {
  963. e.originalEvent.dataTransfer.effectAllowed = 'none';
  964. e.originalEvent.dataTransfer.dropEffect = 'none';
  965. return;
  966. }
  967. addCss(self.$dropZone, 'file-highlighted');
  968. },
  969. _zoneDragLeave: function (e) {
  970. var self = this;
  971. self._zoneDragDropInit(e);
  972. if (self.isDisabled) {
  973. return;
  974. }
  975. self.$dropZone.removeClass('file-highlighted');
  976. },
  977. _zoneDrop: function (e) {
  978. var self = this;
  979. e.preventDefault();
  980. /** @namespace e.originalEvent.dataTransfer */
  981. if (self.isDisabled || isEmpty(e.originalEvent.dataTransfer.files)) {
  982. return;
  983. }
  984. self._change(e, 'dragdrop');
  985. self.$dropZone.removeClass('file-highlighted');
  986. },
  987. _uploadClick: function (e) {
  988. var self = this, $btn = self.$container.find('.fileinput-upload'), $form,
  989. isEnabled = !$btn.hasClass('disabled') && isEmpty($btn.attr('disabled'));
  990. if (e && e.isDefaultPrevented()) {
  991. return;
  992. }
  993. if (!self.isUploadable) {
  994. if (isEnabled && $btn.attr('type') !== 'submit') {
  995. $form = $btn.closest('form');
  996. // downgrade to normal form submit if possible
  997. if ($form.length) {
  998. $form.trigger('submit');
  999. }
  1000. e.preventDefault();
  1001. }
  1002. return;
  1003. }
  1004. e.preventDefault();
  1005. if (isEnabled) {
  1006. self.upload();
  1007. }
  1008. },
  1009. _submitForm: function () {
  1010. var self = this, $el = self.$element, files = $el.get(0).files;
  1011. if (files && self.minFileCount > 0 && self._getFileCount(files.length) < self.minFileCount) {
  1012. self._noFilesError({});
  1013. return false;
  1014. }
  1015. return !self._abort({});
  1016. },
  1017. _clearPreview: function () {
  1018. var self = this, $thumbs = !self.showUploadedThumbs ? self.$preview.find('.file-preview-frame') :
  1019. self.$preview.find('.file-preview-frame:not(.file-preview-success)');
  1020. $thumbs.remove();
  1021. if (!self.$preview.find('.file-preview-frame').length || !self.showPreview) {
  1022. self._resetUpload();
  1023. }
  1024. self._validateDefaultPreview();
  1025. },
  1026. _initSortable: function () {
  1027. var self = this, $preview = self.$preview, $el, settings;
  1028. if (!window.Sortable) {
  1029. return;
  1030. }
  1031. $el = $preview.find('.file-initial-thumbs');
  1032. settings = {
  1033. handle: '.drag-handle-init',
  1034. dataIdAttr: 'data-preview-id',
  1035. onSort: function (e) {
  1036. var oldIndex = e.oldIndex, newIndex = e.newIndex;
  1037. self.initialPreview = moveArray(self.initialPreview, oldIndex, newIndex);
  1038. self.initialPreviewConfig = moveArray(self.initialPreviewConfig, oldIndex, newIndex);
  1039. previewCache.init(self);
  1040. self._raise('filesorted', {
  1041. previewId: $(e.item).attr('id'),
  1042. 'oldIndex': oldIndex,
  1043. 'newIndex': newIndex,
  1044. stack: self.initialPreviewConfig
  1045. });
  1046. }
  1047. };
  1048. if ($el.data('sortable')) {
  1049. $el.sortable('destroy');
  1050. }
  1051. $.extend(true, settings, self.fileActionSettings.dragSettings);
  1052. $el.sortable(settings);
  1053. },
  1054. _initPreview: function (isInit) {
  1055. var self = this, cap = self.initialCaption || '', out;
  1056. if (!previewCache.count(self.id)) {
  1057. self._clearPreview();
  1058. if (isInit) {
  1059. self._setCaption(cap);
  1060. } else {
  1061. self._initCaption();
  1062. }
  1063. return;
  1064. }
  1065. out = previewCache.out(self.id);
  1066. cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
  1067. self.$preview.html(out.content);
  1068. self._setCaption(cap);
  1069. self._initSortable();
  1070. if (!isEmpty(out.content)) {
  1071. self.$container.removeClass('file-input-new');
  1072. }
  1073. },
  1074. _getZoomButton: function (type) {
  1075. var self = this, label = self.previewZoomButtonIcons[type], css = self.previewZoomButtonClasses[type],
  1076. title = ' title="' + (self.previewZoomButtonTitles[type] || '') + '" ',
  1077. params = title + (type === 'close' ? ' data-dismiss="modal" aria-hidden="true"' : '');
  1078. if (type === 'fullscreen' || type === 'borderless' || type === 'toggleheader') {
  1079. params += ' data-toggle="button" aria-pressed="false" autocomplete="off"';
  1080. }
  1081. return '<button type="button" class="' + css + ' btn-' + type + '"' + params + '>' + label + '</button>';
  1082. },
  1083. _getModalContent: function () {
  1084. var self = this;
  1085. return self._getLayoutTemplate('modal')
  1086. .replace(/\{heading}/g, self.msgZoomModalHeading)
  1087. .replace(/\{prev}/g, self._getZoomButton('prev'))
  1088. .replace(/\{next}/g, self._getZoomButton('next'))
  1089. .replace(/\{toggleheader}/g, self._getZoomButton('toggleheader'))
  1090. .replace(/\{fullscreen}/g, self._getZoomButton('fullscreen'))
  1091. .replace(/\{borderless}/g, self._getZoomButton('borderless'))
  1092. .replace(/\{close}/g, self._getZoomButton('close'));
  1093. },
  1094. _listenModalEvent: function (event) {
  1095. var self = this, $modal = self.$modal, getParams = function (e) {
  1096. return {
  1097. sourceEvent: e,
  1098. previewId: $modal.data('previewId'),
  1099. modal: $modal
  1100. };
  1101. };
  1102. $modal.on(event + '.bs.modal', function (e) {
  1103. var $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless');
  1104. self._raise('filezoom' + event, getParams(e));
  1105. if (event === 'shown') {
  1106. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1107. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  1108. if ($modal.hasClass('file-zoom-fullscreen')) {
  1109. self._maximizeZoomDialog();
  1110. if (checkFullScreen()) {
  1111. $btnFull.addClass('active').attr('aria-pressed', 'true');
  1112. } else {
  1113. $btnBord.addClass('active').attr('aria-pressed', 'true');
  1114. }
  1115. }
  1116. }
  1117. });
  1118. },
  1119. _initZoom: function () {
  1120. var self = this, $dialog, modalMain = self._getLayoutTemplate('modalMain'), modalId = '#' + MODAL_ID;
  1121. self.$modal = $(modalId);
  1122. if (!self.$modal || !self.$modal.length) {
  1123. $dialog = $(document.createElement('div')).html(modalMain).insertAfter(self.$container);
  1124. self.$modal = $('#' + MODAL_ID).insertBefore($dialog);
  1125. $dialog.remove();
  1126. }
  1127. self.$modal.html(self._getModalContent());
  1128. self._listenModalEvent('show');
  1129. self._listenModalEvent('shown');
  1130. self._listenModalEvent('hide');
  1131. self._listenModalEvent('hidden');
  1132. self._listenModalEvent('loaded');
  1133. },
  1134. _initZoomButtons: function () {
  1135. var self = this, previewId = self.$modal.data('previewId') || '', $first, $last,
  1136. frames = self.$preview.find('.file-preview-frame').toArray(), len = frames.length,
  1137. $prev = self.$modal.find('.btn-prev'), $next = self.$modal.find('.btn-next');
  1138. if (!len) {
  1139. return;
  1140. }
  1141. $first = $(frames[0]);
  1142. $last = $(frames[len - 1]);
  1143. $prev.removeAttr('disabled');
  1144. $next.removeAttr('disabled');
  1145. if ($first.length && $first.attr('id') === previewId) {
  1146. $prev.attr('disabled', true);
  1147. }
  1148. if ($last.length && $last.attr('id') === previewId) {
  1149. $next.attr('disabled', true);
  1150. }
  1151. },
  1152. _maximizeZoomDialog: function () {
  1153. var self = this, $modal = self.$modal, $head = $modal.find('.modal-header:visible'),
  1154. $foot = $modal.find('.modal-footer:visible'), $body = $modal.find('.modal-body'),
  1155. h = $(window).height(), diff = 0;
  1156. $modal.addClass('file-zoom-fullscreen');
  1157. if ($head && $head.length) {
  1158. h -= $head.outerHeight(true);
  1159. }
  1160. if ($foot && $foot.length) {
  1161. h -= $foot.outerHeight(true);
  1162. }
  1163. if ($body && $body.length) {
  1164. diff = $body.outerHeight(true) - $body.height();
  1165. h -= diff;
  1166. }
  1167. $modal.find('.kv-zoom-body').height(h);
  1168. },
  1169. _resizeZoomDialog: function (fullScreen) {
  1170. var self = this, $modal = self.$modal, $btnFull = $modal.find('.btn-fullscreen'),
  1171. $btnBord = $modal.find('.btn-borderless');
  1172. if ($modal.hasClass('file-zoom-fullscreen')) {
  1173. toggleFullScreen(false);
  1174. if (!fullScreen) {
  1175. if (!$btnFull.hasClass('active')) {
  1176. $modal.removeClass('file-zoom-fullscreen');
  1177. self.$modal.find('.kv-zoom-body').css('height', self.zoomModalHeight);
  1178. } else {
  1179. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  1180. }
  1181. } else {
  1182. if (!$btnFull.hasClass('active')) {
  1183. $modal.removeClass('file-zoom-fullscreen');
  1184. self._resizeZoomDialog(true);
  1185. if ($btnBord.hasClass('active')) {
  1186. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1187. }
  1188. }
  1189. }
  1190. } else {
  1191. if (!fullScreen) {
  1192. self._maximizeZoomDialog();
  1193. return;
  1194. }
  1195. toggleFullScreen(true);
  1196. }
  1197. $modal.focus();
  1198. },
  1199. _setZoomContent: function ($preview, animate) {
  1200. var self = this, $content, tmplt, body, title, $body, $dataEl, config, previewId = $preview.attr('id'),
  1201. $modal = self.$modal, $prev = $modal.find('.btn-prev'), $next = $modal.find('.btn-next'), $tmp,
  1202. $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless'),
  1203. $btnTogh = $modal.find('.btn-toggleheader');
  1204. tmplt = $preview.data('template') || 'generic';
  1205. $content = $preview.find('.kv-file-content');
  1206. body = $content.length ? $content.html() : '';
  1207. title = $preview.find('.file-footer-caption').text() || '';
  1208. $modal.find('.kv-zoom-title').html(title);
  1209. $body = $modal.find('.kv-zoom-body');
  1210. if (animate) {
  1211. $tmp = $body.clone().insertAfter($body);
  1212. $body.html(body).hide();
  1213. $tmp.fadeOut('fast', function () {
  1214. $body.fadeIn('fast');
  1215. $tmp.remove();
  1216. });
  1217. } else {
  1218. $body.html(body);
  1219. }
  1220. config = self.previewZoomSettings[tmplt];
  1221. if (config) {
  1222. $dataEl = $body.find('.kv-preview-data');
  1223. addCss($dataEl, 'file-zoom-detail');
  1224. $.each(config, function (key, value) {
  1225. $dataEl.css(key, value);
  1226. if (($dataEl.attr('width') && key === 'width') || ($dataEl.attr('height') && key === 'height')) {
  1227. $dataEl.removeAttr(key);
  1228. }
  1229. });
  1230. }
  1231. $modal.data('previewId', previewId);
  1232. handler($prev, 'click', function () {
  1233. self._zoomSlideShow('prev', previewId);
  1234. });
  1235. handler($next, 'click', function () {
  1236. self._zoomSlideShow('next', previewId);
  1237. });
  1238. handler($btnFull, 'click', function () {
  1239. self._resizeZoomDialog(true);
  1240. });
  1241. handler($btnBord, 'click', function () {
  1242. self._resizeZoomDialog(false);
  1243. });
  1244. handler($btnTogh, 'click', function () {
  1245. var $header = $modal.find('.modal-header'), $floatBar = $modal.find('.modal-body .floating-buttons'),
  1246. ht, $actions = $header.find('.kv-zoom-actions'), resize = function (height) {
  1247. var $body = self.$modal.find('.kv-zoom-body'), h = self.zoomModalHeight;
  1248. if ($modal.hasClass('file-zoom-fullscreen')) {
  1249. h = $body.outerHeight(true);
  1250. if (!height) {
  1251. h = h - $header.outerHeight(true);
  1252. }
  1253. }
  1254. $body.css('height', height ? h + height : h);
  1255. };
  1256. if ($header.is(':visible')) {
  1257. ht = $header.outerHeight(true);
  1258. $header.slideUp('slow', function () {
  1259. $actions.find('.btn').appendTo($floatBar);
  1260. resize(ht);
  1261. });
  1262. } else {
  1263. $floatBar.find('.btn').appendTo($actions);
  1264. $header.slideDown('slow', function () {
  1265. resize();
  1266. });
  1267. }
  1268. $modal.focus();
  1269. });
  1270. handler($modal, 'keydown', function (e) {
  1271. var key = e.which || e.keyCode;
  1272. if (key === 37 && !$prev.attr('disabled')) {
  1273. self._zoomSlideShow('prev', previewId);
  1274. }
  1275. if (key === 39 && !$next.attr('disabled')) {
  1276. self._zoomSlideShow('next', previewId);
  1277. }
  1278. });
  1279. },
  1280. _zoomPreview: function ($btn) {
  1281. var self = this, $preview;
  1282. if (!$btn.length) {
  1283. throw 'Cannot zoom to detailed preview!';
  1284. }
  1285. self.$modal.html(self._getModalContent());
  1286. $preview = $btn.closest('.file-preview-frame');
  1287. self._setZoomContent($preview);
  1288. self.$modal.modal('show');
  1289. self._initZoomButtons();
  1290. },
  1291. _zoomSlideShow: function (dir, previewId) {
  1292. var self = this, $btn = self.$modal.find('.kv-zoom-actions .btn-' + dir), $targFrame, i,
  1293. frames = self.$preview.find('.file-preview-frame').toArray(), len = frames.length, out;
  1294. if ($btn.attr('disabled')) {
  1295. return;
  1296. }
  1297. for (i = 0; i < len; i++) {
  1298. if ($(frames[i]).attr('id') === previewId) {
  1299. out = dir === 'prev' ? i - 1 : i + 1;
  1300. break;
  1301. }
  1302. }
  1303. if (out < 0 || out >= len || !frames[out]) {
  1304. return;
  1305. }
  1306. $targFrame = $(frames[out]);
  1307. if ($targFrame.length) {
  1308. self._setZoomContent($targFrame, true);
  1309. }
  1310. self._initZoomButtons();
  1311. self._raise('filezoom' + dir, {'previewId': previewId, modal: self.$modal});
  1312. },
  1313. _initZoomButton: function () {
  1314. var self = this;
  1315. self.$preview.find('.kv-file-zoom').each(function () {
  1316. var $el = $(this);
  1317. handler($el, 'click', function () {
  1318. self._zoomPreview($el);
  1319. });
  1320. });
  1321. },
  1322. _initPreviewActions: function () {
  1323. var self = this, deleteExtraData = self.deleteExtraData || {},
  1324. resetProgress = function () {
  1325. var hasFiles = self.isUploadable ? previewCache.count(self.id) : self.$element.get(0).files.length;
  1326. if (self.$preview.find('.kv-file-remove').length === 0 && !hasFiles) {
  1327. self.reset();
  1328. self.initialCaption = '';
  1329. }
  1330. };
  1331. self._initZoomButton();
  1332. self.$preview.find('.kv-file-remove').each(function () {
  1333. var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key');
  1334. if (isEmpty(vUrl) || vKey === undefined) {
  1335. return;
  1336. }
  1337. var $frame = $el.closest('.file-preview-frame'), cache = previewCache.data[self.id],
  1338. settings, params, index = $frame.data('fileindex'), config, extraData;
  1339. index = parseInt(index.replace('init_', ''));
  1340. config = isEmpty(cache.config) && isEmpty(cache.config[index]) ? null : cache.config[index];
  1341. extraData = isEmpty(config) || isEmpty(config.extra) ? deleteExtraData : config.extra;
  1342. if (typeof extraData === "function") {
  1343. extraData = extraData();
  1344. }
  1345. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  1346. settings = $.extend(true, {}, {
  1347. url: vUrl,
  1348. type: 'POST',
  1349. dataType: 'json',
  1350. data: $.extend(true, {}, {key: vKey}, extraData),
  1351. beforeSend: function (jqXHR) {
  1352. self.ajaxAborted = false;
  1353. self._raise('filepredelete', [vKey, jqXHR, extraData]);
  1354. if (self.ajaxAborted) {
  1355. jqXHR.abort();
  1356. } else {
  1357. addCss($frame, 'file-uploading');
  1358. addCss($el, 'disabled');
  1359. }
  1360. },
  1361. success: function (data, textStatus, jqXHR) {
  1362. var n, cap;
  1363. if (isEmpty(data) || isEmpty(data.error)) {
  1364. previewCache.unset(self.id, index);
  1365. n = previewCache.count(self.id);
  1366. cap = n > 0 ? self._getMsgSelected(n) : '';
  1367. self._raise('filedeleted', [vKey, jqXHR, extraData]);
  1368. self._setCaption(cap);
  1369. } else {
  1370. params.jqXHR = jqXHR;
  1371. params.response = data;
  1372. self._showError(data.error, params, 'filedeleteerror');
  1373. $frame.removeClass('file-uploading');
  1374. $el.removeClass('disabled');
  1375. resetProgress();
  1376. return;
  1377. }
  1378. $frame.removeClass('file-uploading').addClass('file-deleted');
  1379. $frame.fadeOut('slow', function () {
  1380. self._clearObjects($frame);
  1381. $frame.remove();
  1382. resetProgress();
  1383. if (!n && self.getFileStack().length === 0) {
  1384. self._setCaption('');
  1385. self.reset();
  1386. }
  1387. });
  1388. },
  1389. error: function (jqXHR, textStatus, errorThrown) {
  1390. var errMsg = self._parseError(jqXHR, errorThrown);
  1391. params.jqXHR = jqXHR;
  1392. params.response = {};
  1393. self._showError(errMsg, params, 'filedeleteerror');
  1394. $frame.removeClass('file-uploading');
  1395. resetProgress();
  1396. }
  1397. }, self.ajaxDeleteSettings);
  1398. handler($el, 'click', function () {
  1399. if (!self._validateMinCount()) {
  1400. return false;
  1401. }
  1402. $.ajax(settings);
  1403. });
  1404. });
  1405. },
  1406. _clearObjects: function ($el) {
  1407. $el.find('video audio').each(function () {
  1408. this.pause();
  1409. $(this).remove();
  1410. });
  1411. $el.find('img object div').each(function () {
  1412. $(this).remove();
  1413. });
  1414. },
  1415. _clearFileInput: function () {
  1416. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  1417. if (isEmpty($el.val())) {
  1418. return;
  1419. }
  1420. // Fix for IE ver < 11, that does not clear file inputs. Requires a sequence of steps to prevent IE
  1421. // crashing but still allow clearing of the file input.
  1422. if (self.isIE9 || self.isIE10) {
  1423. $srcFrm = $el.closest('form');
  1424. $tmpFrm = $(document.createElement('form'));
  1425. $tmpEl = $(document.createElement('div'));
  1426. $el.before($tmpEl);
  1427. if ($srcFrm.length) {
  1428. $srcFrm.after($tmpFrm);
  1429. } else {
  1430. $tmpEl.after($tmpFrm);
  1431. }
  1432. $tmpFrm.append($el).trigger('reset');
  1433. $tmpEl.before($el).remove();
  1434. $tmpFrm.remove();
  1435. } else { // normal input clear behavior for other sane browsers
  1436. $el.val('');
  1437. }
  1438. self.fileInputCleared = true;
  1439. },
  1440. _resetUpload: function () {
  1441. var self = this;
  1442. self.uploadCache = {content: [], config: [], tags: [], append: true};
  1443. self.uploadCount = 0;
  1444. self.uploadStatus = {};
  1445. self.uploadLog = [];
  1446. self.uploadAsyncCount = 0;
  1447. self.loadedImages = [];
  1448. self.totalImagesCount = 0;
  1449. self.$btnUpload.removeAttr('disabled');
  1450. self._setProgress(0);
  1451. addCss(self.$progress, 'hide');
  1452. self._resetErrors(false);
  1453. self.ajaxAborted = false;
  1454. self.ajaxRequests = [];
  1455. self._resetCanvas();
  1456. },
  1457. _resetCanvas: function () {
  1458. var self = this;
  1459. if (self.canvas && self.imageCanvasContext) {
  1460. self.imageCanvasContext.clearRect(0, 0, self.canvas.width, self.canvas.height);
  1461. }
  1462. },
  1463. _hasInitialPreview: function () {
  1464. var self = this;
  1465. return !self.overwriteInitial && previewCache.count(self.id);
  1466. },
  1467. _resetPreview: function () {
  1468. var self = this, out, cap;
  1469. if (previewCache.count(self.id)) {
  1470. out = previewCache.out(self.id);
  1471. self.$preview.html(out.content);
  1472. cap = self.initialCaption ? self.initialCaption : out.caption;
  1473. self._setCaption(cap);
  1474. } else {
  1475. self._clearPreview();
  1476. self._initCaption();
  1477. }
  1478. if (self.showPreview) {
  1479. self._initZoom();
  1480. self._initSortable();
  1481. }
  1482. },
  1483. _clearDefaultPreview: function () {
  1484. var self = this;
  1485. self.$preview.find('.file-default-preview').remove();
  1486. },
  1487. _validateDefaultPreview: function () {
  1488. var self = this;
  1489. if (!self.showPreview || isEmpty(self.defaultPreviewContent)) {
  1490. return;
  1491. }
  1492. self.$preview.html('<div class="file-default-preview">' + self.defaultPreviewContent + '</div>');
  1493. self.$container.removeClass('file-input-new');
  1494. },
  1495. _resetPreviewThumbs: function (isAjax) {
  1496. var self = this, out;
  1497. if (isAjax) {
  1498. self._clearPreview();
  1499. self.clearStack();
  1500. return;
  1501. }
  1502. if (self._hasInitialPreview()) {
  1503. out = previewCache.out(self.id);
  1504. self.$preview.html(out.content);
  1505. self._setCaption(out.caption);
  1506. self._initPreviewActions();
  1507. } else {
  1508. self._clearPreview();
  1509. }
  1510. },
  1511. _getLayoutTemplate: function (t) {
  1512. var self = this,
  1513. template = ifSet(t, self.layoutTemplates, defaultLayoutTemplates[t]);
  1514. if (isEmpty(self.customLayoutTags)) {
  1515. return template;
  1516. }
  1517. return replaceTags(template, self.customLayoutTags);
  1518. },
  1519. _getPreviewTemplate: function (t) {
  1520. var self = this,
  1521. template = ifSet(t, self.previewTemplates, defaultPreviewTemplates[t]);
  1522. if (isEmpty(self.customPreviewTags)) {
  1523. return template;
  1524. }
  1525. return replaceTags(template, self.customPreviewTags);
  1526. },
  1527. _getOutData: function (jqXHR, responseData, filesData) {
  1528. var self = this;
  1529. jqXHR = jqXHR || {};
  1530. responseData = responseData || {};
  1531. filesData = filesData || self.filestack.slice(0) || {};
  1532. return {
  1533. form: self.formdata,
  1534. files: filesData,
  1535. filenames: self.filenames,
  1536. extra: self._getExtraData(),
  1537. response: responseData,
  1538. reader: self.reader,
  1539. jqXHR: jqXHR
  1540. };
  1541. },
  1542. _getMsgSelected: function (n) {
  1543. var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural;
  1544. return self.msgSelected.replace('{n}', n).replace('{files}', strFiles);
  1545. },
  1546. _getThumbs: function (css) {
  1547. css = css || '';
  1548. return this.$preview.find('.file-preview-frame:not(.file-preview-initial)' + css);
  1549. },
  1550. _getExtraData: function (previewId, index) {
  1551. var self = this, data = self.uploadExtraData;
  1552. if (typeof self.uploadExtraData === "function") {
  1553. data = self.uploadExtraData(previewId, index);
  1554. }
  1555. return data;
  1556. },
  1557. _initXhr: function (xhrobj, previewId, fileCount) {
  1558. var self = this;
  1559. if (xhrobj.upload) {
  1560. xhrobj.upload.addEventListener('progress', function (event) {
  1561. var pct = 0, position = event.loaded || event.position, total = event.total;
  1562. /** @namespace event.lengthComputable */
  1563. if (event.lengthComputable) {
  1564. pct = Math.ceil(position / total * 100);
  1565. }
  1566. if (previewId) {
  1567. self._setAsyncUploadStatus(previewId, pct, fileCount);
  1568. } else {
  1569. self._setProgress(Math.ceil(pct));
  1570. }
  1571. }, false);
  1572. }
  1573. return xhrobj;
  1574. },
  1575. _ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, previewId, index) {
  1576. var self = this, settings;
  1577. self._raise('filepreajax', [previewId, index]);
  1578. self._uploadExtra(previewId, index);
  1579. settings = $.extend(true, {}, {
  1580. xhr: function () {
  1581. var xhrobj = $.ajaxSettings.xhr();
  1582. return self._initXhr(xhrobj, previewId, self.getFileStack().length);
  1583. },
  1584. url: self.uploadUrl,
  1585. type: 'POST',
  1586. dataType: 'json',
  1587. data: self.formdata,
  1588. cache: false,
  1589. processData: false,
  1590. contentType: false,
  1591. beforeSend: fnBefore,
  1592. success: fnSuccess,
  1593. complete: fnComplete,
  1594. error: fnError
  1595. }, self.ajaxSettings);
  1596. self.ajaxRequests.push($.ajax(settings));
  1597. },
  1598. _initUploadSuccess: function (out, $thumb, allFiles) {
  1599. var self = this, append, data, index, $newThumb, content, config, tags, i;
  1600. if (!self.showPreview || typeof out !== 'object' || $.isEmptyObject(out)) {
  1601. return;
  1602. }
  1603. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  1604. self.hasInitData = true;
  1605. content = out.initialPreview || [];
  1606. config = out.initialPreviewConfig || [];
  1607. tags = out.initialPreviewThumbTags || [];
  1608. append = out.append === undefined || out.append ? true : false;
  1609. if (content.length > 0 && !isArray(content)) {
  1610. content = content.split(self.initialPreviewDelimiter);
  1611. }
  1612. self.overwriteInitial = false;
  1613. self.initialPreview.concat(content);
  1614. self.initialPreviewThumbTags.concat(tags);
  1615. self.initialPreviewConfig.concat(config);
  1616. if ($thumb !== undefined) {
  1617. if (!allFiles) {
  1618. index = previewCache.add(self.id, content, config[0], tags[0], append);
  1619. data = previewCache.get(self.id, index, false);
  1620. $newThumb = $(data).hide();
  1621. $thumb.after($newThumb).fadeOut('slow', function () {
  1622. $newThumb.fadeIn('slow').css('display:inline-block');
  1623. self._initPreviewActions();
  1624. self._clearFileInput();
  1625. $thumb.remove();
  1626. });
  1627. } else {
  1628. i = $thumb.attr('data-fileindex');
  1629. self.uploadCache.content[i] = content[0];
  1630. self.uploadCache.config[i] = config[0];
  1631. self.uploadCache.tags[i] = tags[0];
  1632. self.uploadCache.append = append;
  1633. }
  1634. } else {
  1635. previewCache.set(self.id, content, config, tags, append);
  1636. self._initPreview();
  1637. self._initPreviewActions();
  1638. }
  1639. }
  1640. },
  1641. _initSuccessThumbs: function () {
  1642. var self = this;
  1643. if (!self.showPreview) {
  1644. return;
  1645. }
  1646. self._getThumbs('.file-preview-success').each(function () {
  1647. var $thumb = $(this), $remove = $thumb.find('.kv-file-remove');
  1648. $remove.removeAttr('disabled');
  1649. handler($remove, 'click', function () {
  1650. var out = self._raise('filesuccessremove', [$thumb.attr('id'), $thumb.data('fileindex')]);
  1651. cleanMemory($thumb);
  1652. if (out === false) {
  1653. return;
  1654. }
  1655. $thumb.fadeOut('slow', function () {
  1656. $thumb.remove();
  1657. if (!self.$preview.find('.file-preview-frame').length) {
  1658. self.reset();
  1659. }
  1660. });
  1661. });
  1662. });
  1663. },
  1664. _checkAsyncComplete: function () {
  1665. var self = this, previewId, i;
  1666. for (i = 0; i < self.filestack.length; i++) {
  1667. if (self.filestack[i]) {
  1668. previewId = self.previewInitId + "-" + i;
  1669. if ($.inArray(previewId, self.uploadLog) === -1) {
  1670. return false;
  1671. }
  1672. }
  1673. }
  1674. return (self.uploadAsyncCount === self.uploadLog.length);
  1675. },
  1676. _uploadExtra: function (previewId, index) {
  1677. var self = this, data = self._getExtraData(previewId, index);
  1678. if (data.length === 0) {
  1679. return;
  1680. }
  1681. $.each(data, function (key, value) {
  1682. self.formdata.append(key, value);
  1683. });
  1684. },
  1685. _uploadSingle: function (i, files, allFiles) {
  1686. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  1687. previewId = self.previewInitId + "-" + i, $thumb, chkComplete, $btnUpload, $btnDelete,
  1688. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1689. fnBefore, fnSuccess, fnComplete, fnError, updateUploadLog, params = {id: previewId, index: i};
  1690. self.formdata = formdata;
  1691. if (self.showPreview) {
  1692. $thumb = $('#' + previewId + ':not(.file-preview-initial)');
  1693. $btnUpload = $thumb.find('.kv-file-upload');
  1694. $btnDelete = $thumb.find('.kv-file-remove');
  1695. $('#' + previewId).find('.file-thumb-progress').removeClass('hide');
  1696. }
  1697. if (total === 0 || !hasPostData || ($btnUpload && $btnUpload.hasClass('disabled')) || self._abort(params)) {
  1698. return;
  1699. }
  1700. updateUploadLog = function (i, previewId) {
  1701. self.updateStack(i, undefined);
  1702. self.uploadLog.push(previewId);
  1703. if (self._checkAsyncComplete()) {
  1704. self.fileBatchCompleted = true;
  1705. }
  1706. };
  1707. chkComplete = function () {
  1708. var u = self.uploadCache;
  1709. if (!self.fileBatchCompleted) {
  1710. return;
  1711. }
  1712. setTimeout(function () {
  1713. if (self.showPreview) {
  1714. previewCache.set(self.id, u.content, u.config, u.tags, u.append);
  1715. if (self.hasInitData) {
  1716. self._initPreview();
  1717. self._initPreviewActions();
  1718. }
  1719. }
  1720. self.unlock();
  1721. self._clearFileInput();
  1722. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  1723. self.uploadCount = 0;
  1724. self.uploadStatus = {};
  1725. self.uploadLog = [];
  1726. self._setProgress(100);
  1727. }, 100);
  1728. };
  1729. fnBefore = function (jqXHR) {
  1730. outData = self._getOutData(jqXHR);
  1731. self.fileBatchCompleted = false;
  1732. if (self.showPreview) {
  1733. if (!$thumb.hasClass('file-preview-success')) {
  1734. self._setThumbStatus($thumb, 'Loading');
  1735. addCss($thumb, 'file-uploading');
  1736. }
  1737. $btnUpload.attr('disabled', true);
  1738. $btnDelete.attr('disabled', true);
  1739. }
  1740. if (!allFiles) {
  1741. self.lock();
  1742. }
  1743. self._raise('filepreupload', [outData, previewId, i]);
  1744. $.extend(true, params, outData);
  1745. if (self._abort(params)) {
  1746. jqXHR.abort();
  1747. self._setProgressCancelled();
  1748. }
  1749. };
  1750. fnSuccess = function (data, textStatus, jqXHR) {
  1751. outData = self._getOutData(jqXHR, data);
  1752. $.extend(true, params, outData);
  1753. setTimeout(function () {
  1754. if (isEmpty(data) || isEmpty(data.error)) {
  1755. if (self.showPreview) {
  1756. self._setThumbStatus($thumb, 'Success');
  1757. $btnUpload.hide();
  1758. self._initUploadSuccess(data, $thumb, allFiles);
  1759. }
  1760. self._raise('fileuploaded', [outData, previewId, i]);
  1761. if (!allFiles) {
  1762. self.updateStack(i, undefined);
  1763. } else {
  1764. updateUploadLog(i, previewId);
  1765. }
  1766. } else {
  1767. self._showUploadError(data.error, params);
  1768. self._setPreviewError($thumb, i);
  1769. if (allFiles) {
  1770. updateUploadLog(i, previewId);
  1771. }
  1772. }
  1773. }, 100);
  1774. };
  1775. fnComplete = function () {
  1776. setTimeout(function () {
  1777. if (self.showPreview) {
  1778. $btnUpload.removeAttr('disabled');
  1779. $btnDelete.removeAttr('disabled');
  1780. $thumb.removeClass('file-uploading');
  1781. }
  1782. if (!allFiles) {
  1783. self.unlock(false);
  1784. self._clearFileInput();
  1785. } else {
  1786. chkComplete();
  1787. }
  1788. self._initSuccessThumbs();
  1789. }, 100);
  1790. };
  1791. fnError = function (jqXHR, textStatus, errorThrown) {
  1792. var errMsg = self._parseError(jqXHR, errorThrown, (allFiles ? files[i].name : null));
  1793. setTimeout(function () {
  1794. if (allFiles) {
  1795. updateUploadLog(i, previewId);
  1796. }
  1797. self.uploadStatus[previewId] = 100;
  1798. self._setPreviewError($thumb, i);
  1799. $.extend(true, params, self._getOutData(jqXHR));
  1800. self._showUploadError(errMsg, params);
  1801. }, 100);
  1802. };
  1803. formdata.append(self.uploadFileAttr, files[i], self.filenames[i]);
  1804. formdata.append('file_id', i);
  1805. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, previewId, i);
  1806. },
  1807. _uploadBatch: function () {
  1808. var self = this, files = self.filestack, total = files.length, params = {}, fnBefore, fnSuccess, fnError,
  1809. fnComplete, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1810. setAllUploaded;
  1811. self.formdata = new FormData();
  1812. if (total === 0 || !hasPostData || self._abort(params)) {
  1813. return;
  1814. }
  1815. setAllUploaded = function () {
  1816. $.each(files, function (key) {
  1817. self.updateStack(key, undefined);
  1818. });
  1819. self._clearFileInput();
  1820. };
  1821. fnBefore = function (jqXHR) {
  1822. self.lock();
  1823. var outData = self._getOutData(jqXHR);
  1824. if (self.showPreview) {
  1825. self._getThumbs().each(function () {
  1826. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  1827. $btnDelete = $thumb.find('.kv-file-remove');
  1828. if (!$thumb.hasClass('file-preview-success')) {
  1829. self._setThumbStatus($thumb, 'Loading');
  1830. addCss($thumb, 'file-uploading');
  1831. }
  1832. $btnUpload.attr('disabled', true);
  1833. $btnDelete.attr('disabled', true);
  1834. });
  1835. }
  1836. self._raise('filebatchpreupload', [outData]);
  1837. if (self._abort(outData)) {
  1838. jqXHR.abort();
  1839. self._setProgressCancelled();
  1840. }
  1841. };
  1842. fnSuccess = function (data, textStatus, jqXHR) {
  1843. /** @namespace data.errorkeys */
  1844. var outData = self._getOutData(jqXHR, data), $thumbs = self._getThumbs(), key = 0,
  1845. keys = isEmpty(data) || isEmpty(data.errorkeys) ? [] : data.errorkeys;
  1846. if (isEmpty(data) || isEmpty(data.error)) {
  1847. self._raise('filebatchuploadsuccess', [outData]);
  1848. setAllUploaded();
  1849. if (self.showPreview) {
  1850. $thumbs.each(function () {
  1851. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload');
  1852. $thumb.find('.kv-file-upload').hide();
  1853. self._setThumbStatus($thumb, 'Success');
  1854. $thumb.removeClass('file-uploading');
  1855. $btnUpload.removeAttr('disabled');
  1856. });
  1857. self._initUploadSuccess(data);
  1858. } else {
  1859. self.reset();
  1860. }
  1861. } else {
  1862. if (self.showPreview) {
  1863. $thumbs.each(function () {
  1864. var $thumb = $(this), $btnDelete = $thumb.find('.kv-file-remove'),
  1865. $btnUpload = $thumb.find('.kv-file-upload');
  1866. $thumb.removeClass('file-uploading');
  1867. $btnUpload.removeAttr('disabled');
  1868. $btnDelete.removeAttr('disabled');
  1869. if (keys.length === 0) {
  1870. self._setPreviewError($thumb);
  1871. return;
  1872. }
  1873. if ($.inArray(key, keys) !== -1) {
  1874. self._setPreviewError($thumb);
  1875. } else {
  1876. $thumb.find('.kv-file-upload').hide();
  1877. self._setThumbStatus($thumb, 'Success');
  1878. self.updateStack(key, undefined);
  1879. }
  1880. key++;
  1881. });
  1882. self._initUploadSuccess(data);
  1883. }
  1884. self._showUploadError(data.error, outData, 'filebatchuploaderror');
  1885. }
  1886. };
  1887. fnComplete = function () {
  1888. self._setProgress(100);
  1889. self.unlock();
  1890. self._initSuccessThumbs();
  1891. self._clearFileInput();
  1892. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  1893. };
  1894. fnError = function (jqXHR, textStatus, errorThrown) {
  1895. var outData = self._getOutData(jqXHR), errMsg = self._parseError(jqXHR, errorThrown);
  1896. self._showUploadError(errMsg, outData, 'filebatchuploaderror');
  1897. self.uploadFileCount = total - 1;
  1898. if (!self.showPreview) {
  1899. return;
  1900. }
  1901. self._getThumbs().each(function () {
  1902. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1903. $thumb.removeClass('file-uploading');
  1904. if (self.filestack[key] !== undefined) {
  1905. self._setPreviewError($thumb);
  1906. }
  1907. });
  1908. self._getThumbs().removeClass('file-uploading');
  1909. self._getThumbs(' .kv-file-upload').removeAttr('disabled');
  1910. self._getThumbs(' .kv-file-delete').removeAttr('disabled');
  1911. };
  1912. $.each(files, function (key, data) {
  1913. if (!isEmpty(files[key])) {
  1914. self.formdata.append(self.uploadFileAttr, data, self.filenames[key]);
  1915. }
  1916. });
  1917. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1918. },
  1919. _uploadExtraOnly: function () {
  1920. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  1921. self.formdata = new FormData();
  1922. if (self._abort(params)) {
  1923. return;
  1924. }
  1925. fnBefore = function (jqXHR) {
  1926. self.lock();
  1927. var outData = self._getOutData(jqXHR);
  1928. self._raise('filebatchpreupload', [outData]);
  1929. self._setProgress(50);
  1930. params.data = outData;
  1931. params.xhr = jqXHR;
  1932. if (self._abort(params)) {
  1933. jqXHR.abort();
  1934. self._setProgressCancelled();
  1935. }
  1936. };
  1937. fnSuccess = function (data, textStatus, jqXHR) {
  1938. var outData = self._getOutData(jqXHR, data);
  1939. if (isEmpty(data) || isEmpty(data.error)) {
  1940. self._raise('filebatchuploadsuccess', [outData]);
  1941. self._clearFileInput();
  1942. self._initUploadSuccess(data);
  1943. } else {
  1944. self._showUploadError(data.error, outData, 'filebatchuploaderror');
  1945. }
  1946. };
  1947. fnComplete = function () {
  1948. self._setProgress(100);
  1949. self.unlock();
  1950. self._clearFileInput();
  1951. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  1952. };
  1953. fnError = function (jqXHR, textStatus, errorThrown) {
  1954. var outData = self._getOutData(jqXHR), errMsg = self._parseError(jqXHR, errorThrown);
  1955. params.data = outData;
  1956. self._showUploadError(errMsg, outData, 'filebatchuploaderror');
  1957. };
  1958. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1959. },
  1960. _initFileActions: function () {
  1961. var self = this;
  1962. if (!self.showPreview) {
  1963. return;
  1964. }
  1965. self._initZoomButton();
  1966. self.$preview.find('.kv-file-remove').each(function () {
  1967. var $el = $(this), $frame = $el.closest('.file-preview-frame'), hasError,
  1968. id = $frame.attr('id'), ind = $frame.attr('data-fileindex'), n, cap, status;
  1969. handler($el, 'click', function () {
  1970. status = self._raise('filepreremove', [id, ind]);
  1971. if (status === false || !self._validateMinCount()) {
  1972. return false;
  1973. }
  1974. hasError = $frame.hasClass('file-preview-error');
  1975. cleanMemory($frame);
  1976. $frame.fadeOut('slow', function () {
  1977. self.updateStack(ind, undefined);
  1978. self._clearObjects($frame);
  1979. $frame.remove();
  1980. if (id && hasError) {
  1981. self.$errorContainer.find('li[data-file-id="' + id + '"]').fadeOut('fast', function () {
  1982. $(this).remove();
  1983. if (!self._errorsExist()) {
  1984. self._resetErrors();
  1985. }
  1986. });
  1987. }
  1988. var filestack = self.getFileStack(true), len = filestack.length, chk = previewCache.count(
  1989. self.id),
  1990. hasThumb = self.showPreview && self.$preview.find('.file-preview-frame').length;
  1991. self._clearFileInput();
  1992. if (len === 0 && chk === 0 && !hasThumb) {
  1993. self.reset();
  1994. } else {
  1995. n = chk + len;
  1996. cap = n > 1 ? self._getMsgSelected(n) : (filestack[0] ? self._getFileNames()[0] : '');
  1997. self._setCaption(cap);
  1998. }
  1999. self._raise('fileremoved', [id, ind]);
  2000. });
  2001. });
  2002. });
  2003. self.$preview.find('.kv-file-upload').each(function () {
  2004. var $el = $(this);
  2005. handler($el, 'click', function () {
  2006. var $frame = $el.closest('.file-preview-frame'),
  2007. ind = $frame.attr('data-fileindex');
  2008. if (!$frame.hasClass('file-preview-error')) {
  2009. self._uploadSingle(ind, self.filestack, false);
  2010. }
  2011. });
  2012. });
  2013. },
  2014. _hideFileIcon: function () {
  2015. if (this.overwriteInitial) {
  2016. this.$captionContainer.find('.kv-caption-icon').hide();
  2017. }
  2018. },
  2019. _showFileIcon: function () {
  2020. this.$captionContainer.find('.kv-caption-icon').show();
  2021. },
  2022. _getSize: function (bytes) {
  2023. var size = parseFloat(bytes);
  2024. if (bytes === null || isNaN(size)) {
  2025. return '';
  2026. }
  2027. var self = this, i, tmplt = self._getLayoutTemplate('size'), func = self.fileSizeGetter, sizes, out;
  2028. if (typeof func === 'function') {
  2029. out = func(bytes);
  2030. } else {
  2031. i = Math.floor(Math.log(size) / Math.log(1024));
  2032. sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
  2033. out = (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + sizes[i];
  2034. }
  2035. return tmplt.replace('{sizeText}', out);
  2036. },
  2037. _generatePreviewTemplate: function (cat, data, fname, ftype, previewId, isError, size, frameClass, foot, ind) {
  2038. var self = this, tmplt = self._getPreviewTemplate(cat), content, sText, css = frameClass || '',
  2039. config = ifSet(cat, self.previewSettings, defaultPreviewSettings[cat]),
  2040. caption = self.slug(fname), footer = foot || self._renderFileFooter(caption, size, config.width);
  2041. ind = ind || previewId.slice(previewId.lastIndexOf('-') + 1);
  2042. tmplt = self._parseFilePreviewIcon(tmplt, fname);
  2043. if (isError) {
  2044. footer += '<div class="file-other-error" title="' + self.fileActionSettings.indicatorErrorTitle +
  2045. '">' + self.fileActionSettings.indicatorError + '</div>';
  2046. }
  2047. if (cat === 'text' || cat === 'html') {
  2048. sText = cat === 'text' ? htmlEncode(data) : data;
  2049. content = tmplt.replace(/\{previewId}/g, previewId).replace(/\{caption}/g, caption)
  2050. .replace(/\{width}/g, config.width).replace(/\{height}/g, config.height)
  2051. .replace(/\{frameClass}/g, css).replace(/\{cat}/g, ftype)
  2052. .replace(/\{footer}/g, footer).replace(/\{fileindex}/g, ind)
  2053. .replace(/\{data}/g, sText).replace(/\{template}/g, cat);
  2054. } else {
  2055. content = tmplt.replace(/\{previewId}/g, previewId).replace(/\{caption}/g, caption)
  2056. .replace(/\{frameClass}/g, css).replace(/\{type}/g, ftype).replace(/\{fileindex}/g, ind)
  2057. .replace(/\{width}/g, config.width).replace(/\{height}/g, config.height)
  2058. .replace(/\{footer}/g, footer).replace(/\{data}/g, data).replace(/\{template}/g, cat);
  2059. }
  2060. return content;
  2061. },
  2062. _previewDefault: function (file, previewId, isDisabled) {
  2063. var self = this, $preview = self.$preview, $previewLive = $preview.find('.file-live-thumbs');
  2064. if (!self.showPreview) {
  2065. return;
  2066. }
  2067. var fname = file ? file.name : '', ftype = file ? file.type : '', content,
  2068. isError = isDisabled === true && !self.isUploadable, data = objUrl.createObjectURL(file);
  2069. self._clearDefaultPreview();
  2070. content = self._generatePreviewTemplate('other', data, fname, ftype, previewId, isError, file.size);
  2071. if (!$previewLive.length) {
  2072. $previewLive = $(document.createElement('div')).addClass('file-live-thumbs').appendTo($preview);
  2073. }
  2074. $previewLive.append("\n" + content);
  2075. if (isDisabled === true && self.isUploadable) {
  2076. self._setThumbStatus($('#' + previewId), 'Error');
  2077. }
  2078. },
  2079. _previewFile: function (i, file, theFile, previewId, data) {
  2080. if (!this.showPreview) {
  2081. return;
  2082. }
  2083. var self = this, cat = self._parseFileType(file), fname = file ? file.name : '', caption = self.slug(fname),
  2084. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes, $preview = self.$preview,
  2085. chkTypes = types && types.indexOf(cat) >= 0, $previewLive = $preview.find('.file-live-thumbs'),
  2086. iData = (cat === 'text' || cat === 'html' || cat === 'image') ? theFile.target.result : data, content,
  2087. chkMimes = mimes && mimes.indexOf(file.type) !== -1;
  2088. if (!$previewLive.length) {
  2089. $previewLive = $(document.createElement('div')).addClass('file-live-thumbs').appendTo($preview);
  2090. }
  2091. /** @namespace window.DOMPurify */
  2092. if (cat === 'html' && self.purifyHtml && window.DOMPurify) {
  2093. iData = window.DOMPurify.sanitize(iData);
  2094. }
  2095. if (chkTypes || chkMimes) {
  2096. content = self._generatePreviewTemplate(cat, iData, fname, file.type, previewId, false, file.size);
  2097. self._clearDefaultPreview();
  2098. $previewLive.append("\n" + content);
  2099. self._validateImage(i, previewId, caption, file.type);
  2100. } else {
  2101. self._previewDefault(file, previewId);
  2102. }
  2103. self._initSortable();
  2104. },
  2105. _slugDefault: function (text) {
  2106. return isEmpty(text) ? '' : String(text).replace(/[\-\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_');
  2107. },
  2108. _readFiles: function (files) {
  2109. this.reader = new FileReader();
  2110. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  2111. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  2112. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  2113. settings = self.fileTypeSettings, ctr = self.filestack.length, readFile,
  2114. maxPreviewSize = self.maxFilePreviewSize && parseFloat(self.maxFilePreviewSize),
  2115. canPreview = $preview.length && (!maxPreviewSize || isNaN(maxPreviewSize)),
  2116. throwError = function (msg, file, previewId, index) {
  2117. var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}),
  2118. p2 = {id: previewId, index: index, file: file, files: files};
  2119. self._previewDefault(file, previewId, true);
  2120. if (self.isUploadable) {
  2121. self.addToStack(undefined);
  2122. }
  2123. setTimeout(function () {
  2124. readFile(index + 1);
  2125. }, 100);
  2126. self._initFileActions();
  2127. if (self.removeFromPreviewOnError) {
  2128. $('#' + previewId).remove();
  2129. }
  2130. return self.isUploadable ? self._showUploadError(msg, p1) : self._showError(msg, p2);
  2131. };
  2132. self.loadedImages = [];
  2133. self.totalImagesCount = 0;
  2134. $.each(files, function (key, file) {
  2135. var func = self.fileTypeSettings.image || defaultFileTypeSettings.image;
  2136. if (func && func(file.type)) {
  2137. self.totalImagesCount++;
  2138. }
  2139. });
  2140. readFile = function (i) {
  2141. if (isEmpty($el.attr('multiple'))) {
  2142. numFiles = 1;
  2143. }
  2144. if (i >= numFiles) {
  2145. if (self.isUploadable && self.filestack.length > 0) {
  2146. self._raise('filebatchselected', [self.getFileStack()]);
  2147. } else {
  2148. self._raise('filebatchselected', [files]);
  2149. }
  2150. $container.removeClass('file-thumb-loading');
  2151. $status.html('');
  2152. return;
  2153. }
  2154. var node = ctr + i, previewId = previewInitId + "-" + node, isText, isImage, file = files[i],
  2155. caption = self.slug(file.name), fileSize = (file.size || 0) / 1000, checkFile, fileExtExpr = '',
  2156. previewData = objUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk,
  2157. fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '),
  2158. fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', ');
  2159. if (!isEmpty(fileExt)) {
  2160. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  2161. }
  2162. fileSize = fileSize.toFixed(2);
  2163. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  2164. msg = self.msgSizeTooLarge.replace('{name}', caption)
  2165. .replace('{size}', fileSize)
  2166. .replace('{maxSize}', self.maxFileSize);
  2167. self.isError = throwError(msg, file, previewId, i);
  2168. return;
  2169. }
  2170. if (!isEmpty(fileTypes) && isArray(fileTypes)) {
  2171. for (j = 0; j < fileTypes.length; j += 1) {
  2172. typ = fileTypes[j];
  2173. checkFile = settings[typ];
  2174. chk = (checkFile !== undefined && checkFile(file.type, caption));
  2175. fileCount += isEmpty(chk) ? 0 : chk.length;
  2176. }
  2177. if (fileCount === 0) {
  2178. msg = self.msgInvalidFileType.replace('{name}', caption).replace('{types}', strTypes);
  2179. self.isError = throwError(msg, file, previewId, i);
  2180. return;
  2181. }
  2182. }
  2183. if (fileCount === 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) {
  2184. chk = compare(caption, fileExtExpr);
  2185. fileCount += isEmpty(chk) ? 0 : chk.length;
  2186. if (fileCount === 0) {
  2187. msg = self.msgInvalidFileExtension.replace('{name}', caption).replace('{extensions}',
  2188. strExt);
  2189. self.isError = throwError(msg, file, previewId, i);
  2190. return;
  2191. }
  2192. }
  2193. if (!self.showPreview) {
  2194. self.addToStack(file);
  2195. setTimeout(function () {
  2196. readFile(i + 1);
  2197. }, 100);
  2198. self._raise('fileloaded', [file, previewId, i, reader]);
  2199. return;
  2200. }
  2201. if (!canPreview && fileSize > maxPreviewSize) {
  2202. $container.addClass('file-thumb-loading');
  2203. self._previewDefault(file, previewId);
  2204. self._initFileActions();
  2205. self._updateFileDetails(numFiles);
  2206. readFile(i + 1);
  2207. return;
  2208. }
  2209. if ($preview.length && FileReader !== undefined) {
  2210. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  2211. $container.addClass('file-thumb-loading');
  2212. reader.onerror = function (evt) {
  2213. self._errorHandler(evt, caption);
  2214. };
  2215. reader.onload = function (theFile) {
  2216. self._previewFile(i, file, theFile, previewId, previewData);
  2217. self._initFileActions();
  2218. };
  2219. reader.onloadend = function () {
  2220. msg = msgProgress.replace('{index}', i + 1).replace('{files}', numFiles)
  2221. .replace('{percent}', 50).replace('{name}', caption);
  2222. setTimeout(function () {
  2223. $status.html(msg);
  2224. self._updateFileDetails(numFiles);
  2225. readFile(i + 1);
  2226. }, 100);
  2227. self._raise('fileloaded', [file, previewId, i, reader]);
  2228. };
  2229. reader.onprogress = function (data) {
  2230. if (data.lengthComputable) {
  2231. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  2232. msg = msgProgress.replace('{index}', i + 1).replace('{files}', numFiles)
  2233. .replace('{percent}', progress).replace('{name}', caption);
  2234. setTimeout(function () {
  2235. $status.html(msg);
  2236. }, 100);
  2237. }
  2238. };
  2239. isText = ifSet('text', settings, defaultFileTypeSettings.text);
  2240. isImage = ifSet('image', settings, defaultFileTypeSettings.image);
  2241. if (isText(file.type, caption)) {
  2242. reader.readAsText(file, self.textEncoding);
  2243. } else {
  2244. if (isImage(file.type, caption)) {
  2245. reader.readAsDataURL(file);
  2246. } else {
  2247. reader.readAsArrayBuffer(file);
  2248. }
  2249. }
  2250. } else {
  2251. self._previewDefault(file, previewId);
  2252. setTimeout(function () {
  2253. readFile(i + 1);
  2254. self._updateFileDetails(numFiles);
  2255. }, 100);
  2256. self._raise('fileloaded', [file, previewId, i, reader]);
  2257. }
  2258. self.addToStack(file);
  2259. };
  2260. readFile(0);
  2261. self._updateFileDetails(numFiles, false);
  2262. },
  2263. _updateFileDetails: function (numFiles) {
  2264. var self = this, $el = self.$element, fileStack = self.getFileStack(),
  2265. name = (isIE(9) && findFileName($el.val())) ||
  2266. ($el[0].files[0] && $el[0].files[0].name) || (fileStack.length && fileStack[0].name) || '',
  2267. label = self.slug(name), n = self.isUploadable ? fileStack.length : numFiles,
  2268. nFiles = previewCache.count(self.id) + n, log = n > 1 ? self._getMsgSelected(nFiles) : label;
  2269. if (self.isError) {
  2270. self.$previewContainer.removeClass('file-thumb-loading');
  2271. self.$previewStatus.html('');
  2272. self.$captionContainer.find('.kv-caption-icon').hide();
  2273. } else {
  2274. self._showFileIcon();
  2275. }
  2276. self._setCaption(log, self.isError);
  2277. self.$container.removeClass('file-input-new file-input-ajax-new');
  2278. if (arguments.length === 1) {
  2279. self._raise('fileselect', [numFiles, label]);
  2280. }
  2281. if (previewCache.count(self.id)) {
  2282. self._initPreviewActions();
  2283. }
  2284. },
  2285. _setThumbStatus: function ($thumb, status) {
  2286. var self = this;
  2287. if (!self.showPreview) {
  2288. return;
  2289. }
  2290. var icon = 'indicator' + status, msg = icon + 'Title',
  2291. css = 'file-preview-' + status.toLowerCase(),
  2292. $indicator = $thumb.find('.file-upload-indicator'),
  2293. config = self.fileActionSettings;
  2294. $thumb.removeClass('file-preview-success file-preview-error file-preview-loading');
  2295. if (status === 'Error') {
  2296. $thumb.find('.kv-file-upload').attr('disabled', true);
  2297. }
  2298. if (status === 'Success') {
  2299. $thumb.find('.file-drag-handle').remove();
  2300. $indicator.css('margin-left', 0);
  2301. }
  2302. $indicator.html(config[icon]);
  2303. $indicator.attr('title', config[msg]);
  2304. $thumb.addClass(css);
  2305. },
  2306. _setProgressCancelled: function () {
  2307. var self = this;
  2308. self._setProgress(100, self.$progress, self.msgCancelled);
  2309. },
  2310. _setProgress: function (p, $el, error) {
  2311. var self = this, pct = Math.min(p, 100), template = pct < 100 ? self.progressTemplate :
  2312. (error ? self.progressErrorTemplate : self.progressCompleteTemplate);
  2313. $el = $el || self.$progress;
  2314. if (!isEmpty(template)) {
  2315. $el.html(template.replace(/\{percent}/g, pct));
  2316. if (error) {
  2317. $el.find('[role="progressbar"]').html(error);
  2318. }
  2319. }
  2320. },
  2321. _setFileDropZoneTitle: function () {
  2322. var self = this, $zone = self.$container.find('.file-drop-zone');
  2323. $zone.find('.' + self.dropZoneTitleClass).remove();
  2324. if (!self.isUploadable || !self.showPreview || $zone.length === 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled) {
  2325. return;
  2326. }
  2327. if ($zone.find('.file-preview-frame').length === 0 && isEmpty(self.defaultPreviewContent)) {
  2328. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + self.dropZoneTitle + '</div>');
  2329. }
  2330. self.$container.removeClass('file-input-new');
  2331. addCss(self.$container, 'file-input-ajax-new');
  2332. },
  2333. _setAsyncUploadStatus: function (previewId, pct, total) {
  2334. var self = this, sum = 0;
  2335. self._setProgress(pct, $('#' + previewId).find('.file-thumb-progress'));
  2336. self.uploadStatus[previewId] = pct;
  2337. $.each(self.uploadStatus, function (key, value) {
  2338. sum += value;
  2339. });
  2340. self._setProgress(Math.ceil(sum / total));
  2341. },
  2342. _validateMinCount: function () {
  2343. var self = this, len = self.isUploadable ? self.getFileStack().length : self.$element.get(0).files.length;
  2344. if (self.validateInitialCount && self.minFileCount > 0 && self._getFileCount(
  2345. len - 1) < self.minFileCount) {
  2346. self._noFilesError({});
  2347. return false;
  2348. }
  2349. return true;
  2350. },
  2351. _getFileCount: function (fileCount) {
  2352. var self = this, addCount = 0;
  2353. if (self.validateInitialCount && !self.overwriteInitial) {
  2354. addCount = previewCache.count(self.id);
  2355. fileCount += addCount;
  2356. }
  2357. return fileCount;
  2358. },
  2359. _getFileName: function (file) {
  2360. return file && file.name ? this.slug(file.name) : undefined;
  2361. },
  2362. _getFileNames: function (skipNull) {
  2363. var self = this;
  2364. return self.filenames.filter(function (n) {
  2365. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  2366. });
  2367. },
  2368. _setPreviewError: function ($thumb, i, val) {
  2369. var self = this;
  2370. if (i) {
  2371. self.updateStack(i, val);
  2372. }
  2373. if (self.removeFromPreviewOnError) {
  2374. $thumb.remove();
  2375. } else {
  2376. self._setThumbStatus($thumb, 'Error');
  2377. }
  2378. },
  2379. _checkDimensions: function (i, chk, $img, $thumb, fname, type, params) {
  2380. var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max', limit = self[tag + 'Image' + type],
  2381. $imgEl, isValid;
  2382. if (isEmpty(limit) || !$img.length) {
  2383. return;
  2384. }
  2385. $imgEl = $img[0];
  2386. dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height;
  2387. isValid = chk === 'Small' ? dim >= limit : dim <= limit;
  2388. if (isValid) {
  2389. return;
  2390. }
  2391. msg = self['msgImage' + type + chk].replace('{name}', fname).replace('{size}', limit);
  2392. self._showUploadError(msg, params);
  2393. self._setPreviewError($thumb, i, null);
  2394. },
  2395. _validateImage: function (i, previewId, fname, ftype) {
  2396. var self = this, $preview = self.$preview, params, w1, w2,
  2397. $thumb = $preview.find("#" + previewId), $img = $thumb.find('img');
  2398. fname = fname || 'Untitled';
  2399. if (!$img.length) {
  2400. return;
  2401. }
  2402. handler($img, 'load', function () {
  2403. w1 = $thumb.width();
  2404. w2 = $preview.width();
  2405. if (w1 > w2) {
  2406. $img.css('width', '100%');
  2407. $thumb.css('width', '97%');
  2408. }
  2409. params = {ind: i, id: previewId};
  2410. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
  2411. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
  2412. if (!self.resizeImage) {
  2413. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
  2414. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
  2415. }
  2416. self._raise('fileimageloaded', [previewId]);
  2417. self.loadedImages.push({ind: i, img: $img, thumb: $thumb, pid: previewId, typ: ftype});
  2418. self._validateAllImages();
  2419. objUrl.revokeObjectURL($img.attr('src'));
  2420. });
  2421. },
  2422. _validateAllImages: function () {
  2423. var self = this, i, config, $img, $thumb, pid, ind, params = {}, errFunc;
  2424. if (self.loadedImages.length !== self.totalImagesCount) {
  2425. return;
  2426. }
  2427. self._raise('fileimagesloaded');
  2428. if (!self.resizeImage) {
  2429. return;
  2430. }
  2431. errFunc = self.isUploadable ? self._showUploadError : self._showError;
  2432. for (i = 0; i < self.loadedImages.length; i++) {
  2433. config = self.loadedImages[i];
  2434. $img = config.img;
  2435. $thumb = config.thumb;
  2436. pid = config.pid;
  2437. ind = config.ind;
  2438. params = {id: pid, 'index': ind};
  2439. if (!self._getResizedImage($img[0], config.typ, pid, ind)) {
  2440. errFunc(self.msgImageResizeError, params, 'fileimageresizeerror');
  2441. self._setPreviewError($thumb, ind);
  2442. }
  2443. }
  2444. self._raise('fileimagesresized');
  2445. },
  2446. _getResizedImage: function (image, type, pid, ind) {
  2447. var self = this, width = image.naturalWidth, height = image.naturalHeight, ratio = 1,
  2448. maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height,
  2449. isValidImage = (width && height), chkWidth, chkHeight,
  2450. canvas = self.imageCanvas, context = self.imageCanvasContext;
  2451. if (!isValidImage) {
  2452. return false;
  2453. }
  2454. if (width === maxWidth && height === maxHeight) {
  2455. return true;
  2456. }
  2457. type = type || self.resizeDefaultImageType;
  2458. chkWidth = width > maxWidth;
  2459. chkHeight = height > maxHeight;
  2460. if (self.resizePreference === 'width') {
  2461. ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1);
  2462. } else {
  2463. ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1);
  2464. }
  2465. self._resetCanvas();
  2466. width *= ratio;
  2467. height *= ratio;
  2468. canvas.width = width;
  2469. canvas.height = height;
  2470. try {
  2471. context.drawImage(image, 0, 0, width, height);
  2472. canvas.toBlob(function (blob) {
  2473. self._raise('fileimageresized', [pid, ind]);
  2474. self.filestack[ind] = blob;
  2475. }, type, self.resizeQuality);
  2476. return true;
  2477. }
  2478. catch (err) {
  2479. return false;
  2480. }
  2481. },
  2482. _initBrowse: function ($container) {
  2483. var self = this;
  2484. self.$btnFile = $container.find('.btn-file');
  2485. self.$btnFile.append(self.$element);
  2486. },
  2487. _initCaption: function () {
  2488. var self = this, cap = self.initialCaption || '';
  2489. if (self.overwriteInitial || isEmpty(cap)) {
  2490. self.$caption.html('');
  2491. return false;
  2492. }
  2493. self._setCaption(cap);
  2494. return true;
  2495. },
  2496. _setCaption: function (content, isError) {
  2497. var self = this, title, out, n, cap, stack = self.getFileStack();
  2498. if (!self.$caption.length) {
  2499. return;
  2500. }
  2501. if (isError) {
  2502. title = $('<div>' + self.msgValidationError + '</div>').text();
  2503. n = stack.length;
  2504. if (n) {
  2505. cap = n === 1 && stack[0] ? self._getFileNames()[0] : self._getMsgSelected(n);
  2506. } else {
  2507. cap = self._getMsgSelected(self.msgNo);
  2508. }
  2509. out = '<span class="' + self.msgValidationErrorClass + '">' + self.msgValidationErrorIcon +
  2510. (isEmpty(content) ? cap : content) + '</span>';
  2511. } else {
  2512. if (isEmpty(content)) {
  2513. return;
  2514. }
  2515. title = $('<div>' + content + '</div>').text();
  2516. out = self._getLayoutTemplate('fileIcon') + title;
  2517. }
  2518. self.$caption.html(out);
  2519. self.$caption.attr('title', title);
  2520. self.$captionContainer.find('.file-caption-ellipsis').attr('title', title);
  2521. },
  2522. _createContainer: function () {
  2523. var self = this, $container = $(document.createElement("div"))
  2524. .attr({"class": 'file-input file-input-new'})
  2525. .html(self._renderMain());
  2526. self.$element.before($container);
  2527. self._initBrowse($container);
  2528. if (self.theme) {
  2529. $container.addClass('theme-' + self.theme);
  2530. }
  2531. return $container;
  2532. },
  2533. _refreshContainer: function () {
  2534. var self = this, $container = self.$container;
  2535. $container.before(self.$element);
  2536. $container.html(self._renderMain());
  2537. self._initBrowse($container);
  2538. },
  2539. _renderMain: function () {
  2540. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : 'file-drop-disabled',
  2541. close = !self.showClose ? '' : self._getLayoutTemplate('close'),
  2542. preview = !self.showPreview ? '' : self._getLayoutTemplate('preview')
  2543. .replace(/\{class}/g, self.previewClass)
  2544. .replace(/\{dropClass}/g, dropCss),
  2545. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  2546. caption = self.captionTemplate.replace(/\{class}/g, css + ' kv-fileinput-caption');
  2547. return self.mainTemplate.replace(/\{class}/g, self.mainClass)
  2548. .replace(/\{preview}/g, preview)
  2549. .replace(/\{close}/g, close)
  2550. .replace(/\{caption}/g, caption)
  2551. .replace(/\{upload}/g, self._renderButton('upload'))
  2552. .replace(/\{remove}/g, self._renderButton('remove'))
  2553. .replace(/\{cancel}/g, self._renderButton('cancel'))
  2554. .replace(/\{browse}/g, self._renderButton('browse'));
  2555. },
  2556. _renderButton: function (type) {
  2557. var self = this, tmplt = self._getLayoutTemplate('btnDefault'), css = self[type + 'Class'],
  2558. title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'],
  2559. status = self.isDisabled ? ' disabled' : '', btnType = 'button';
  2560. switch (type) {
  2561. case 'remove':
  2562. if (!self.showRemove) {
  2563. return '';
  2564. }
  2565. break;
  2566. case 'cancel':
  2567. if (!self.showCancel) {
  2568. return '';
  2569. }
  2570. css += ' hide';
  2571. break;
  2572. case 'upload':
  2573. if (!self.showUpload) {
  2574. return '';
  2575. }
  2576. if (self.isUploadable && !self.isDisabled) {
  2577. tmplt = self._getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl);
  2578. } else {
  2579. btnType = 'submit';
  2580. }
  2581. break;
  2582. case 'browse':
  2583. tmplt = self._getLayoutTemplate('btnBrowse');
  2584. break;
  2585. default:
  2586. return '';
  2587. }
  2588. css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button';
  2589. if (!isEmpty(label)) {
  2590. label = ' <span class="' + self.buttonLabelClass + '">' + label + '</span>';
  2591. }
  2592. return tmplt.replace('{type}', btnType).replace('{css}', css).replace('{title}', title)
  2593. .replace('{status}', status).replace('{icon}', icon).replace('{label}', label);
  2594. },
  2595. _renderThumbProgress: function () {
  2596. return '<div class="file-thumb-progress hide">' + this.progressTemplate.replace(/\{percent}/g,
  2597. '0') + '</div>';
  2598. },
  2599. _renderFileFooter: function (caption, size, width) {
  2600. var self = this, config = self.fileActionSettings, footer, rem = config.showRemove, drg = config.showDrag,
  2601. upl = config.showUpload, zoom = config.showZoom, out, template = self._getLayoutTemplate('footer');
  2602. size = self._getSize(size);
  2603. if (self.isUploadable) {
  2604. out = template.replace(/\{actions}/g, self._renderFileActions(rem, upl, zoom, drg, false, false, false))
  2605. .replace(/\{caption}/g, caption).replace(/\{size}/g, size).replace(/\{width}/g, width)
  2606. .replace(/\{progress}/g, self._renderThumbProgress()).replace(/\{indicator}/g, config.indicatorNew)
  2607. .replace(/\{indicatorTitle}/g, config.indicatorNewTitle);
  2608. } else {
  2609. out = template.replace(/\{actions}/g,
  2610. self._renderFileActions(false, false, zoom, drg, false, false, false))
  2611. .replace(/\{caption}/g, caption).replace(/\{size}/g, size).replace(/\{width}/g, width)
  2612. .replace(/\{progress}/g, '').replace(/\{indicator}/g, config.indicatorNew)
  2613. .replace(/\{indicatorTitle}/g, config.indicatorNewTitle);
  2614. }
  2615. out = replaceTags(out, self.previewThumbTags);
  2616. return out;
  2617. },
  2618. _renderFileActions: function (showUpload, showDelete, showZoom, showDrag, disabled, url, key, isInit) {
  2619. if (!showUpload && !showDelete && !showZoom && !showDrag) {
  2620. return '';
  2621. }
  2622. var self = this,
  2623. vUrl = url === false ? '' : ' data-url="' + url + '"',
  2624. vKey = key === false ? '' : ' data-key="' + key + '"',
  2625. btnDelete = '', btnUpload = '', btnZoom = '', btnDrag = '', css,
  2626. template = self._getLayoutTemplate('actions'), config = self.fileActionSettings,
  2627. otherButtons = self.otherActionButtons.replace(/\{dataKey}/g, vKey),
  2628. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  2629. if (showDelete) {
  2630. btnDelete = self._getLayoutTemplate('actionDelete')
  2631. .replace(/\{removeClass}/g, removeClass)
  2632. .replace(/\{removeIcon}/g, config.removeIcon)
  2633. .replace(/\{removeTitle}/g, config.removeTitle)
  2634. .replace(/\{dataUrl}/g, vUrl)
  2635. .replace(/\{dataKey}/g, vKey);
  2636. }
  2637. if (showUpload) {
  2638. btnUpload = self._getLayoutTemplate('actionUpload')
  2639. .replace(/\{uploadClass}/g, config.uploadClass)
  2640. .replace(/\{uploadIcon}/g, config.uploadIcon)
  2641. .replace(/\{uploadTitle}/g, config.uploadTitle);
  2642. }
  2643. if (showZoom) {
  2644. btnZoom = self._getLayoutTemplate('actionZoom')
  2645. .replace(/\{zoomClass}/g, config.zoomClass)
  2646. .replace(/\{zoomIcon}/g, config.zoomIcon)
  2647. .replace(/\{zoomTitle}/g, config.zoomTitle);
  2648. }
  2649. if (showDrag && isInit) {
  2650. css = 'drag-handle-init ' + config.dragClass;
  2651. btnDrag = self._getLayoutTemplate('actionDrag').replace(/\{dragClass}/g, css)
  2652. .replace(/\{dragTitle}/g, config.dragTitle)
  2653. .replace(/\{dragIcon}/g, config.dragIcon);
  2654. }
  2655. return template.replace(/\{delete}/g, btnDelete)
  2656. .replace(/\{upload}/g, btnUpload)
  2657. .replace(/\{zoom}/g, btnZoom)
  2658. .replace(/\{drag}/g, btnDrag)
  2659. .replace(/\{other}/g, otherButtons);
  2660. },
  2661. _browse: function (e) {
  2662. var self = this;
  2663. self._raise('filebrowse');
  2664. if (e && e.isDefaultPrevented()) {
  2665. return;
  2666. }
  2667. if (self.isError && !self.isUploadable) {
  2668. self.clear();
  2669. }
  2670. self.$captionContainer.focus();
  2671. },
  2672. _change: function (e) {
  2673. var self = this, $el = self.$element;
  2674. if (!self.isUploadable && isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix
  2675. self.fileInputCleared = false;
  2676. return;
  2677. }
  2678. self.fileInputCleared = false;
  2679. var tfiles, msg, total, isDragDrop = arguments.length > 1, isAjaxUpload = self.isUploadable, i = 0, f, n, len,
  2680. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files, ctr = self.filestack.length,
  2681. isSingleUpload = isEmpty($el.attr('multiple')), flagSingle = (isSingleUpload && ctr > 0), folders = 0,
  2682. throwError = function (mesg, file, previewId, index) {
  2683. var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}),
  2684. p2 = {id: previewId, index: index, file: file, files: files};
  2685. return self.isUploadable ? self._showUploadError(mesg, p1) : self._showError(mesg, p2);
  2686. };
  2687. self.reader = null;
  2688. self._resetUpload();
  2689. self._hideFileIcon();
  2690. if (self.isUploadable) {
  2691. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  2692. }
  2693. if (isDragDrop) {
  2694. tfiles = [];
  2695. while (files[i]) {
  2696. f = files[i];
  2697. if (!f.type && f.size % 4096 === 0) {
  2698. folders++;
  2699. } else {
  2700. tfiles.push(f);
  2701. }
  2702. i++;
  2703. }
  2704. } else {
  2705. if (e.target.files === undefined) {
  2706. tfiles = e.target && e.target.value ? [
  2707. {name: e.target.value.replace(/^.+\\/, '')}
  2708. ] : [];
  2709. } else {
  2710. tfiles = e.target.files;
  2711. }
  2712. }
  2713. if (isEmpty(tfiles) || tfiles.length === 0) {
  2714. if (!isAjaxUpload) {
  2715. self.clear();
  2716. }
  2717. self._showFolderError(folders);
  2718. self._raise('fileselectnone');
  2719. return;
  2720. }
  2721. self._resetErrors();
  2722. len = tfiles.length;
  2723. total = self._getFileCount(self.isUploadable ? (self.getFileStack().length + len) : len);
  2724. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  2725. if (!self.autoReplace || len > self.maxFileCount) {
  2726. n = (self.autoReplace && len > self.maxFileCount) ? len : total;
  2727. msg = self.msgFilesTooMany.replace('{m}', self.maxFileCount).replace('{n}', n);
  2728. self.isError = throwError(msg, null, null, null);
  2729. self.$captionContainer.find('.kv-caption-icon').hide();
  2730. self._setCaption('', true);
  2731. self.$container.removeClass('file-input-new file-input-ajax-new');
  2732. return;
  2733. }
  2734. if (total > self.maxFileCount) {
  2735. self._resetPreviewThumbs(isAjaxUpload);
  2736. }
  2737. } else {
  2738. if (!isAjaxUpload || flagSingle) {
  2739. self._resetPreviewThumbs(false);
  2740. if (flagSingle) {
  2741. self.clearStack();
  2742. }
  2743. } else {
  2744. if (isAjaxUpload && ctr === 0 && (!previewCache.count(self.id) || self.overwriteInitial)) {
  2745. self._resetPreviewThumbs(true);
  2746. }
  2747. }
  2748. }
  2749. if (self.isPreviewable) {
  2750. self._readFiles(tfiles);
  2751. } else {
  2752. self._updateFileDetails(1);
  2753. }
  2754. self._showFolderError(folders);
  2755. },
  2756. _abort: function (params) {
  2757. var self = this, data;
  2758. if (self.ajaxAborted && typeof self.ajaxAborted === "object" && self.ajaxAborted.message !== undefined) {
  2759. data = $.extend(true, {}, self._getOutData(), params);
  2760. data.abortData = self.ajaxAborted.data || {};
  2761. data.abortMessage = self.ajaxAborted.message;
  2762. self.cancel();
  2763. self._setProgress(100, self.$progress, self.msgCancelled);
  2764. self._showUploadError(self.ajaxAborted.message, data, 'filecustomerror');
  2765. return true;
  2766. }
  2767. return false;
  2768. },
  2769. _resetFileStack: function () {
  2770. var self = this, i = 0, newstack = [], newnames = [];
  2771. self._getThumbs().each(function () {
  2772. var $thumb = $(this), ind = $thumb.attr('data-fileindex'),
  2773. file = self.filestack[ind];
  2774. if (ind === -1) {
  2775. return;
  2776. }
  2777. if (file !== undefined) {
  2778. newstack[i] = file;
  2779. newnames[i] = self._getFileName(file);
  2780. $thumb.attr({
  2781. 'id': self.previewInitId + '-' + i,
  2782. 'data-fileindex': i
  2783. });
  2784. i++;
  2785. } else {
  2786. $thumb.attr({
  2787. 'id': 'uploaded-' + uniqId(),
  2788. 'data-fileindex': '-1'
  2789. });
  2790. }
  2791. });
  2792. self.filestack = newstack;
  2793. self.filenames = newnames;
  2794. },
  2795. clearStack: function () {
  2796. var self = this;
  2797. self.filestack = [];
  2798. self.filenames = [];
  2799. return self.$element;
  2800. },
  2801. updateStack: function (i, file) {
  2802. var self = this;
  2803. self.filestack[i] = file;
  2804. self.filenames[i] = self._getFileName(file);
  2805. return self.$element;
  2806. },
  2807. addToStack: function (file) {
  2808. var self = this;
  2809. self.filestack.push(file);
  2810. self.filenames.push(self._getFileName(file));
  2811. return self.$element;
  2812. },
  2813. getFileStack: function (skipNull) {
  2814. var self = this;
  2815. return self.filestack.filter(function (n) {
  2816. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  2817. });
  2818. },
  2819. lock: function () {
  2820. var self = this;
  2821. self._resetErrors();
  2822. self.disable();
  2823. if (self.showRemove) {
  2824. addCss(self.$container.find('.fileinput-remove'), 'hide');
  2825. }
  2826. if (self.showCancel) {
  2827. self.$container.find('.fileinput-cancel').removeClass('hide');
  2828. }
  2829. self._raise('filelock', [self.filestack, self._getExtraData()]);
  2830. return self.$element;
  2831. },
  2832. unlock: function (reset) {
  2833. var self = this;
  2834. if (reset === undefined) {
  2835. reset = true;
  2836. }
  2837. self.enable();
  2838. if (self.showCancel) {
  2839. addCss(self.$container.find('.fileinput-cancel'), 'hide');
  2840. }
  2841. if (self.showRemove) {
  2842. self.$container.find('.fileinput-remove').removeClass('hide');
  2843. }
  2844. if (reset) {
  2845. self._resetFileStack();
  2846. }
  2847. self._raise('fileunlock', [self.filestack, self._getExtraData()]);
  2848. return self.$element;
  2849. },
  2850. cancel: function () {
  2851. var self = this, xhr = self.ajaxRequests, len = xhr.length, i;
  2852. if (len > 0) {
  2853. for (i = 0; i < len; i += 1) {
  2854. self.cancelling = true;
  2855. xhr[i].abort();
  2856. }
  2857. }
  2858. self._setProgressCancelled();
  2859. self._getThumbs().each(function () {
  2860. var $thumb = $(this), ind = $thumb.attr('data-fileindex');
  2861. $thumb.removeClass('file-uploading');
  2862. if (self.filestack[ind] !== undefined) {
  2863. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  2864. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  2865. }
  2866. self.unlock();
  2867. });
  2868. return self.$element;
  2869. },
  2870. clear: function () {
  2871. var self = this, cap;
  2872. self.$btnUpload.removeAttr('disabled');
  2873. self._getThumbs().find('video,audio,img').each(function () {
  2874. cleanMemory($(this));
  2875. });
  2876. self._resetUpload();
  2877. self.clearStack();
  2878. self._clearFileInput();
  2879. self._resetErrors(true);
  2880. self._raise('fileclear');
  2881. if (self._hasInitialPreview()) {
  2882. self._showFileIcon();
  2883. self._resetPreview();
  2884. self._initPreviewActions();
  2885. self.$container.removeClass('file-input-new');
  2886. } else {
  2887. self._getThumbs().each(function () {
  2888. self._clearObjects($(this));
  2889. });
  2890. if (self.isUploadable) {
  2891. previewCache.data[self.id] = {};
  2892. }
  2893. self.$preview.html('');
  2894. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  2895. self._setCaption(cap);
  2896. self.$caption.attr('title', '');
  2897. addCss(self.$container, 'file-input-new');
  2898. self._validateDefaultPreview();
  2899. }
  2900. if (self.$container.find('.file-preview-frame').length === 0) {
  2901. if (!self._initCaption()) {
  2902. self.$captionContainer.find('.kv-caption-icon').hide();
  2903. }
  2904. }
  2905. self._hideFileIcon();
  2906. self._raise('filecleared');
  2907. self.$captionContainer.focus();
  2908. self._setFileDropZoneTitle();
  2909. return self.$element;
  2910. },
  2911. reset: function () {
  2912. var self = this;
  2913. self._resetPreview();
  2914. self.$container.find('.fileinput-filename').text('');
  2915. self._raise('filereset');
  2916. addCss(self.$container, 'file-input-new');
  2917. if (self.$preview.find('.file-preview-frame').length || self.isUploadable && self.dropZoneEnabled) {
  2918. self.$container.removeClass('file-input-new');
  2919. }
  2920. self._setFileDropZoneTitle();
  2921. self.clearStack();
  2922. self.formdata = {};
  2923. return self.$element;
  2924. },
  2925. disable: function () {
  2926. var self = this;
  2927. self.isDisabled = true;
  2928. self._raise('filedisabled');
  2929. self.$element.attr('disabled', 'disabled');
  2930. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  2931. self.$container.find(".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").attr(
  2932. "disabled",
  2933. true);
  2934. self._initDragDrop();
  2935. return self.$element;
  2936. },
  2937. enable: function () {
  2938. var self = this;
  2939. self.isDisabled = false;
  2940. self._raise('fileenabled');
  2941. self.$element.removeAttr('disabled');
  2942. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  2943. self.$container.find(
  2944. ".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").removeAttr("disabled");
  2945. self._initDragDrop();
  2946. return self.$element;
  2947. },
  2948. upload: function () {
  2949. var self = this, totLen = self.getFileStack().length, params = {},
  2950. i, outData, len, hasExtraData = !$.isEmptyObject(self._getExtraData());
  2951. if (self.minFileCount > 0 && self._getFileCount(totLen) < self.minFileCount) {
  2952. self._noFilesError(params);
  2953. return;
  2954. }
  2955. if (!self.isUploadable || self.isDisabled || (totLen === 0 && !hasExtraData)) {
  2956. return;
  2957. }
  2958. self._resetUpload();
  2959. self.$progress.removeClass('hide');
  2960. self.uploadCount = 0;
  2961. self.uploadStatus = {};
  2962. self.uploadLog = [];
  2963. self.lock();
  2964. self._setProgress(2);
  2965. if (totLen === 0 && hasExtraData) {
  2966. self._uploadExtraOnly();
  2967. return;
  2968. }
  2969. len = self.filestack.length;
  2970. self.hasInitData = false;
  2971. if (self.uploadAsync) {
  2972. outData = self._getOutData();
  2973. self._raise('filebatchpreupload', [outData]);
  2974. self.fileBatchCompleted = false;
  2975. self.uploadCache = {content: [], config: [], tags: [], append: true};
  2976. self.uploadAsyncCount = self.getFileStack().length;
  2977. for (i = 0; i < len; i++) {
  2978. self.uploadCache.content[i] = null;
  2979. self.uploadCache.config[i] = null;
  2980. self.uploadCache.tags[i] = null;
  2981. }
  2982. for (i = 0; i < len; i++) {
  2983. if (self.filestack[i] !== undefined) {
  2984. self._uploadSingle(i, self.filestack, true);
  2985. }
  2986. }
  2987. return;
  2988. }
  2989. self._uploadBatch();
  2990. return self.$element;
  2991. },
  2992. destroy: function () {
  2993. var self = this, $cont = self.$container;
  2994. $cont.find('.file-drop-zone').off();
  2995. self.$element.insertBefore($cont).off(NAMESPACE).removeData();
  2996. $cont.off().remove();
  2997. return self.$element;
  2998. },
  2999. refresh: function (options) {
  3000. var self = this, $el = self.$element;
  3001. options = options ? $.extend(true, {}, self.options, options) : self.options;
  3002. self.destroy();
  3003. $el.fileinput(options);
  3004. if ($el.val()) {
  3005. $el.trigger('change.fileinput');
  3006. }
  3007. return $el;
  3008. }
  3009. };
  3010. $.fn.fileinput = function (option) {
  3011. if (!hasFileAPISupport() && !isIE(9)) {
  3012. return;
  3013. }
  3014. var args = Array.apply(null, arguments), retvals = [];
  3015. args.shift();
  3016. this.each(function () {
  3017. var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option,
  3018. theme = options.theme || self.data('theme'), l = {}, t = {},
  3019. lang = options.language || self.data('language') || 'en', opts;
  3020. if (!data) {
  3021. if (theme) {
  3022. t = $.fn.fileinputThemes[theme] || {};
  3023. }
  3024. if (lang !== 'en' && !isEmpty($.fn.fileinputLocales[lang])) {
  3025. l = $.fn.fileinputLocales[lang] || {};
  3026. }
  3027. opts = $.extend(true, {}, $.fn.fileinput.defaults, t, $.fn.fileinputLocales.en, l, options,
  3028. self.data());
  3029. data = new FileInput(this, opts);
  3030. self.data('fileinput', data);
  3031. }
  3032. if (typeof option === 'string') {
  3033. retvals.push(data[option].apply(data, args));
  3034. }
  3035. });
  3036. switch (retvals.length) {
  3037. case 0:
  3038. return this;
  3039. case 1:
  3040. return retvals[0];
  3041. default:
  3042. return retvals;
  3043. }
  3044. };
  3045. $.fn.fileinput.defaults = {
  3046. language: 'en',
  3047. showCaption: true,
  3048. showPreview: true,
  3049. showRemove: true,
  3050. showUpload: true,
  3051. showCancel: true,
  3052. showClose: true,
  3053. showUploadedThumbs: true,
  3054. autoReplace: false,
  3055. previewClass: '',
  3056. captionClass: '',
  3057. mainClass: '',
  3058. mainTemplate: null,
  3059. purifyHtml: true,
  3060. fileSizeGetter: null,
  3061. initialCaption: '',
  3062. initialPreview: [],
  3063. initialPreviewDelimiter: '*$$*',
  3064. initialPreviewAsData: false,
  3065. initialPreviewFileType: 'image',
  3066. initialPreviewConfig: [],
  3067. initialPreviewThumbTags: [],
  3068. previewThumbTags: {},
  3069. initialPreviewShowDelete: true,
  3070. removeFromPreviewOnError: false,
  3071. deleteUrl: '',
  3072. deleteExtraData: {},
  3073. overwriteInitial: true,
  3074. layoutTemplates: defaultLayoutTemplates,
  3075. previewTemplates: defaultPreviewTemplates,
  3076. previewZoomSettings: defaultPreviewZoomSettings,
  3077. previewZoomButtonIcons: {
  3078. prev: '<i class="glyphicon glyphicon-triangle-left"></i>',
  3079. next: '<i class="glyphicon glyphicon-triangle-right"></i>',
  3080. toggleheader: '<i class="glyphicon glyphicon-resize-vertical"></i>',
  3081. fullscreen: '<i class="glyphicon glyphicon-fullscreen"></i>',
  3082. borderless: '<i class="glyphicon glyphicon-resize-full"></i>',
  3083. close: '<i class="glyphicon glyphicon-remove"></i>'
  3084. },
  3085. previewZoomButtonClasses: {
  3086. prev: 'btn btn-navigate',
  3087. next: 'btn btn-navigate',
  3088. toggleheader: 'btn btn-default btn-header-toggle',
  3089. fullscreen: 'btn btn-default',
  3090. borderless: 'btn btn-default',
  3091. close: 'btn btn-default'
  3092. },
  3093. allowedPreviewTypes: null,
  3094. allowedPreviewMimeTypes: null,
  3095. allowedFileTypes: null,
  3096. allowedFileExtensions: null,
  3097. defaultPreviewContent: null,
  3098. customLayoutTags: {},
  3099. customPreviewTags: {},
  3100. previewSettings: defaultPreviewSettings,
  3101. fileTypeSettings: defaultFileTypeSettings,
  3102. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  3103. previewFileIconClass: 'file-other-icon',
  3104. previewFileIconSettings: {},
  3105. previewFileExtSettings: {},
  3106. buttonLabelClass: 'hidden-xs',
  3107. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i>&nbsp;',
  3108. browseClass: 'btn btn-primary',
  3109. removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
  3110. removeClass: 'btn btn-default',
  3111. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i>',
  3112. cancelClass: 'btn btn-default',
  3113. uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
  3114. uploadClass: 'btn btn-default',
  3115. uploadUrl: null,
  3116. uploadAsync: true,
  3117. uploadExtraData: {},
  3118. zoomModalHeight: 480,
  3119. minImageWidth: null,
  3120. minImageHeight: null,
  3121. maxImageWidth: null,
  3122. maxImageHeight: null,
  3123. resizeImage: false,
  3124. resizePreference: 'width',
  3125. resizeQuality: 0.92,
  3126. resizeDefaultImageType: 'image/jpeg',
  3127. maxFileSize: 0,
  3128. maxFilePreviewSize: 25600, // 25 MB
  3129. minFileCount: 0,
  3130. maxFileCount: 0,
  3131. validateInitialCount: false,
  3132. msgValidationErrorClass: 'text-danger',
  3133. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  3134. msgErrorClass: 'file-error-message',
  3135. progressThumbClass: "progress-bar progress-bar-success progress-bar-striped active",
  3136. progressClass: "progress-bar progress-bar-success progress-bar-striped active",
  3137. progressCompleteClass: "progress-bar progress-bar-success",
  3138. progressErrorClass: "progress-bar progress-bar-danger",
  3139. previewFileType: 'image',
  3140. elCaptionContainer: null,
  3141. elCaptionText: null,
  3142. elPreviewContainer: null,
  3143. elPreviewImage: null,
  3144. elPreviewStatus: null,
  3145. elErrorContainer: null,
  3146. errorCloseButton: '<span class="close kv-error-close">&times;</span>',
  3147. slugCallback: null,
  3148. dropZoneEnabled: true,
  3149. dropZoneTitleClass: 'file-drop-zone-title',
  3150. fileActionSettings: {},
  3151. otherActionButtons: '',
  3152. textEncoding: 'UTF-8',
  3153. ajaxSettings: {},
  3154. ajaxDeleteSettings: {},
  3155. showAjaxErrorDetails: true
  3156. };
  3157. $.fn.fileinputLocales.en = {
  3158. fileSingle: 'file',
  3159. filePlural: 'files',
  3160. browseLabel: 'Browse &hellip;',
  3161. removeLabel: 'Remove',
  3162. removeTitle: 'Clear selected files',
  3163. cancelLabel: 'Cancel',
  3164. cancelTitle: 'Abort ongoing upload',
  3165. uploadLabel: 'Upload',
  3166. uploadTitle: 'Upload selected files',
  3167. msgNo: 'No',
  3168. msgCancelled: 'Cancelled',
  3169. msgZoomModalHeading: 'Detailed Preview',
  3170. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
  3171. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
  3172. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
  3173. msgFileNotFound: 'File "{name}" not found!',
  3174. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  3175. msgFileNotReadable: 'File "{name}" is not readable.',
  3176. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  3177. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  3178. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  3179. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  3180. msgUploadAborted: 'The file upload was aborted',
  3181. msgValidationError: 'Validation Error',
  3182. msgLoading: 'Loading file {index} of {files} &hellip;',
  3183. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  3184. msgSelected: '{n} {files} selected',
  3185. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  3186. msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
  3187. msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
  3188. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
  3189. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
  3190. msgImageResizeError: 'Could not get the image dimensions to resize.',
  3191. msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>',
  3192. dropZoneTitle: 'Drag & drop files here &hellip;',
  3193. previewZoomButtonTitles: {
  3194. prev: 'View previous file',
  3195. next: 'View next file',
  3196. toggleheader: 'Toggle header',
  3197. fullscreen: 'Toggle full screen',
  3198. borderless: 'Toggle borderless mode',
  3199. close: 'Close detailed preview'
  3200. }
  3201. };
  3202. $.fn.fileinput.Constructor = FileInput;
  3203. /**
  3204. * Convert automatically file inputs with class 'file' into a bootstrap fileinput control.
  3205. */
  3206. $(document).ready(function () {
  3207. var $input = $('input.file[type=file]');
  3208. if ($input.length) {
  3209. $input.fileinput();
  3210. }
  3211. });
  3212. }));