fileinput.js 154 KB

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