fileinput.js 156 KB

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