fileinput.js 153 KB

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