fileinput.js 196 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287
  1. /*!
  2. * bootstrap-fileinput v4.4.6
  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. String.prototype.setTokens = function (replacePairs) {
  32. var str = this.toString(), key, re;
  33. for (key in replacePairs) {
  34. if (replacePairs.hasOwnProperty(key)) {
  35. re = new RegExp("\{" + key + "\}", "g");
  36. str = str.replace(re, replacePairs[key]);
  37. }
  38. }
  39. return str;
  40. };
  41. var $h, FileInput;
  42. // fileinput helper object for all global variables and internal helper methods
  43. //noinspection JSUnresolvedVariable
  44. $h = {
  45. FRAMES: '.kv-preview-thumb',
  46. SORT_CSS: 'file-sortable',
  47. OBJECT_PARAMS: '<param name="controller" value="true" />\n' +
  48. '<param name="allowFullScreen" value="true" />\n' +
  49. '<param name="allowScriptAccess" value="always" />\n' +
  50. '<param name="autoPlay" value="false" />\n' +
  51. '<param name="autoStart" value="false" />\n' +
  52. '<param name="quality" value="high" />\n',
  53. DEFAULT_PREVIEW: '<div class="file-preview-other">\n' +
  54. '<span class="{previewFileIconClass}">{previewFileIcon}</span>\n' +
  55. '</div>',
  56. MODAL_ID: 'kvFileinputModal',
  57. MODAL_EVENTS: ['show', 'shown', 'hide', 'hidden', 'loaded'],
  58. objUrl: window.URL || window.webkitURL,
  59. compare: function (input, str, exact) {
  60. return input !== undefined && (exact ? input === str : input.match(str));
  61. },
  62. isIE: function (ver) {
  63. // check for IE versions < 11
  64. if (navigator.appName !== 'Microsoft Internet Explorer') {
  65. return false;
  66. }
  67. if (ver === 10) {
  68. return new RegExp('msie\\s' + ver, 'i').test(navigator.userAgent);
  69. }
  70. var div = document.createElement("div"), status;
  71. div.innerHTML = "<!--[if IE " + ver + "]> <i></i> <![endif]-->";
  72. status = div.getElementsByTagName("i").length;
  73. document.body.appendChild(div);
  74. div.parentNode.removeChild(div);
  75. return status;
  76. },
  77. initModal: function ($modal) {
  78. var $body = $('body');
  79. if ($body.length) {
  80. $modal.appendTo($body);
  81. }
  82. },
  83. isEmpty: function (value, trim) {
  84. return value === undefined || value === null || value.length === 0 || (trim && $.trim(value) === '');
  85. },
  86. isArray: function (a) {
  87. return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]';
  88. },
  89. ifSet: function (needle, haystack, def) {
  90. def = def || '';
  91. return (haystack && typeof haystack === 'object' && needle in haystack) ? haystack[needle] : def;
  92. },
  93. cleanArray: function (arr) {
  94. if (!(arr instanceof Array)) {
  95. arr = [];
  96. }
  97. return arr.filter(function (e) {
  98. return (e !== undefined && e !== null);
  99. });
  100. },
  101. spliceArray: function (arr, index) {
  102. var i, j = 0, out = [];
  103. if (!(arr instanceof Array)) {
  104. return [];
  105. }
  106. for (i = 0; i < arr.length; i++) {
  107. if (i !== index) {
  108. out[j] = arr[i];
  109. j++;
  110. }
  111. }
  112. return out;
  113. },
  114. getNum: function (num, def) {
  115. def = def || 0;
  116. if (typeof num === "number") {
  117. return num;
  118. }
  119. if (typeof num === "string") {
  120. num = parseFloat(num);
  121. }
  122. return isNaN(num) ? def : num;
  123. },
  124. hasFileAPISupport: function () {
  125. return !!(window.File && window.FileReader);
  126. },
  127. hasDragDropSupport: function () {
  128. var div = document.createElement('div');
  129. /** @namespace div.draggable */
  130. /** @namespace div.ondragstart */
  131. /** @namespace div.ondrop */
  132. return !$h.isIE(9) &&
  133. (div.draggable !== undefined || (div.ondragstart !== undefined && div.ondrop !== undefined));
  134. },
  135. hasFileUploadSupport: function () {
  136. return $h.hasFileAPISupport() && window.FormData;
  137. },
  138. hasBlobSupport: function () {
  139. try {
  140. return !!window.Blob && Boolean(new Blob());
  141. } catch (e) {
  142. return false;
  143. }
  144. },
  145. hasArrayBufferViewSupport: function () {
  146. try {
  147. return new Blob([new Uint8Array(100)]).size === 100;
  148. } catch (e) {
  149. return false;
  150. }
  151. },
  152. dataURI2Blob: function (dataURI) {
  153. //noinspection JSUnresolvedVariable
  154. var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder ||
  155. window.MSBlobBuilder, canBlob = $h.hasBlobSupport(), byteStr, arrayBuffer, intArray, i, mimeStr, bb,
  156. canProceed = (canBlob || BlobBuilder) && window.atob && window.ArrayBuffer && window.Uint8Array;
  157. if (!canProceed) {
  158. return null;
  159. }
  160. if (dataURI.split(',')[0].indexOf('base64') >= 0) {
  161. byteStr = atob(dataURI.split(',')[1]);
  162. } else {
  163. byteStr = decodeURIComponent(dataURI.split(',')[1]);
  164. }
  165. arrayBuffer = new ArrayBuffer(byteStr.length);
  166. intArray = new Uint8Array(arrayBuffer);
  167. for (i = 0; i < byteStr.length; i += 1) {
  168. intArray[i] = byteStr.charCodeAt(i);
  169. }
  170. mimeStr = dataURI.split(',')[0].split(':')[1].split(';')[0];
  171. if (canBlob) {
  172. return new Blob([$h.hasArrayBufferViewSupport() ? intArray : arrayBuffer], {type: mimeStr});
  173. }
  174. bb = new BlobBuilder();
  175. bb.append(arrayBuffer);
  176. return bb.getBlob(mimeStr);
  177. },
  178. arrayBuffer2String: function (buffer) {
  179. //noinspection JSUnresolvedVariable
  180. if (window.TextDecoder) {
  181. return new TextDecoder("utf-8").decode(buffer);
  182. }
  183. var array = Array.prototype.slice.apply(new Uint8Array(buffer)), out = '', i = 0, len, c, char2, char3;
  184. len = array.length;
  185. while (i < len) {
  186. c = array[i++];
  187. switch (c >> 4) { // jshint ignore:line
  188. case 0:
  189. case 1:
  190. case 2:
  191. case 3:
  192. case 4:
  193. case 5:
  194. case 6:
  195. case 7:
  196. // 0xxxxxxx
  197. out += String.fromCharCode(c);
  198. break;
  199. case 12:
  200. case 13:
  201. // 110x xxxx 10xx xxxx
  202. char2 = array[i++];
  203. out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); // jshint ignore:line
  204. break;
  205. case 14:
  206. // 1110 xxxx 10xx xxxx 10xx xxxx
  207. char2 = array[i++];
  208. char3 = array[i++];
  209. out += String.fromCharCode(((c & 0x0F) << 12) | // jshint ignore:line
  210. ((char2 & 0x3F) << 6) | // jshint ignore:line
  211. ((char3 & 0x3F) << 0)); // jshint ignore:line
  212. break;
  213. }
  214. }
  215. return out;
  216. },
  217. isHtml: function (str) {
  218. var a = document.createElement('div');
  219. a.innerHTML = str;
  220. for (var c = a.childNodes, i = c.length; i--;) {
  221. if (c[i].nodeType === 1) {
  222. return true;
  223. }
  224. }
  225. return false;
  226. },
  227. isSvg: function (str) {
  228. return str.match(/^\s*<\?xml/i) && (str.match(/<!DOCTYPE svg/i) || str.match(/<svg/i));
  229. },
  230. getMimeType: function (signature, contents, type) {
  231. switch (signature) {
  232. case "ffd8ffe0":
  233. case "ffd8ffe1":
  234. case "ffd8ffe2":
  235. return 'image/jpeg';
  236. case '89504E47':
  237. return 'image/png';
  238. case '47494638':
  239. return 'image/gif';
  240. case '49492a00':
  241. return 'image/tiff';
  242. case '52494646':
  243. return 'image/webp';
  244. case '66747970':
  245. return 'video/3gp';
  246. case '4f676753':
  247. return 'video/ogg';
  248. case '1a45dfa3':
  249. return 'video/mkv';
  250. case '000001ba':
  251. case '000001b3':
  252. return 'video/mpeg';
  253. case '3026b275':
  254. return 'video/wmv';
  255. case '25504446':
  256. return 'application/pdf';
  257. case '25215053':
  258. return 'application/ps';
  259. case '504b0304':
  260. case '504b0506':
  261. case '504b0508':
  262. return 'application/zip';
  263. case '377abcaf':
  264. return 'application/7z';
  265. case '75737461':
  266. return 'application/tar';
  267. case '7801730d':
  268. return 'application/dmg';
  269. default:
  270. switch (signature.substring(0, 6)) {
  271. case '435753':
  272. return 'application/x-shockwave-flash';
  273. case '494433':
  274. return 'audio/mp3';
  275. case '425a68':
  276. return 'application/bzip';
  277. default:
  278. switch (signature.substring(0, 4)) {
  279. case '424d':
  280. return 'image/bmp';
  281. case 'fffb':
  282. return 'audio/mp3';
  283. case '4d5a':
  284. return 'application/exe';
  285. case '1f9d':
  286. case '1fa0':
  287. return 'application/zip';
  288. case '1f8b':
  289. return 'application/gzip';
  290. default:
  291. return contents && !contents.match(/[^\u0000-\u007f]/) ? 'application/text-plain' : type;
  292. }
  293. }
  294. }
  295. },
  296. addCss: function ($el, css) {
  297. $el.removeClass(css).addClass(css);
  298. },
  299. getElement: function (options, param, value) {
  300. return ($h.isEmpty(options) || $h.isEmpty(options[param])) ? value : $(options[param]);
  301. },
  302. uniqId: function () {
  303. return Math.round(new Date().getTime()) + '_' + Math.round(Math.random() * 100);
  304. },
  305. htmlEncode: function (str) {
  306. return str.replace(/&/g, '&amp;')
  307. .replace(/</g, '&lt;')
  308. .replace(/>/g, '&gt;')
  309. .replace(/"/g, '&quot;')
  310. .replace(/'/g, '&apos;');
  311. },
  312. replaceTags: function (str, tags) {
  313. var out = str;
  314. if (!tags) {
  315. return out;
  316. }
  317. $.each(tags, function (key, value) {
  318. if (typeof value === "function") {
  319. value = value();
  320. }
  321. out = out.split(key).join(value);
  322. });
  323. return out;
  324. },
  325. cleanMemory: function ($thumb) {
  326. var data = $thumb.is('img') ? $thumb.attr('src') : $thumb.find('source').attr('src');
  327. /** @namespace $h.objUrl.revokeObjectURL */
  328. $h.objUrl.revokeObjectURL(data);
  329. },
  330. findFileName: function (filePath) {
  331. var sepIndex = filePath.lastIndexOf('/');
  332. if (sepIndex === -1) {
  333. sepIndex = filePath.lastIndexOf('\\');
  334. }
  335. return filePath.split(filePath.substring(sepIndex, sepIndex + 1)).pop();
  336. },
  337. checkFullScreen: function () {
  338. //noinspection JSUnresolvedVariable
  339. return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement ||
  340. document.msFullscreenElement;
  341. },
  342. toggleFullScreen: function (maximize) {
  343. var doc = document, de = doc.documentElement;
  344. if (de && maximize && !$h.checkFullScreen()) {
  345. /** @namespace document.requestFullscreen */
  346. /** @namespace document.msRequestFullscreen */
  347. /** @namespace document.mozRequestFullScreen */
  348. /** @namespace document.webkitRequestFullscreen */
  349. /** @namespace Element.ALLOW_KEYBOARD_INPUT */
  350. if (de.requestFullscreen) {
  351. de.requestFullscreen();
  352. } else if (de.msRequestFullscreen) {
  353. de.msRequestFullscreen();
  354. } else if (de.mozRequestFullScreen) {
  355. de.mozRequestFullScreen();
  356. } else if (de.webkitRequestFullscreen) {
  357. de.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
  358. }
  359. } else {
  360. /** @namespace document.exitFullscreen */
  361. /** @namespace document.msExitFullscreen */
  362. /** @namespace document.mozCancelFullScreen */
  363. /** @namespace document.webkitExitFullscreen */
  364. if (doc.exitFullscreen) {
  365. doc.exitFullscreen();
  366. } else if (doc.msExitFullscreen) {
  367. doc.msExitFullscreen();
  368. } else if (doc.mozCancelFullScreen) {
  369. doc.mozCancelFullScreen();
  370. } else if (doc.webkitExitFullscreen) {
  371. doc.webkitExitFullscreen();
  372. }
  373. }
  374. },
  375. moveArray: function (arr, oldIndex, newIndex) {
  376. if (newIndex >= arr.length) {
  377. var k = newIndex - arr.length;
  378. while ((k--) + 1) {
  379. arr.push(undefined);
  380. }
  381. }
  382. arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]);
  383. return arr;
  384. },
  385. cleanZoomCache: function ($el) {
  386. var $cache = $el.closest('.kv-zoom-cache-theme');
  387. if (!$cache.length) {
  388. $cache = $el.closest('.kv-zoom-cache');
  389. }
  390. $cache.remove();
  391. },
  392. setOrientation: function (buffer, callback) {
  393. var scanner = new DataView(buffer), idx = 0, value = 1, // Non-rotated is the default
  394. maxBytes, uInt16, exifLength;
  395. if (scanner.getUint16(idx) !== 0xFFD8 || buffer.length < 2) { // not a proper JPEG
  396. if (callback) {
  397. callback();
  398. }
  399. return;
  400. }
  401. idx += 2;
  402. maxBytes = scanner.byteLength;
  403. while (idx < maxBytes - 2) {
  404. uInt16 = scanner.getUint16(idx);
  405. idx += 2;
  406. switch (uInt16) {
  407. case 0xFFE1: // Start of EXIF
  408. exifLength = scanner.getUint16(idx);
  409. maxBytes = exifLength - idx;
  410. idx += 2;
  411. break;
  412. case 0x0112: // Orientation tag
  413. value = scanner.getUint16(idx + 6, false);
  414. maxBytes = 0; // Stop scanning
  415. break;
  416. }
  417. }
  418. if (callback) {
  419. callback(value);
  420. }
  421. },
  422. validateOrientation: function (file, callback) {
  423. if (!window.FileReader || !window.DataView) {
  424. return; // skip orientation if pre-requisite libraries not supported by browser
  425. }
  426. var reader = new FileReader(), buffer;
  427. reader.onloadend = function () {
  428. buffer = reader.result;
  429. $h.setOrientation(buffer, callback);
  430. };
  431. reader.readAsArrayBuffer(file);
  432. },
  433. adjustOrientedImage: function ($img, isZoom) {
  434. var offsetContTop, offsetTop, newTop;
  435. if (!$img.hasClass('is-portrait-gt4')) {
  436. return;
  437. }
  438. if (isZoom) {
  439. $img.css({width: $img.parent().height()});
  440. return;
  441. } else {
  442. $img.css({height: 'auto', width: $img.height()});
  443. }
  444. offsetContTop = $img.parent().offset().top;
  445. offsetTop = $img.offset().top;
  446. newTop = offsetContTop - offsetTop;
  447. $img.css('margin-top', newTop);
  448. }
  449. };
  450. FileInput = function (element, options) {
  451. var self = this;
  452. self.$element = $(element);
  453. self.$parent = self.$element.parent();
  454. if (!self._validate()) {
  455. return;
  456. }
  457. self.isPreviewable = $h.hasFileAPISupport();
  458. self.isIE9 = $h.isIE(9);
  459. self.isIE10 = $h.isIE(10);
  460. if (self.isPreviewable || self.isIE9) {
  461. self._init(options);
  462. self._listen();
  463. }
  464. self.$element.removeClass('file-loading');
  465. };
  466. //noinspection JSUnusedGlobalSymbols
  467. FileInput.prototype = {
  468. constructor: FileInput,
  469. _cleanup: function () {
  470. var self = this;
  471. self.reader = null;
  472. self.formdata = {};
  473. self.uploadCount = 0;
  474. self.uploadStatus = {};
  475. self.uploadLog = [];
  476. self.uploadAsyncCount = 0;
  477. self.loadedImages = [];
  478. self.totalImagesCount = 0;
  479. self.ajaxRequests = [];
  480. self.clearStack();
  481. self.fileInputCleared = false;
  482. self.fileBatchCompleted = true;
  483. if (!self.isPreviewable) {
  484. self.showPreview = false;
  485. }
  486. self.isError = false;
  487. self.ajaxAborted = false;
  488. self.cancelling = false;
  489. },
  490. _init: function (options, refreshMode) {
  491. var self = this, f, $el = self.$element, $cont, t, tmp;
  492. self.options = options;
  493. $.each(options, function (key, value) {
  494. switch (key) {
  495. case 'minFileCount':
  496. case 'maxFileCount':
  497. case 'minFileSize':
  498. case 'maxFileSize':
  499. case 'maxFilePreviewSize':
  500. case 'resizeImageQuality':
  501. case 'resizeIfSizeMoreThan':
  502. case 'progressUploadThreshold':
  503. case 'initialPreviewCount':
  504. case 'zoomModalHeight':
  505. case 'minImageHeight':
  506. case 'maxImageHeight':
  507. case 'minImageWidth':
  508. case 'maxImageWidth':
  509. self[key] = $h.getNum(value);
  510. break;
  511. default:
  512. self[key] = value;
  513. break;
  514. }
  515. });
  516. if (self.rtl) { // swap buttons for rtl
  517. tmp = self.previewZoomButtonIcons.prev;
  518. self.previewZoomButtonIcons.prev = self.previewZoomButtonIcons.next;
  519. self.previewZoomButtonIcons.next = tmp;
  520. }
  521. if (!refreshMode) {
  522. self._cleanup();
  523. }
  524. self.$form = $el.closest('form');
  525. self._initTemplateDefaults();
  526. self.uploadFileAttr = !$h.isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data';
  527. t = self._getLayoutTemplate('progress');
  528. self.progressTemplate = t.replace('{class}', self.progressClass);
  529. self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass);
  530. self.progressErrorTemplate = t.replace('{class}', self.progressErrorClass);
  531. self.dropZoneEnabled = $h.hasDragDropSupport() && self.dropZoneEnabled;
  532. self.isDisabled = $el.attr('disabled') || $el.attr('readonly');
  533. if (self.isDisabled) {
  534. $el.attr('disabled', true);
  535. }
  536. self.isAjaxUpload = $h.hasFileUploadSupport() && !$h.isEmpty(self.uploadUrl);
  537. self.isClickable = self.browseOnZoneClick && self.showPreview &&
  538. (self.isAjaxUpload && self.dropZoneEnabled || !$h.isEmpty(self.defaultPreviewContent));
  539. self.slug = typeof options.slugCallback === "function" ? options.slugCallback : self._slugDefault;
  540. self.mainTemplate = self.showCaption ? self._getLayoutTemplate('main1') : self._getLayoutTemplate('main2');
  541. self.captionTemplate = self._getLayoutTemplate('caption');
  542. self.previewGenericTemplate = self._getPreviewTemplate('generic');
  543. if (!self.imageCanvas && self.resizeImage && (self.maxImageWidth || self.maxImageHeight)) {
  544. self.imageCanvas = document.createElement('canvas');
  545. self.imageCanvasContext = self.imageCanvas.getContext('2d');
  546. }
  547. if ($h.isEmpty($el.attr('id'))) {
  548. $el.attr('id', $h.uniqId());
  549. }
  550. self.namespace = '.fileinput_' + $el.attr('id').replace(/-/g, '_');
  551. if (self.$container === undefined) {
  552. self.$container = self._createContainer();
  553. } else {
  554. self._refreshContainer();
  555. }
  556. $cont = self.$container;
  557. self.$dropZone = $cont.find('.file-drop-zone');
  558. self.$progress = $cont.find('.kv-upload-progress');
  559. self.$btnUpload = $cont.find('.fileinput-upload');
  560. self.$captionContainer = $h.getElement(options, 'elCaptionContainer', $cont.find('.file-caption'));
  561. self.$caption = $h.getElement(options, 'elCaptionText', $cont.find('.file-caption-name'));
  562. if (!$h.isEmpty(self.msgPlaceholder)) {
  563. f = $el.attr('multiple') ? self.filePlural : self.fileSingle;
  564. self.$caption.attr('placeholder', self.msgPlaceholder.replace('{files}', f));
  565. }
  566. self.$captionIcon = self.$captionContainer.find('.file-caption-icon');
  567. if (self.mainClass.indexOf('input-group-lg') > -1) {
  568. $h.addCss(self.$captionIcon, 'icon-lg');
  569. } else {
  570. self.$captionIcon.removeClass('icon-lg');
  571. }
  572. self.$previewContainer = $h.getElement(options, 'elPreviewContainer', $cont.find('.file-preview'));
  573. self.$preview = $h.getElement(options, 'elPreviewImage', $cont.find('.file-preview-thumbnails'));
  574. self.$previewStatus = $h.getElement(options, 'elPreviewStatus', $cont.find('.file-preview-status'));
  575. self.$errorContainer = $h.getElement(options, 'elErrorContainer',
  576. self.$previewContainer.find('.kv-fileinput-error'));
  577. self._validateDisabled();
  578. if (!$h.isEmpty(self.msgErrorClass)) {
  579. $h.addCss(self.$errorContainer, self.msgErrorClass);
  580. }
  581. if (!refreshMode) {
  582. self.$errorContainer.hide();
  583. self.previewInitId = "preview-" + $h.uniqId();
  584. self._initPreviewCache();
  585. self._initPreview(true);
  586. self._initPreviewActions();
  587. self._setFileDropZoneTitle();
  588. if (self.$parent.hasClass('file-loading')) {
  589. self.$container.insertBefore(self.$parent);
  590. self.$parent.remove();
  591. }
  592. }
  593. if ($el.attr('disabled')) {
  594. self.disable();
  595. }
  596. self._initZoom();
  597. if (self.hideThumbnailContent) {
  598. $h.addCss(self.$preview, 'hide-content');
  599. }
  600. },
  601. _initTemplateDefaults: function () {
  602. var self = this, tMain1, tMain2, tPreview, tFileIcon, tClose, tCaption, tBtnDefault, tBtnLink, tBtnBrowse,
  603. tModalMain, tModal, tProgress, tSize, tFooter, tActions, tActionDelete, tActionUpload, tActionDownload,
  604. tActionZoom, tActionDrag, tIndicator, tTagBef, tTagBef1, tTagBef2, tTagAft, tGeneric, tHtml, tImage,
  605. tText, tOffice, tVideo, tAudio, tFlash, tObject, tPdf, tOther, tZoomCache, vDefaultDim;
  606. tMain1 = '{preview}\n' +
  607. '<div class="kv-upload-progress kv-hidden"></div><div class="clearfix"></div>\n' +
  608. '<div class="input-group {class}">\n' +
  609. ' {caption}\n' +
  610. '<div class="input-group-btn">\n' +
  611. ' {remove}\n' +
  612. ' {cancel}\n' +
  613. ' {upload}\n' +
  614. ' {browse}\n' +
  615. ' </div>\n' +
  616. '</div>';
  617. tMain2 = '{preview}\n<div class="kv-upload-progress kv-hidden"></div>\n<div class="clearfix"></div>\n{remove}\n{cancel}\n{upload}\n{browse}\n';
  618. tPreview = '<div class="file-preview {class}">\n' +
  619. ' {close}' +
  620. ' <div class="{dropClass}">\n' +
  621. ' <div class="file-preview-thumbnails">\n' +
  622. ' </div>\n' +
  623. ' <div class="clearfix"></div>' +
  624. ' <div class="file-preview-status text-center text-success"></div>\n' +
  625. ' <div class="kv-fileinput-error"></div>\n' +
  626. ' </div>\n' +
  627. '</div>';
  628. tClose = '<button type="button" class="close fileinput-remove">&times;</button>\n';
  629. tFileIcon = '<i class="glyphicon glyphicon-file"></i>';
  630. tCaption = '<div class="file-caption form-control {class}" tabindex="500">\n' +
  631. ' <span class="file-caption-icon"></span>\n' +
  632. ' <input class="file-caption-name" onkeydown="return false;" onpaste="return false;">\n' +
  633. '</div>';
  634. //noinspection HtmlUnknownAttribute
  635. tBtnDefault = '<button type="{type}" tabindex="500" title="{title}" class="{css}" ' +
  636. '{status}>{icon} {label}</button>';
  637. //noinspection HtmlUnknownAttribute
  638. tBtnLink = '<a href="{href}" tabindex="500" title="{title}" class="{css}" {status}>{icon} {label}</a>';
  639. //noinspection HtmlUnknownAttribute
  640. tBtnBrowse = '<div tabindex="500" class="{css}" {status}>{icon} {label}</div>';
  641. tModalMain = '<div id="' + $h.MODAL_ID + '" class="file-zoom-dialog modal fade" ' +
  642. 'tabindex="-1" aria-labelledby="' + $h.MODAL_ID + 'Label"></div>';
  643. tModal = '<div class="modal-dialog modal-lg{rtl}" role="document">\n' +
  644. ' <div class="modal-content">\n' +
  645. ' <div class="modal-header">\n' +
  646. ' <h5 class="modal-title">{heading}</h5>\n' +
  647. ' <span class="kv-zoom-title"></span>\n' +
  648. ' <div class="kv-zoom-actions">{toggleheader}{fullscreen}{borderless}{close}</div>\n' +
  649. ' </div>\n' +
  650. ' <div class="modal-body">\n' +
  651. ' <div class="floating-buttons"></div>\n' +
  652. ' <div class="kv-zoom-body file-zoom-content {zoomFrameClass}"></div>\n' + '{prev} {next}\n' +
  653. ' </div>\n' +
  654. ' </div>\n' +
  655. '</div>\n';
  656. tProgress = '<div class="progress">\n' +
  657. ' <div class="{class}" role="progressbar"' +
  658. ' aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' +
  659. ' {status}\n' +
  660. ' </div>\n' +
  661. '</div>';
  662. tSize = ' <samp>({sizeText})</samp>';
  663. tFooter = '<div class="file-thumbnail-footer">\n' +
  664. ' <div class="file-footer-caption" title="{caption}">\n' +
  665. ' <div class="file-caption-info">{caption}</div>\n' +
  666. ' <div class="file-size-info">{size}</div>\n' +
  667. ' </div>\n' +
  668. ' {progress}\n{indicator}\n{actions}\n' +
  669. '</div>';
  670. tActions = '<div class="file-actions">\n' +
  671. ' <div class="file-footer-buttons">\n' +
  672. ' {download} {upload} {delete} {zoom} {other}' +
  673. ' </div>\n' +
  674. '</div>\n' +
  675. '{drag}\n' +
  676. '<div class="clearfix"></div>';
  677. //noinspection HtmlUnknownAttribute
  678. tActionDelete = '<button type="button" class="kv-file-remove {removeClass}" ' +
  679. 'title="{removeTitle}" {dataUrl}{dataKey}>{removeIcon}</button>\n';
  680. tActionUpload = '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">' +
  681. '{uploadIcon}</button>';
  682. tActionDownload = '<a href="{downloadUrl}" class="{downloadClass}" title="{downloadTitle}" ' +
  683. 'download="{caption}">{downloadIcon}</a>';
  684. tActionZoom = '<button type="button" class="kv-file-zoom {zoomClass}" ' +
  685. 'title="{zoomTitle}">{zoomIcon}</button>';
  686. tActionDrag = '<span class="file-drag-handle {dragClass}" title="{dragTitle}">{dragIcon}</span>';
  687. tIndicator = '<div class="file-upload-indicator" title="{indicatorTitle}">{indicator}</div>';
  688. tTagBef = '<div class="file-preview-frame {frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  689. ' data-template="{template}"';
  690. tTagBef1 = tTagBef + '><div class="kv-file-content">\n';
  691. tTagBef2 = tTagBef + ' title="{caption}"><div class="kv-file-content">\n';
  692. tTagAft = '</div>{footer}\n</div>\n';
  693. tGeneric = '{content}\n';
  694. tHtml = '<div class="kv-preview-data file-preview-html" title="{caption}" {style}>{data}</div>\n';
  695. tImage = '<img src="{data}" class="file-preview-image kv-preview-data" title="{caption}" ' +
  696. 'alt="{caption}" {style}>\n';
  697. tText = '<textarea class="kv-preview-data file-preview-text" title="{caption}" readonly {style}>' +
  698. '{data}</textarea>\n';
  699. tOffice = '<iframe class="kv-preview-data file-preview-office" ' +
  700. 'src="https://docs.google.com/gview?url={data}&embedded=true" {style}></iframe>';
  701. tVideo = '<video class="kv-preview-data file-preview-video" controls {style}>\n' +
  702. '<source src="{data}" type="{type}">\n' + $h.DEFAULT_PREVIEW + '\n</video>\n';
  703. tAudio = '<audio class="kv-preview-data file-preview-audio" controls {style}>\n<source src="{data}" ' +
  704. 'type="{type}">\n' + $h.DEFAULT_PREVIEW + '\n</audio>\n';
  705. tFlash = '<embed class="kv-preview-data file-preview-flash" src="{data}" type="application/x-shockwave-flash" {style}>\n';
  706. tPdf = '<embed class="kv-preview-data file-preview-pdf" src="{data}" type="application/pdf" {style}>\n';
  707. tObject = '<object class="kv-preview-data file-preview-object file-object {typeCss}" ' +
  708. 'data="{data}" type="{type}" {style}>\n' + '<param name="movie" value="{caption}" />\n' +
  709. $h.OBJECT_PARAMS + ' ' + $h.DEFAULT_PREVIEW + '\n</object>\n';
  710. tOther = '<div class="kv-preview-data file-preview-other-frame" {style}>\n' + $h.DEFAULT_PREVIEW + '\n</div>\n';
  711. tZoomCache = '<div class="kv-zoom-cache" style="display:none">{zoomContent}</div>';
  712. vDefaultDim = {width: "100%", height: "100%", 'min-height': "480px"};
  713. self.defaults = {
  714. layoutTemplates: {
  715. main1: tMain1,
  716. main2: tMain2,
  717. preview: tPreview,
  718. close: tClose,
  719. fileIcon: tFileIcon,
  720. caption: tCaption,
  721. modalMain: tModalMain,
  722. modal: tModal,
  723. progress: tProgress,
  724. size: tSize,
  725. footer: tFooter,
  726. indicator: tIndicator,
  727. actions: tActions,
  728. actionDelete: tActionDelete,
  729. actionUpload: tActionUpload,
  730. actionDownload: tActionDownload,
  731. actionZoom: tActionZoom,
  732. actionDrag: tActionDrag,
  733. btnDefault: tBtnDefault,
  734. btnLink: tBtnLink,
  735. btnBrowse: tBtnBrowse,
  736. zoomCache: tZoomCache
  737. },
  738. previewMarkupTags: {
  739. tagBefore1: tTagBef1,
  740. tagBefore2: tTagBef2,
  741. tagAfter: tTagAft
  742. },
  743. previewContentTemplates: {
  744. generic: tGeneric,
  745. html: tHtml,
  746. image: tImage,
  747. text: tText,
  748. office: tOffice,
  749. video: tVideo,
  750. audio: tAudio,
  751. flash: tFlash,
  752. object: tObject,
  753. pdf: tPdf,
  754. other: tOther
  755. },
  756. allowedPreviewTypes: ['image', 'html', 'text', 'video', 'audio', 'flash', 'pdf', 'object'],
  757. previewTemplates: {},
  758. previewSettings: {
  759. image: {width: "auto", height: "auto", 'max-width': "100%", 'max-height': "100%"},
  760. html: {width: "213px", height: "160px"},
  761. text: {width: "213px", height: "160px"},
  762. office: {width: "213px", height: "160px"},
  763. video: {width: "213px", height: "160px"},
  764. audio: {width: "100%", height: "30px"},
  765. flash: {width: "213px", height: "160px"},
  766. object: {width: "213px", height: "160px"},
  767. pdf: {width: "213px", height: "160px"},
  768. other: {width: "213px", height: "160px"}
  769. },
  770. previewSettingsSmall: {
  771. image: {width: "auto", height: "auto", 'max-width': "100%", 'max-height': "100%"},
  772. html: {width: "100%", height: "160px"},
  773. text: {width: "100%", height: "160px"},
  774. office: {width: "100%", height: "160px"},
  775. video: {width: "100%", height: "auto"},
  776. audio: {width: "100%", height: "30px"},
  777. flash: {width: "100%", height: "auto"},
  778. object: {width: "100%", height: "auto"},
  779. pdf: {width: "100%", height: "160px"},
  780. other: {width: "100%", height: "160px"}
  781. },
  782. previewZoomSettings: {
  783. image: {width: "auto", height: "auto", 'max-width': "100%", 'max-height': "100%"},
  784. html: vDefaultDim,
  785. text: vDefaultDim,
  786. office: {width: "100%", height: "100%", 'max-width': "100%", 'min-height': "480px"},
  787. video: {width: "auto", height: "100%", 'max-width': "100%"},
  788. audio: {width: "100%", height: "30px"},
  789. flash: {width: "auto", height: "480px"},
  790. object: {width: "auto", height: "100%", 'max-width': "100%", 'min-height': "480px"},
  791. pdf: vDefaultDim,
  792. other: {width: "auto", height: "100%", 'min-height': "480px"}
  793. },
  794. fileTypeSettings: {
  795. image: function (vType, vName) {
  796. return $h.compare(vType, 'image.*') || $h.compare(vName, /\.(gif|png|jpe?g)$/i);
  797. },
  798. html: function (vType, vName) {
  799. return $h.compare(vType, 'text/html') || $h.compare(vName, /\.(htm|html)$/i);
  800. },
  801. text: function (vType, vName) {
  802. return $h.compare(vType, 'text.*') || $h.compare(vName, /\.(xml|javascript)$/i) ||
  803. $h.compare(vName, /\.(txt|md|csv|nfo|ini|json|php|js|css)$/i);
  804. },
  805. office: function (vType, vName) {
  806. return $h.compare(vType, 'msword') || $h.compare(vType, 'ms-excel') ||
  807. $h.compare(vType, 'ms-powerpoint') ||
  808. $h.compare(vType, 'vnd.openxmlformats-officedocument') ||
  809. $h.compare(vName, /\.(doc|docx|rtf|odt|xls|xlsx|ods|ppt|pptx|pps|pot|potx)$/i);
  810. },
  811. video: function (vType, vName) {
  812. return $h.compare(vType, 'video.*') && ($h.compare(vType, /(ogg|mp4|mp?g|mov|webm|3gp)$/i) ||
  813. $h.compare(vName, /\.(og?|mp4|webm|mp?g|mov|3gp)$/i));
  814. },
  815. audio: function (vType, vName) {
  816. return $h.compare(vType, 'audio.*') && ($h.compare(vName, /(ogg|mp3|mp?g|wav)$/i) ||
  817. $h.compare(vName, /\.(og?|mp3|mp?g|wav)$/i));
  818. },
  819. flash: function (vType, vName) {
  820. return $h.compare(vType, 'application/x-shockwave-flash', true) || $h.compare(vName, /\.(swf)$/i);
  821. },
  822. pdf: function (vType, vName) {
  823. return $h.compare(vType, 'application/pdf', true) || $h.compare(vName, /\.(pdf)$/i);
  824. },
  825. object: function () {
  826. return true;
  827. },
  828. other: function () {
  829. return true;
  830. }
  831. },
  832. fileActionSettings: {
  833. showRemove: true,
  834. showUpload: true,
  835. showDownload: true,
  836. showZoom: true,
  837. showDrag: true,
  838. removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
  839. removeClass: 'btn btn-kv btn-default btn-outline-secondary',
  840. removeErrorClass: 'btn btn-kv btn-danger',
  841. removeTitle: 'Remove file',
  842. uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
  843. uploadClass: 'btn btn-kv btn-default btn-outline-secondary',
  844. uploadTitle: 'Upload file',
  845. uploadRetryIcon: '<i class="glyphicon glyphicon-repeat"></i>',
  846. uploadRetryTitle: 'Retry upload',
  847. downloadIcon: '<i class="glyphicon glyphicon-download"></i>',
  848. downloadClass: 'btn btn-kv btn-default btn-outline-secondary',
  849. downloadTitle: 'Download file',
  850. zoomIcon: '<i class="glyphicon glyphicon-zoom-in"></i>',
  851. zoomClass: 'btn btn-kv btn-default btn-outline-secondary',
  852. zoomTitle: 'View Details',
  853. dragIcon: '<i class="glyphicon glyphicon-move"></i>',
  854. dragClass: 'text-info',
  855. dragTitle: 'Move / Rearrange',
  856. dragSettings: {},
  857. indicatorNew: '<i class="glyphicon glyphicon-plus-sign text-warning"></i>',
  858. indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign text-success"></i>',
  859. indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>',
  860. indicatorLoading: '<i class="glyphicon glyphicon-hourglass text-muted"></i>',
  861. indicatorNewTitle: 'Not uploaded yet',
  862. indicatorSuccessTitle: 'Uploaded',
  863. indicatorErrorTitle: 'Upload Error',
  864. indicatorLoadingTitle: 'Uploading ...'
  865. }
  866. };
  867. $.each(self.defaults, function (key, setting) {
  868. if (key === 'allowedPreviewTypes') {
  869. if (self.allowedPreviewTypes === undefined) {
  870. self.allowedPreviewTypes = setting;
  871. }
  872. return;
  873. }
  874. self[key] = $.extend(true, {}, setting, self[key]);
  875. });
  876. self._initPreviewTemplates();
  877. },
  878. _initPreviewTemplates: function () {
  879. var self = this, cfg = self.defaults, tags = self.previewMarkupTags, tagBef, tagAft = tags.tagAfter;
  880. $.each(cfg.previewContentTemplates, function (key, value) {
  881. if ($h.isEmpty(self.previewTemplates[key])) {
  882. tagBef = tags.tagBefore2;
  883. if (key === 'generic' || key === 'image' || key === 'html' || key === 'text') {
  884. tagBef = tags.tagBefore1;
  885. }
  886. self.previewTemplates[key] = tagBef + value + tagAft;
  887. }
  888. });
  889. },
  890. _initPreviewCache: function () {
  891. var self = this;
  892. self.previewCache = {
  893. data: {},
  894. init: function () {
  895. var content = self.initialPreview;
  896. if (content.length > 0 && !$h.isArray(content)) {
  897. content = content.split(self.initialPreviewDelimiter);
  898. }
  899. self.previewCache.data = {
  900. content: content,
  901. config: self.initialPreviewConfig,
  902. tags: self.initialPreviewThumbTags
  903. };
  904. },
  905. count: function () {
  906. return !!self.previewCache.data && !!self.previewCache.data.content ?
  907. self.previewCache.data.content.length : 0;
  908. },
  909. get: function (i, isDisabled) {
  910. var ind = 'init_' + i, data = self.previewCache.data, config = data.config[i],
  911. content = data.content[i], previewId = self.previewInitId + '-' + ind, out, $tmp, cat, ftr,
  912. fname, ftype, frameClass, asData = $h.ifSet('previewAsData', config, self.initialPreviewAsData),
  913. parseTemplate = function (cat, dat, fn, ft, id, ftr, ind, fc, t) {
  914. fc = ' file-preview-initial ' + $h.SORT_CSS + (fc ? ' ' + fc : '');
  915. return self._generatePreviewTemplate(cat, dat, fn, ft, id, false, null, fc, ftr, ind, t);
  916. };
  917. if (!content) {
  918. return '';
  919. }
  920. isDisabled = isDisabled === undefined ? true : isDisabled;
  921. cat = $h.ifSet('type', config, self.initialPreviewFileType || 'generic');
  922. fname = $h.ifSet('filename', config, $h.ifSet('caption', config));
  923. ftype = $h.ifSet('filetype', config, cat);
  924. ftr = self.previewCache.footer(i, isDisabled, (config && config.size || null));
  925. frameClass = $h.ifSet('frameClass', config);
  926. if (asData) {
  927. out = parseTemplate(cat, content, fname, ftype, previewId, ftr, ind, frameClass);
  928. } else {
  929. out = parseTemplate('generic', content, fname, ftype, previewId, ftr, ind, frameClass, cat)
  930. .setTokens({'content': data.content[i]});
  931. }
  932. if (data.tags.length && data.tags[i]) {
  933. out = $h.replaceTags(out, data.tags[i]);
  934. }
  935. /** @namespace config.frameAttr */
  936. if (!$h.isEmpty(config) && !$h.isEmpty(config.frameAttr)) {
  937. $tmp = $(document.createElement('div')).html(out);
  938. $tmp.find('.file-preview-initial').attr(config.frameAttr);
  939. out = $tmp.html();
  940. $tmp.remove();
  941. }
  942. return out;
  943. },
  944. add: function (content, config, tags, append) {
  945. var data = self.previewCache.data, index;
  946. if (!$h.isArray(content)) {
  947. content = content.split(self.initialPreviewDelimiter);
  948. }
  949. if (append) {
  950. index = data.content.push(content) - 1;
  951. data.config[index] = config;
  952. data.tags[index] = tags;
  953. } else {
  954. index = content.length - 1;
  955. data.content = content;
  956. data.config = config;
  957. data.tags = tags;
  958. }
  959. self.previewCache.data = data;
  960. return index;
  961. },
  962. set: function (content, config, tags, append) {
  963. var data = self.previewCache.data, i, chk;
  964. if (!content || !content.length) {
  965. return;
  966. }
  967. if (!$h.isArray(content)) {
  968. content = content.split(self.initialPreviewDelimiter);
  969. }
  970. chk = content.filter(function (n) {
  971. return n !== null;
  972. });
  973. if (!chk.length) {
  974. return;
  975. }
  976. if (data.content === undefined) {
  977. data.content = [];
  978. }
  979. if (data.config === undefined) {
  980. data.config = [];
  981. }
  982. if (data.tags === undefined) {
  983. data.tags = [];
  984. }
  985. if (append) {
  986. for (i = 0; i < content.length; i++) {
  987. if (content[i]) {
  988. data.content.push(content[i]);
  989. }
  990. }
  991. for (i = 0; i < config.length; i++) {
  992. if (config[i]) {
  993. data.config.push(config[i]);
  994. }
  995. }
  996. for (i = 0; i < tags.length; i++) {
  997. if (tags[i]) {
  998. data.tags.push(tags[i]);
  999. }
  1000. }
  1001. } else {
  1002. data.content = content;
  1003. data.config = config;
  1004. data.tags = tags;
  1005. }
  1006. self.previewCache.data = data;
  1007. },
  1008. unset: function (index) {
  1009. var chk = self.previewCache.count();
  1010. if (!chk) {
  1011. return;
  1012. }
  1013. if (chk === 1) {
  1014. self.previewCache.data.content = [];
  1015. self.previewCache.data.config = [];
  1016. self.previewCache.data.tags = [];
  1017. self.initialPreview = [];
  1018. self.initialPreviewConfig = [];
  1019. self.initialPreviewThumbTags = [];
  1020. return;
  1021. }
  1022. self.previewCache.data.content.splice(index, 1);
  1023. self.previewCache.data.config.splice(index, 1);
  1024. self.previewCache.data.tags.splice(index, 1);
  1025. },
  1026. out: function () {
  1027. var html = '', caption, len = self.previewCache.count(), i;
  1028. if (len === 0) {
  1029. return {content: '', caption: ''};
  1030. }
  1031. for (i = 0; i < len; i++) {
  1032. html += self.previewCache.get(i);
  1033. }
  1034. caption = self._getMsgSelected(len);
  1035. return {content: html, caption: caption};
  1036. },
  1037. footer: function (i, isDisabled, size) {
  1038. var data = self.previewCache.data || {};
  1039. if ($h.isEmpty(data.content)) {
  1040. return '';
  1041. }
  1042. if ($h.isEmpty(data.config) || $h.isEmpty(data.config[i])) {
  1043. data.config[i] = {};
  1044. }
  1045. isDisabled = isDisabled === undefined ? true : isDisabled;
  1046. var config = data.config[i], caption = $h.ifSet('caption', config), a,
  1047. width = $h.ifSet('width', config, 'auto'), url = $h.ifSet('url', config, false),
  1048. key = $h.ifSet('key', config, null), fs = self.fileActionSettings,
  1049. initPreviewShowDel = self.initialPreviewShowDelete || false,
  1050. dUrl = config.downloadUrl || self.initialPreviewDownloadUrl || '',
  1051. dFil = config.filename || config.caption || '',
  1052. initPreviewShowDwl = !!(dUrl),
  1053. sDel = $h.ifSet('showDelete', config, $h.ifSet('showDelete', fs, initPreviewShowDel)),
  1054. sDwl = $h.ifSet('showDownload', config, $h.ifSet('showDownload', fs, initPreviewShowDwl)),
  1055. sZm = $h.ifSet('showZoom', config, $h.ifSet('showZoom', fs, true)),
  1056. sDrg = $h.ifSet('showDrag', config, $h.ifSet('showDrag', fs, true)),
  1057. dis = (url === false) && isDisabled;
  1058. sDwl = sDwl && config.downloadUrl !== false && !!dUrl;
  1059. a = self._renderFileActions(false, sDwl, sDel, sZm, sDrg, dis, url, key, true, dUrl, dFil);
  1060. return self._getLayoutTemplate('footer').setTokens({
  1061. 'progress': self._renderThumbProgress(),
  1062. 'actions': a,
  1063. 'caption': caption,
  1064. 'size': self._getSize(size),
  1065. 'width': width,
  1066. 'indicator': ''
  1067. });
  1068. }
  1069. };
  1070. self.previewCache.init();
  1071. },
  1072. _handler: function ($el, event, callback) {
  1073. var self = this, ns = self.namespace, ev = event.split(' ').join(ns + ' ') + ns;
  1074. if (!$el || !$el.length) {
  1075. return;
  1076. }
  1077. $el.off(ev).on(ev, callback);
  1078. },
  1079. _log: function (msg) {
  1080. var self = this, id = self.$element.attr('id');
  1081. if (id) {
  1082. msg = '"' + id + '": ' + msg;
  1083. }
  1084. if (typeof window.console.log !== "undefined") {
  1085. window.console.log(msg);
  1086. } else {
  1087. window.alert(msg);
  1088. }
  1089. },
  1090. _validate: function () {
  1091. var self = this, status = self.$element.attr('type') === 'file';
  1092. if (!status) {
  1093. self._log('The input "type" must be set to "file" for initializing the "bootstrap-fileinput" plugin.');
  1094. }
  1095. return status;
  1096. },
  1097. _errorsExist: function () {
  1098. var self = this, $err, $errList = self.$errorContainer.find('li');
  1099. if ($errList.length) {
  1100. return true;
  1101. }
  1102. $err = $(document.createElement('div')).html(self.$errorContainer.html());
  1103. $err.find('.kv-error-close').remove();
  1104. $err.find('ul').remove();
  1105. return !!$.trim($err.text()).length;
  1106. },
  1107. _errorHandler: function (evt, caption) {
  1108. var self = this, err = evt.target.error, showError = function (msg) {
  1109. self._showError(msg.replace('{name}', caption));
  1110. };
  1111. /** @namespace err.NOT_FOUND_ERR */
  1112. /** @namespace err.SECURITY_ERR */
  1113. /** @namespace err.NOT_READABLE_ERR */
  1114. if (err.code === err.NOT_FOUND_ERR) {
  1115. showError(self.msgFileNotFound);
  1116. } else if (err.code === err.SECURITY_ERR) {
  1117. showError(self.msgFileSecured);
  1118. } else if (err.code === err.NOT_READABLE_ERR) {
  1119. showError(self.msgFileNotReadable);
  1120. } else if (err.code === err.ABORT_ERR) {
  1121. showError(self.msgFilePreviewAborted);
  1122. } else {
  1123. showError(self.msgFilePreviewError);
  1124. }
  1125. },
  1126. _addError: function (msg) {
  1127. var self = this, $error = self.$errorContainer;
  1128. if (msg && $error.length) {
  1129. $error.html(self.errorCloseButton + msg);
  1130. self._handler($error.find('.kv-error-close'), 'click', function () {
  1131. $error.fadeOut('slow');
  1132. });
  1133. }
  1134. },
  1135. _setValidationError: function (css) {
  1136. var self = this;
  1137. css = (css ? css + ' ' : '') + 'has-error';
  1138. self.$container.removeClass(css).addClass('has-error');
  1139. $h.addCss(self.$captionContainer, 'is-invalid');
  1140. },
  1141. _resetErrors: function (fade) {
  1142. var self = this, $error = self.$errorContainer;
  1143. self.isError = false;
  1144. self.$container.removeClass('has-error');
  1145. self.$captionContainer.removeClass('is-invalid');
  1146. $error.html('');
  1147. if (fade) {
  1148. $error.fadeOut('slow');
  1149. } else {
  1150. $error.hide();
  1151. }
  1152. },
  1153. _showFolderError: function (folders) {
  1154. var self = this, $error = self.$errorContainer, msg;
  1155. if (!folders) {
  1156. return;
  1157. }
  1158. msg = self.msgFoldersNotAllowed.replace('{n}', folders);
  1159. self._addError(msg);
  1160. self._setValidationError();
  1161. $error.fadeIn(800);
  1162. self._raise('filefoldererror', [folders, msg]);
  1163. },
  1164. _showUploadError: function (msg, params, event) {
  1165. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror', e = params && params.id ?
  1166. '<li data-file-id="' + params.id + '">' + msg + '</li>' : '<li>' + msg + '</li>';
  1167. if ($error.find('ul').length === 0) {
  1168. self._addError('<ul>' + e + '</ul>');
  1169. } else {
  1170. $error.find('ul').append(e);
  1171. }
  1172. $error.fadeIn(800);
  1173. self._raise(ev, [params, msg]);
  1174. self._setValidationError('file-input-new');
  1175. return true;
  1176. },
  1177. _showError: function (msg, params, event) {
  1178. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  1179. params = params || {};
  1180. params.reader = self.reader;
  1181. self._addError(msg);
  1182. $error.fadeIn(800);
  1183. self._raise(ev, [params, msg]);
  1184. if (!self.isAjaxUpload) {
  1185. self._clearFileInput();
  1186. }
  1187. self._setValidationError('file-input-new');
  1188. self.$btnUpload.attr('disabled', true);
  1189. return true;
  1190. },
  1191. _noFilesError: function (params) {
  1192. var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle,
  1193. msg = self.msgFilesTooLess.replace('{n}', self.minFileCount).replace('{files}', label),
  1194. $error = self.$errorContainer;
  1195. self._addError(msg);
  1196. self.isError = true;
  1197. self._updateFileDetails(0);
  1198. $error.fadeIn(800);
  1199. self._raise('fileerror', [params, msg]);
  1200. self._clearFileInput();
  1201. self._setValidationError();
  1202. },
  1203. _parseError: function (operation, jqXHR, errorThrown, fileName) {
  1204. /** @namespace jqXHR.responseJSON */
  1205. var self = this, errMsg = $.trim(errorThrown + ''), textPre,
  1206. text = jqXHR.responseJSON !== undefined && jqXHR.responseJSON.error !== undefined ?
  1207. jqXHR.responseJSON.error : jqXHR.responseText;
  1208. if (self.cancelling && self.msgUploadAborted) {
  1209. errMsg = self.msgUploadAborted;
  1210. }
  1211. if (self.showAjaxErrorDetails && text) {
  1212. text = $.trim(text.replace(/\n\s*\n/g, '\n'));
  1213. textPre = text.length ? '<pre>' + text + '</pre>' : '';
  1214. errMsg += errMsg ? textPre : text;
  1215. }
  1216. if (!errMsg) {
  1217. errMsg = self.msgAjaxError.replace('{operation}', operation);
  1218. }
  1219. self.cancelling = false;
  1220. return fileName ? '<b>' + fileName + ': </b>' + errMsg : errMsg;
  1221. },
  1222. _parseFileType: function (type, name) {
  1223. var self = this, isValid, vType, cat, i, types = self.allowedPreviewTypes || [];
  1224. if (type === 'application/text-plain') {
  1225. return 'text';
  1226. }
  1227. for (i = 0; i < types.length; i++) {
  1228. cat = types[i];
  1229. isValid = self.fileTypeSettings[cat];
  1230. vType = isValid(type, name) ? cat : '';
  1231. if (!$h.isEmpty(vType)) {
  1232. return vType;
  1233. }
  1234. }
  1235. return 'other';
  1236. },
  1237. _getPreviewIcon: function (fname) {
  1238. var self = this, ext, out = null;
  1239. if (fname && fname.indexOf('.') > -1) {
  1240. ext = fname.split('.').pop();
  1241. if (self.previewFileIconSettings) {
  1242. out = self.previewFileIconSettings[ext] || self.previewFileIconSettings[ext.toLowerCase()] || null;
  1243. }
  1244. if (self.previewFileExtSettings) {
  1245. $.each(self.previewFileExtSettings, function (key, func) {
  1246. if (self.previewFileIconSettings[key] && func(ext)) {
  1247. out = self.previewFileIconSettings[key];
  1248. //noinspection UnnecessaryReturnStatementJS
  1249. return;
  1250. }
  1251. });
  1252. }
  1253. }
  1254. return out;
  1255. },
  1256. _parseFilePreviewIcon: function (content, fname) {
  1257. var self = this, icn = self._getPreviewIcon(fname) || self.previewFileIcon, out = content;
  1258. if (out.indexOf('{previewFileIcon}') > -1) {
  1259. out = out.setTokens({'previewFileIconClass': self.previewFileIconClass, 'previewFileIcon': icn});
  1260. }
  1261. return out;
  1262. },
  1263. _raise: function (event, params) {
  1264. var self = this, e = $.Event(event);
  1265. if (params !== undefined) {
  1266. self.$element.trigger(e, params);
  1267. } else {
  1268. self.$element.trigger(e);
  1269. }
  1270. if (e.isDefaultPrevented() || e.result === false) {
  1271. return false;
  1272. }
  1273. switch (event) {
  1274. // ignore these events
  1275. case 'filebatchuploadcomplete':
  1276. case 'filebatchuploadsuccess':
  1277. case 'fileuploaded':
  1278. case 'fileclear':
  1279. case 'filecleared':
  1280. case 'filereset':
  1281. case 'fileerror':
  1282. case 'filefoldererror':
  1283. case 'fileuploaderror':
  1284. case 'filebatchuploaderror':
  1285. case 'filedeleteerror':
  1286. case 'filecustomerror':
  1287. case 'filesuccessremove':
  1288. break;
  1289. // receive data response via `filecustomerror` event`
  1290. default:
  1291. if (!self.ajaxAborted) {
  1292. self.ajaxAborted = e.result;
  1293. }
  1294. break;
  1295. }
  1296. return true;
  1297. },
  1298. _listenFullScreen: function (isFullScreen) {
  1299. var self = this, $modal = self.$modal, $btnFull, $btnBord;
  1300. if (!$modal || !$modal.length) {
  1301. return;
  1302. }
  1303. $btnFull = $modal && $modal.find('.btn-fullscreen');
  1304. $btnBord = $modal && $modal.find('.btn-borderless');
  1305. if (!$btnFull.length || !$btnBord.length) {
  1306. return;
  1307. }
  1308. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  1309. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1310. if (isFullScreen) {
  1311. $btnFull.addClass('active').attr('aria-pressed', 'true');
  1312. } else {
  1313. $btnBord.addClass('active').attr('aria-pressed', 'true');
  1314. }
  1315. if ($modal.hasClass('file-zoom-fullscreen')) {
  1316. self._maximizeZoomDialog();
  1317. } else {
  1318. if (isFullScreen) {
  1319. self._maximizeZoomDialog();
  1320. } else {
  1321. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1322. }
  1323. }
  1324. },
  1325. _listen: function () {
  1326. var self = this, $el = self.$element, $form = self.$form, $cont = self.$container, fullScreenEvents;
  1327. self._handler($el, 'change', $.proxy(self._change, self));
  1328. if (self.showBrowse) {
  1329. self._handler(self.$btnFile, 'click', $.proxy(self._browse, self));
  1330. }
  1331. self._handler($cont.find('.fileinput-remove:not([disabled])'), 'click', $.proxy(self.clear, self));
  1332. self._handler($cont.find('.fileinput-cancel'), 'click', $.proxy(self.cancel, self));
  1333. self._initDragDrop();
  1334. self._handler($form, 'reset', $.proxy(self.clear, self));
  1335. if (!self.isAjaxUpload) {
  1336. self._handler($form, 'submit', $.proxy(self._submitForm, self));
  1337. }
  1338. self._handler(self.$container.find('.fileinput-upload'), 'click', $.proxy(self._uploadClick, self));
  1339. self._handler($(window), 'resize', function () {
  1340. self._listenFullScreen(screen.width === window.innerWidth && screen.height === window.innerHeight);
  1341. });
  1342. fullScreenEvents = 'webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange';
  1343. self._handler($(document), fullScreenEvents, function () {
  1344. self._listenFullScreen($h.checkFullScreen());
  1345. });
  1346. self._autoFitContent();
  1347. self._initClickable();
  1348. },
  1349. _autoFitContent: function () {
  1350. var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
  1351. self = this, config = width < 400 ? (self.previewSettingsSmall || self.defaults.previewSettingsSmall) :
  1352. (self.previewSettings || self.defaults.previewSettings), sel;
  1353. $.each(config, function (cat, settings) {
  1354. sel = '.file-preview-frame .file-preview-' + cat;
  1355. self.$preview.find(sel + '.kv-preview-data,' + sel + ' .kv-preview-data').css(settings);
  1356. });
  1357. },
  1358. _initClickable: function () {
  1359. var self = this, $zone;
  1360. if (!self.isClickable) {
  1361. return;
  1362. }
  1363. $zone = self.isAjaxUpload ? self.$dropZone : self.$preview.find('.file-default-preview');
  1364. $h.addCss($zone, 'clickable');
  1365. $zone.attr('tabindex', -1);
  1366. self._handler($zone, 'click', function (e) {
  1367. var $tar = $(e.target);
  1368. if (!$tar.parents('.file-preview-thumbnails').length || $tar.parents('.file-default-preview').length) {
  1369. self.$element.trigger('click');
  1370. $zone.blur();
  1371. }
  1372. });
  1373. },
  1374. _initDragDrop: function () {
  1375. var self = this, $zone = self.$dropZone;
  1376. if (self.isAjaxUpload && self.dropZoneEnabled && self.showPreview) {
  1377. self._handler($zone, 'dragenter dragover', $.proxy(self._zoneDragEnter, self));
  1378. self._handler($zone, 'dragleave', $.proxy(self._zoneDragLeave, self));
  1379. self._handler($zone, 'drop', $.proxy(self._zoneDrop, self));
  1380. self._handler($(document), 'dragenter dragover drop', self._zoneDragDropInit);
  1381. }
  1382. },
  1383. _zoneDragDropInit: function (e) {
  1384. e.stopPropagation();
  1385. e.preventDefault();
  1386. },
  1387. _zoneDragEnter: function (e) {
  1388. var self = this, hasFiles = $.inArray('Files', e.originalEvent.dataTransfer.types) > -1;
  1389. self._zoneDragDropInit(e);
  1390. if (self.isDisabled || !hasFiles) {
  1391. e.originalEvent.dataTransfer.effectAllowed = 'none';
  1392. e.originalEvent.dataTransfer.dropEffect = 'none';
  1393. return;
  1394. }
  1395. $h.addCss(self.$dropZone, 'file-highlighted');
  1396. },
  1397. _zoneDragLeave: function (e) {
  1398. var self = this;
  1399. self._zoneDragDropInit(e);
  1400. if (self.isDisabled) {
  1401. return;
  1402. }
  1403. self.$dropZone.removeClass('file-highlighted');
  1404. },
  1405. _zoneDrop: function (e) {
  1406. var self = this;
  1407. e.preventDefault();
  1408. /** @namespace e.originalEvent.dataTransfer */
  1409. if (self.isDisabled || $h.isEmpty(e.originalEvent.dataTransfer.files)) {
  1410. return;
  1411. }
  1412. self._change(e, 'dragdrop');
  1413. self.$dropZone.removeClass('file-highlighted');
  1414. },
  1415. _uploadClick: function (e) {
  1416. var self = this, $btn = self.$container.find('.fileinput-upload'), $form,
  1417. isEnabled = !$btn.hasClass('disabled') && $h.isEmpty($btn.attr('disabled'));
  1418. if (e && e.isDefaultPrevented()) {
  1419. return;
  1420. }
  1421. if (!self.isAjaxUpload) {
  1422. if (isEnabled && $btn.attr('type') !== 'submit') {
  1423. $form = $btn.closest('form');
  1424. // downgrade to normal form submit if possible
  1425. if ($form.length) {
  1426. $form.trigger('submit');
  1427. }
  1428. e.preventDefault();
  1429. }
  1430. return;
  1431. }
  1432. e.preventDefault();
  1433. if (isEnabled) {
  1434. self.upload();
  1435. }
  1436. },
  1437. _submitForm: function () {
  1438. var self = this;
  1439. return self._isFileSelectionValid() && !self._abort({});
  1440. },
  1441. _clearPreview: function () {
  1442. var self = this, $p = self.$preview,
  1443. $thumbs = self.showUploadedThumbs ? self.getFrames(':not(.file-preview-success)') : self.getFrames();
  1444. $thumbs.each(function () {
  1445. var $thumb = $(this);
  1446. $thumb.remove();
  1447. $h.cleanZoomCache($p.find('#zoom-' + $thumb.attr('id')));
  1448. });
  1449. if (!self.getFrames().length || !self.showPreview) {
  1450. self._resetUpload();
  1451. }
  1452. self._validateDefaultPreview();
  1453. },
  1454. _initSortable: function () {
  1455. var self = this, $el = self.$preview, settings, selector = '.' + $h.SORT_CSS;
  1456. if (!window.KvSortable || $el.find(selector).length === 0) {
  1457. return;
  1458. }
  1459. //noinspection JSUnusedGlobalSymbols
  1460. settings = {
  1461. handle: '.drag-handle-init',
  1462. dataIdAttr: 'data-preview-id',
  1463. scroll: false,
  1464. draggable: selector,
  1465. onSort: function (e) {
  1466. var oldIndex = e.oldIndex, newIndex = e.newIndex, key, $frame;
  1467. self.initialPreview = $h.moveArray(self.initialPreview, oldIndex, newIndex);
  1468. self.initialPreviewConfig = $h.moveArray(self.initialPreviewConfig, oldIndex, newIndex);
  1469. self.previewCache.init();
  1470. for (var i = 0; i < self.initialPreviewConfig.length; i++) {
  1471. if (self.initialPreviewConfig[i] !== null) {
  1472. key = self.initialPreviewConfig[i].key;
  1473. $frame = $(".kv-file-remove[data-key='" + key + "']").closest($h.FRAMES);
  1474. $frame.attr('data-fileindex', 'init_' + i).attr('data-fileindex', 'init_' + i);
  1475. }
  1476. }
  1477. self._raise('filesorted', {
  1478. previewId: $(e.item).attr('id'),
  1479. 'oldIndex': oldIndex,
  1480. 'newIndex': newIndex,
  1481. stack: self.initialPreviewConfig
  1482. });
  1483. }
  1484. };
  1485. if ($el.data('kvsortable')) {
  1486. $el.kvsortable('destroy');
  1487. }
  1488. $.extend(true, settings, self.fileActionSettings.dragSettings);
  1489. $el.kvsortable(settings);
  1490. },
  1491. _setPreviewContent: function (content) {
  1492. var self = this;
  1493. self.$preview.html(content);
  1494. self._autoFitContent();
  1495. },
  1496. _initPreview: function (isInit) {
  1497. var self = this, cap = self.initialCaption || '', out;
  1498. if (!self.previewCache.count()) {
  1499. self._clearPreview();
  1500. if (isInit) {
  1501. self._setCaption(cap);
  1502. } else {
  1503. self._initCaption();
  1504. }
  1505. return;
  1506. }
  1507. out = self.previewCache.out();
  1508. cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
  1509. self._setPreviewContent(out.content);
  1510. self._setInitThumbAttr();
  1511. self._setCaption(cap);
  1512. self._initSortable();
  1513. if (!$h.isEmpty(out.content)) {
  1514. self.$container.removeClass('file-input-new');
  1515. }
  1516. },
  1517. _getZoomButton: function (type) {
  1518. var self = this, label = self.previewZoomButtonIcons[type], css = self.previewZoomButtonClasses[type],
  1519. title = ' title="' + (self.previewZoomButtonTitles[type] || '') + '" ',
  1520. params = title + (type === 'close' ? ' data-dismiss="modal" aria-hidden="true"' : '');
  1521. if (type === 'fullscreen' || type === 'borderless' || type === 'toggleheader') {
  1522. params += ' data-toggle="button" aria-pressed="false" autocomplete="off"';
  1523. }
  1524. return '<button type="button" class="' + css + ' btn-' + type + '"' + params + '>' + label + '</button>';
  1525. },
  1526. _getModalContent: function () {
  1527. var self = this;
  1528. return self._getLayoutTemplate('modal').setTokens({
  1529. 'rtl': self.rtl ? ' kv-rtl' : '',
  1530. 'zoomFrameClass': self.frameClass,
  1531. 'heading': self.msgZoomModalHeading,
  1532. 'prev': self._getZoomButton('prev'),
  1533. 'next': self._getZoomButton('next'),
  1534. 'toggleheader': self._getZoomButton('toggleheader'),
  1535. 'fullscreen': self._getZoomButton('fullscreen'),
  1536. 'borderless': self._getZoomButton('borderless'),
  1537. 'close': self._getZoomButton('close')
  1538. });
  1539. },
  1540. _listenModalEvent: function (event) {
  1541. var self = this, $modal = self.$modal, getParams = function (e) {
  1542. return {
  1543. sourceEvent: e,
  1544. previewId: $modal.data('previewId'),
  1545. modal: $modal
  1546. };
  1547. };
  1548. $modal.on(event + '.bs.modal', function (e) {
  1549. var $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless');
  1550. self._raise('filezoom' + event, getParams(e));
  1551. if (event === 'shown') {
  1552. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1553. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  1554. if ($modal.hasClass('file-zoom-fullscreen')) {
  1555. self._maximizeZoomDialog();
  1556. if ($h.checkFullScreen()) {
  1557. $btnFull.addClass('active').attr('aria-pressed', 'true');
  1558. } else {
  1559. $btnBord.addClass('active').attr('aria-pressed', 'true');
  1560. }
  1561. }
  1562. }
  1563. });
  1564. },
  1565. _initZoom: function () {
  1566. var self = this, $dialog, modalMain = self._getLayoutTemplate('modalMain'), modalId = '#' + $h.MODAL_ID;
  1567. if (!self.showPreview) {
  1568. return;
  1569. }
  1570. self.$modal = $(modalId);
  1571. if (!self.$modal || !self.$modal.length) {
  1572. $dialog = $(document.createElement('div')).html(modalMain).insertAfter(self.$container);
  1573. self.$modal = $(modalId).insertBefore($dialog);
  1574. $dialog.remove();
  1575. }
  1576. $h.initModal(self.$modal);
  1577. self.$modal.html(self._getModalContent());
  1578. $.each($h.MODAL_EVENTS, function (key, event) {
  1579. self._listenModalEvent(event);
  1580. });
  1581. },
  1582. _initZoomButtons: function () {
  1583. var self = this, previewId = self.$modal.data('previewId') || '', $first, $last,
  1584. thumbs = self.getFrames().toArray(), len = thumbs.length, $prev = self.$modal.find('.btn-prev'),
  1585. $next = self.$modal.find('.btn-next');
  1586. if (thumbs.length < 2) {
  1587. $prev.hide();
  1588. $next.hide();
  1589. return;
  1590. } else {
  1591. $prev.show();
  1592. $next.show();
  1593. }
  1594. if (!len) {
  1595. return;
  1596. }
  1597. $first = $(thumbs[0]);
  1598. $last = $(thumbs[len - 1]);
  1599. $prev.removeAttr('disabled');
  1600. $next.removeAttr('disabled');
  1601. if ($first.length && $first.attr('id') === previewId) {
  1602. $prev.attr('disabled', true);
  1603. }
  1604. if ($last.length && $last.attr('id') === previewId) {
  1605. $next.attr('disabled', true);
  1606. }
  1607. },
  1608. _maximizeZoomDialog: function () {
  1609. var self = this, $modal = self.$modal, $head = $modal.find('.modal-header:visible'),
  1610. $foot = $modal.find('.modal-footer:visible'), $body = $modal.find('.modal-body'),
  1611. h = $(window).height(), diff = 0;
  1612. $modal.addClass('file-zoom-fullscreen');
  1613. if ($head && $head.length) {
  1614. h -= $head.outerHeight(true);
  1615. }
  1616. if ($foot && $foot.length) {
  1617. h -= $foot.outerHeight(true);
  1618. }
  1619. if ($body && $body.length) {
  1620. diff = $body.outerHeight(true) - $body.height();
  1621. h -= diff;
  1622. }
  1623. $modal.find('.kv-zoom-body').height(h);
  1624. },
  1625. _resizeZoomDialog: function (fullScreen) {
  1626. var self = this, $modal = self.$modal, $btnFull = $modal.find('.btn-fullscreen'),
  1627. $btnBord = $modal.find('.btn-borderless');
  1628. if ($modal.hasClass('file-zoom-fullscreen')) {
  1629. $h.toggleFullScreen(false);
  1630. if (!fullScreen) {
  1631. if (!$btnFull.hasClass('active')) {
  1632. $modal.removeClass('file-zoom-fullscreen');
  1633. self.$modal.find('.kv-zoom-body').css('height', self.zoomModalHeight);
  1634. } else {
  1635. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  1636. }
  1637. } else {
  1638. if (!$btnFull.hasClass('active')) {
  1639. $modal.removeClass('file-zoom-fullscreen');
  1640. self._resizeZoomDialog(true);
  1641. if ($btnBord.hasClass('active')) {
  1642. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1643. }
  1644. }
  1645. }
  1646. } else {
  1647. if (!fullScreen) {
  1648. self._maximizeZoomDialog();
  1649. return;
  1650. }
  1651. $h.toggleFullScreen(true);
  1652. }
  1653. $modal.focus();
  1654. },
  1655. _setZoomContent: function ($frame, animate) {
  1656. var self = this, $content, tmplt, body, title, $body, $dataEl, config, pid = $frame.attr('id'),
  1657. $modal = self.$modal, $prev = $modal.find('.btn-prev'), $next = $modal.find('.btn-next'), $tmp,
  1658. $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless'), cap, size,
  1659. $btnTogh = $modal.find('.btn-toggleheader'), $zoomPreview = self.$preview.find('#zoom-' + pid);
  1660. tmplt = $zoomPreview.attr('data-template') || 'generic';
  1661. $content = $zoomPreview.find('.kv-file-content');
  1662. body = $content.length ? $content.html() : '';
  1663. cap = $frame.data('caption') || '';
  1664. size = $frame.data('size') || '';
  1665. title = cap + ' ' + size;
  1666. $modal.find('.kv-zoom-title').attr('title', $('<div/>').html(title).text()).html(title);
  1667. $body = $modal.find('.kv-zoom-body');
  1668. $modal.removeClass('kv-single-content');
  1669. if (animate) {
  1670. $tmp = $body.addClass('file-thumb-loading').clone().insertAfter($body);
  1671. $body.html(body).hide();
  1672. $tmp.fadeOut('fast', function () {
  1673. $body.fadeIn('fast', function () {
  1674. $body.removeClass('file-thumb-loading');
  1675. });
  1676. $tmp.remove();
  1677. });
  1678. } else {
  1679. $body.html(body);
  1680. }
  1681. config = self.previewZoomSettings[tmplt];
  1682. if (config) {
  1683. $dataEl = $body.find('.kv-preview-data');
  1684. $h.addCss($dataEl, 'file-zoom-detail');
  1685. $.each(config, function (key, value) {
  1686. $dataEl.css(key, value);
  1687. if (($dataEl.attr('width') && key === 'width') || ($dataEl.attr('height') && key === 'height')) {
  1688. $dataEl.removeAttr(key);
  1689. }
  1690. });
  1691. }
  1692. $modal.data('previewId', pid);
  1693. var $img = $body.find('img');
  1694. if ($img.length) {
  1695. $h.adjustOrientedImage($img, true);
  1696. }
  1697. self._handler($prev, 'click', function () {
  1698. self._zoomSlideShow('prev', pid);
  1699. });
  1700. self._handler($next, 'click', function () {
  1701. self._zoomSlideShow('next', pid);
  1702. });
  1703. self._handler($btnFull, 'click', function () {
  1704. self._resizeZoomDialog(true);
  1705. });
  1706. self._handler($btnBord, 'click', function () {
  1707. self._resizeZoomDialog(false);
  1708. });
  1709. self._handler($btnTogh, 'click', function () {
  1710. var $header = $modal.find('.modal-header'), $floatBar = $modal.find('.modal-body .floating-buttons'),
  1711. ht, $actions = $header.find('.kv-zoom-actions'), resize = function (height) {
  1712. var $body = self.$modal.find('.kv-zoom-body'), h = self.zoomModalHeight;
  1713. if ($modal.hasClass('file-zoom-fullscreen')) {
  1714. h = $body.outerHeight(true);
  1715. if (!height) {
  1716. h = h - $header.outerHeight(true);
  1717. }
  1718. }
  1719. $body.css('height', height ? h + height : h);
  1720. };
  1721. if ($header.is(':visible')) {
  1722. ht = $header.outerHeight(true);
  1723. $header.slideUp('slow', function () {
  1724. $actions.find('.btn').appendTo($floatBar);
  1725. resize(ht);
  1726. });
  1727. } else {
  1728. $floatBar.find('.btn').appendTo($actions);
  1729. $header.slideDown('slow', function () {
  1730. resize();
  1731. });
  1732. }
  1733. $modal.focus();
  1734. });
  1735. self._handler($modal, 'keydown', function (e) {
  1736. var key = e.which || e.keyCode;
  1737. if (key === 37 && !$prev.attr('disabled')) {
  1738. self._zoomSlideShow('prev', pid);
  1739. }
  1740. if (key === 39 && !$next.attr('disabled')) {
  1741. self._zoomSlideShow('next', pid);
  1742. }
  1743. });
  1744. },
  1745. _zoomPreview: function ($btn) {
  1746. var self = this, $frame, $modal = self.$modal;
  1747. if (!$btn.length) {
  1748. throw 'Cannot zoom to detailed preview!';
  1749. }
  1750. $h.initModal($modal);
  1751. $modal.html(self._getModalContent());
  1752. $frame = $btn.closest($h.FRAMES);
  1753. self._setZoomContent($frame);
  1754. $modal.modal('show');
  1755. self._initZoomButtons();
  1756. },
  1757. _zoomSlideShow: function (dir, previewId) {
  1758. var self = this, $btn = self.$modal.find('.kv-zoom-actions .btn-' + dir), $targFrame, i,
  1759. thumbs = self.getFrames().toArray(), len = thumbs.length, out;
  1760. if ($btn.attr('disabled')) {
  1761. return;
  1762. }
  1763. for (i = 0; i < len; i++) {
  1764. if ($(thumbs[i]).attr('id') === previewId) {
  1765. out = dir === 'prev' ? i - 1 : i + 1;
  1766. break;
  1767. }
  1768. }
  1769. if (out < 0 || out >= len || !thumbs[out]) {
  1770. return;
  1771. }
  1772. $targFrame = $(thumbs[out]);
  1773. if ($targFrame.length) {
  1774. self._setZoomContent($targFrame, true);
  1775. }
  1776. self._initZoomButtons();
  1777. self._raise('filezoom' + dir, {'previewId': previewId, modal: self.$modal});
  1778. },
  1779. _initZoomButton: function () {
  1780. var self = this;
  1781. self.$preview.find('.kv-file-zoom').each(function () {
  1782. var $el = $(this);
  1783. self._handler($el, 'click', function () {
  1784. self._zoomPreview($el);
  1785. });
  1786. });
  1787. },
  1788. _clearObjects: function ($el) {
  1789. $el.find('video audio').each(function () {
  1790. this.pause();
  1791. $(this).remove();
  1792. });
  1793. $el.find('img object div').each(function () {
  1794. $(this).remove();
  1795. });
  1796. },
  1797. _clearFileInput: function () {
  1798. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  1799. self.fileInputCleared = true;
  1800. if ($h.isEmpty($el.val())) {
  1801. return;
  1802. }
  1803. // Fix for IE ver < 11, that does not clear file inputs. Requires a sequence of steps to prevent IE
  1804. // crashing but still allow clearing of the file input.
  1805. if (self.isIE9 || self.isIE10) {
  1806. $srcFrm = $el.closest('form');
  1807. $tmpFrm = $(document.createElement('form'));
  1808. $tmpEl = $(document.createElement('div'));
  1809. $el.before($tmpEl);
  1810. if ($srcFrm.length) {
  1811. $srcFrm.after($tmpFrm);
  1812. } else {
  1813. $tmpEl.after($tmpFrm);
  1814. }
  1815. $tmpFrm.append($el).trigger('reset');
  1816. $tmpEl.before($el).remove();
  1817. $tmpFrm.remove();
  1818. } else { // normal input clear behavior for other sane browsers
  1819. $el.val('');
  1820. }
  1821. },
  1822. _resetUpload: function () {
  1823. var self = this;
  1824. self.uploadCache = {content: [], config: [], tags: [], append: true};
  1825. self.uploadCount = 0;
  1826. self.uploadStatus = {};
  1827. self.uploadLog = [];
  1828. self.uploadAsyncCount = 0;
  1829. self.loadedImages = [];
  1830. self.totalImagesCount = 0;
  1831. self.$btnUpload.removeAttr('disabled');
  1832. self._setProgress(0);
  1833. self.$progress.hide();
  1834. self._resetErrors(false);
  1835. self.ajaxAborted = false;
  1836. self.ajaxRequests = [];
  1837. self._resetCanvas();
  1838. self.cacheInitialPreview = {};
  1839. if (self.overwriteInitial) {
  1840. self.initialPreview = [];
  1841. self.initialPreviewConfig = [];
  1842. self.initialPreviewThumbTags = [];
  1843. self.previewCache.data = {
  1844. content: [],
  1845. config: [],
  1846. tags: []
  1847. };
  1848. }
  1849. },
  1850. _resetCanvas: function () {
  1851. var self = this;
  1852. if (self.canvas && self.imageCanvasContext) {
  1853. self.imageCanvasContext.clearRect(0, 0, self.canvas.width, self.canvas.height);
  1854. }
  1855. },
  1856. _hasInitialPreview: function () {
  1857. var self = this;
  1858. return !self.overwriteInitial && self.previewCache.count();
  1859. },
  1860. _resetPreview: function () {
  1861. var self = this, out, cap;
  1862. if (self.previewCache.count()) {
  1863. out = self.previewCache.out();
  1864. self._setPreviewContent(out.content);
  1865. self._setInitThumbAttr();
  1866. cap = self.initialCaption ? self.initialCaption : out.caption;
  1867. self._setCaption(cap);
  1868. } else {
  1869. self._clearPreview();
  1870. self._initCaption();
  1871. }
  1872. if (self.showPreview) {
  1873. self._initZoom();
  1874. self._initSortable();
  1875. }
  1876. },
  1877. _clearDefaultPreview: function () {
  1878. var self = this;
  1879. self.$preview.find('.file-default-preview').remove();
  1880. },
  1881. _validateDefaultPreview: function () {
  1882. var self = this;
  1883. if (!self.showPreview || $h.isEmpty(self.defaultPreviewContent)) {
  1884. return;
  1885. }
  1886. self._setPreviewContent('<div class="file-default-preview">' + self.defaultPreviewContent + '</div>');
  1887. self.$container.removeClass('file-input-new');
  1888. self._initClickable();
  1889. },
  1890. _resetPreviewThumbs: function (isAjax) {
  1891. var self = this, out;
  1892. if (isAjax) {
  1893. self._clearPreview();
  1894. self.clearStack();
  1895. return;
  1896. }
  1897. if (self._hasInitialPreview()) {
  1898. out = self.previewCache.out();
  1899. self._setPreviewContent(out.content);
  1900. self._setInitThumbAttr();
  1901. self._setCaption(out.caption);
  1902. self._initPreviewActions();
  1903. } else {
  1904. self._clearPreview();
  1905. }
  1906. },
  1907. _getLayoutTemplate: function (t) {
  1908. var self = this, template = self.layoutTemplates[t];
  1909. if ($h.isEmpty(self.customLayoutTags)) {
  1910. return template;
  1911. }
  1912. return $h.replaceTags(template, self.customLayoutTags);
  1913. },
  1914. _getPreviewTemplate: function (t) {
  1915. var self = this, template = self.previewTemplates[t];
  1916. if ($h.isEmpty(self.customPreviewTags)) {
  1917. return template;
  1918. }
  1919. return $h.replaceTags(template, self.customPreviewTags);
  1920. },
  1921. _getOutData: function (jqXHR, responseData, filesData) {
  1922. var self = this;
  1923. jqXHR = jqXHR || {};
  1924. responseData = responseData || {};
  1925. filesData = filesData || self.filestack.slice(0) || {};
  1926. return {
  1927. form: self.formdata,
  1928. files: filesData,
  1929. filenames: self.filenames,
  1930. filescount: self.getFilesCount(),
  1931. extra: self._getExtraData(),
  1932. response: responseData,
  1933. reader: self.reader,
  1934. jqXHR: jqXHR
  1935. };
  1936. },
  1937. _getMsgSelected: function (n) {
  1938. var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural;
  1939. return n > 0 ? self.msgSelected.replace('{n}', n).replace('{files}', strFiles) : self.msgNoFilesSelected;
  1940. },
  1941. _getFrame: function (id) {
  1942. var self = this, $frame = $('#' + id);
  1943. if (!$frame.length) {
  1944. self._log('Invalid thumb frame with id: "' + id + '".');
  1945. return null;
  1946. }
  1947. return $frame;
  1948. },
  1949. _getThumbs: function (css) {
  1950. css = css || '';
  1951. return this.getFrames(':not(.file-preview-initial)' + css);
  1952. },
  1953. _getExtraData: function (previewId, index) {
  1954. var self = this, data = self.uploadExtraData;
  1955. if (typeof self.uploadExtraData === "function") {
  1956. data = self.uploadExtraData(previewId, index);
  1957. }
  1958. return data;
  1959. },
  1960. _initXhr: function (xhrobj, previewId, fileCount) {
  1961. var self = this;
  1962. if (xhrobj.upload) {
  1963. xhrobj.upload.addEventListener('progress', function (event) {
  1964. var pct = 0, total = event.total, position = event.loaded || event.position;
  1965. /** @namespace event.lengthComputable */
  1966. if (event.lengthComputable) {
  1967. pct = Math.floor(position / total * 100);
  1968. }
  1969. if (previewId) {
  1970. self._setAsyncUploadStatus(previewId, pct, fileCount);
  1971. } else {
  1972. self._setProgress(pct);
  1973. }
  1974. }, false);
  1975. }
  1976. return xhrobj;
  1977. },
  1978. _mergeAjaxCallback: function (funcName, srcFunc, type) {
  1979. var self = this, settings = self.ajaxSettings, flag = self.mergeAjaxCallbacks, targFunc;
  1980. if (type === 'delete') {
  1981. settings = self.ajaxDeleteSettings;
  1982. flag = self.mergeAjaxDeleteCallbacks;
  1983. }
  1984. targFunc = settings[funcName];
  1985. if (flag && typeof targFunc === "function") {
  1986. if (flag === 'before') {
  1987. settings[funcName] = function () {
  1988. targFunc.apply(this, arguments);
  1989. srcFunc.apply(this, arguments);
  1990. };
  1991. } else {
  1992. settings[funcName] = function () {
  1993. srcFunc.apply(this, arguments);
  1994. targFunc.apply(this, arguments);
  1995. };
  1996. }
  1997. } else {
  1998. settings[funcName] = srcFunc;
  1999. }
  2000. if (type === 'delete') {
  2001. self.ajaxDeleteSettings = settings;
  2002. } else {
  2003. self.ajaxSettings = settings;
  2004. }
  2005. },
  2006. _ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, previewId, index) {
  2007. var self = this, settings;
  2008. if (!self._raise('filepreajax', [previewId, index])) {
  2009. return;
  2010. }
  2011. self._uploadExtra(previewId, index);
  2012. self._mergeAjaxCallback('beforeSend', fnBefore);
  2013. self._mergeAjaxCallback('success', fnSuccess);
  2014. self._mergeAjaxCallback('complete', fnComplete);
  2015. self._mergeAjaxCallback('error', fnError);
  2016. settings = $.extend(true, {}, {
  2017. xhr: function () {
  2018. var xhrobj = $.ajaxSettings.xhr();
  2019. return self._initXhr(xhrobj, previewId, self.getFileStack().length);
  2020. },
  2021. url: index && self.uploadUrlThumb ? self.uploadUrlThumb : self.uploadUrl,
  2022. type: 'POST',
  2023. dataType: 'json',
  2024. data: self.formdata,
  2025. cache: false,
  2026. processData: false,
  2027. contentType: false
  2028. }, self.ajaxSettings);
  2029. self.ajaxRequests.push($.ajax(settings));
  2030. },
  2031. _mergeArray: function (prop, content) {
  2032. var self = this, arr1 = $h.cleanArray(self[prop]), arr2 = $h.cleanArray(content);
  2033. self[prop] = arr1.concat(arr2);
  2034. },
  2035. _initUploadSuccess: function (out, $thumb, allFiles) {
  2036. var self = this, append, data, index, $div, $newCache, content, config, tags, i;
  2037. if (!self.showPreview || typeof out !== 'object' || $.isEmptyObject(out)) {
  2038. return;
  2039. }
  2040. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  2041. self.hasInitData = true;
  2042. content = out.initialPreview || [];
  2043. config = out.initialPreviewConfig || [];
  2044. tags = out.initialPreviewThumbTags || [];
  2045. append = out.append === undefined || out.append;
  2046. if (content.length > 0 && !$h.isArray(content)) {
  2047. content = content.split(self.initialPreviewDelimiter);
  2048. }
  2049. self._mergeArray('initialPreview', content);
  2050. self._mergeArray('initialPreviewConfig', config);
  2051. self._mergeArray('initialPreviewThumbTags', tags);
  2052. if ($thumb !== undefined) {
  2053. if (!allFiles) {
  2054. index = self.previewCache.add(content, config[0], tags[0], append);
  2055. data = self.previewCache.get(index, false);
  2056. $div = $(document.createElement('div')).html(data).hide().insertAfter($thumb);
  2057. $newCache = $div.find('.kv-zoom-cache');
  2058. if ($newCache && $newCache.length) {
  2059. $newCache.insertAfter($thumb);
  2060. }
  2061. $thumb.fadeOut('slow', function () {
  2062. var $newThumb = $div.find('.file-preview-frame');
  2063. if ($newThumb && $newThumb.length) {
  2064. $newThumb.insertBefore($thumb).fadeIn('slow').css('display:inline-block');
  2065. }
  2066. self._initPreviewActions();
  2067. self._clearFileInput();
  2068. $h.cleanZoomCache(self.$preview.find('#zoom-' + $thumb.attr('id')));
  2069. $thumb.remove();
  2070. $div.remove();
  2071. self._initSortable();
  2072. });
  2073. } else {
  2074. i = $thumb.attr('data-fileindex');
  2075. self.uploadCache.content[i] = content[0];
  2076. self.uploadCache.config[i] = config[0] || [];
  2077. self.uploadCache.tags[i] = tags[0] || [];
  2078. self.uploadCache.append = append;
  2079. }
  2080. } else {
  2081. self.previewCache.set(content, config, tags, append);
  2082. self._initPreview();
  2083. self._initPreviewActions();
  2084. }
  2085. }
  2086. },
  2087. _initSuccessThumbs: function () {
  2088. var self = this;
  2089. if (!self.showPreview) {
  2090. return;
  2091. }
  2092. self._getThumbs($h.FRAMES + '.file-preview-success').each(function () {
  2093. var $thumb = $(this), $preview = self.$preview, $remove = $thumb.find('.kv-file-remove');
  2094. $remove.removeAttr('disabled');
  2095. self._handler($remove, 'click', function () {
  2096. var id = $thumb.attr('id'),
  2097. out = self._raise('filesuccessremove', [id, $thumb.attr('data-fileindex')]);
  2098. $h.cleanMemory($thumb);
  2099. if (out === false) {
  2100. return;
  2101. }
  2102. $thumb.fadeOut('slow', function () {
  2103. $h.cleanZoomCache($preview.find('#zoom-' + id));
  2104. $thumb.remove();
  2105. if (!self.getFrames().length) {
  2106. self.reset();
  2107. }
  2108. });
  2109. });
  2110. });
  2111. },
  2112. _checkAsyncComplete: function () {
  2113. var self = this, previewId, i;
  2114. for (i = 0; i < self.filestack.length; i++) {
  2115. if (self.filestack[i]) {
  2116. previewId = self.previewInitId + "-" + i;
  2117. if ($.inArray(previewId, self.uploadLog) === -1) {
  2118. return false;
  2119. }
  2120. }
  2121. }
  2122. return (self.uploadAsyncCount === self.uploadLog.length);
  2123. },
  2124. _uploadExtra: function (previewId, index) {
  2125. var self = this, data = self._getExtraData(previewId, index);
  2126. if (data.length === 0) {
  2127. return;
  2128. }
  2129. $.each(data, function (key, value) {
  2130. self.formdata.append(key, value);
  2131. });
  2132. },
  2133. _uploadSingle: function (i, allFiles) {
  2134. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  2135. previewId = self.previewInitId + "-" + i, $thumb, chkComplete, $btnUpload, $btnDelete,
  2136. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData), uploadFailed,
  2137. $prog = $('#' + previewId).find('.file-thumb-progress'), fnBefore, fnSuccess, fnComplete, fnError,
  2138. updateUploadLog, params = {id: previewId, index: i};
  2139. self.formdata = formdata;
  2140. if (self.showPreview) {
  2141. $thumb = $('#' + previewId + ':not(.file-preview-initial)');
  2142. $btnUpload = $thumb.find('.kv-file-upload');
  2143. $btnDelete = $thumb.find('.kv-file-remove');
  2144. $prog.show();
  2145. }
  2146. if (total === 0 || !hasPostData || ($btnUpload && $btnUpload.hasClass('disabled')) || self._abort(params)) {
  2147. return;
  2148. }
  2149. updateUploadLog = function (i, previewId) {
  2150. if (!uploadFailed) {
  2151. self.updateStack(i, undefined);
  2152. }
  2153. self.uploadLog.push(previewId);
  2154. if (self._checkAsyncComplete()) {
  2155. self.fileBatchCompleted = true;
  2156. }
  2157. };
  2158. chkComplete = function () {
  2159. var u = self.uploadCache, $initThumbs, i, j, len = 0, data = self.cacheInitialPreview;
  2160. if (!self.fileBatchCompleted) {
  2161. return;
  2162. }
  2163. if (data && data.content) {
  2164. len = data.content.length;
  2165. }
  2166. setTimeout(function () {
  2167. var triggerReset = self.getFileStack(true).length === 0;
  2168. if (self.showPreview) {
  2169. self.previewCache.set(u.content, u.config, u.tags, u.append);
  2170. if (len) {
  2171. for (i = 0; i < u.content.length; i++) {
  2172. j = i + len;
  2173. data.content[j] = u.content[i];
  2174. //noinspection JSUnresolvedVariable
  2175. if (data.config.length) {
  2176. data.config[j] = u.config[i];
  2177. }
  2178. if (data.tags.length) {
  2179. data.tags[j] = u.tags[i];
  2180. }
  2181. }
  2182. self.initialPreview = $h.cleanArray(data.content);
  2183. self.initialPreviewConfig = $h.cleanArray(data.config);
  2184. self.initialPreviewThumbTags = $h.cleanArray(data.tags);
  2185. } else {
  2186. self.initialPreview = u.content;
  2187. self.initialPreviewConfig = u.config;
  2188. self.initialPreviewThumbTags = u.tags;
  2189. }
  2190. self.cacheInitialPreview = {};
  2191. if (self.hasInitData) {
  2192. self._initPreview();
  2193. self._initPreviewActions();
  2194. }
  2195. }
  2196. self.unlock(triggerReset);
  2197. if (triggerReset) {
  2198. self._clearFileInput();
  2199. }
  2200. $initThumbs = self.$preview.find('.file-preview-initial');
  2201. if (self.uploadAsync && $initThumbs.length) {
  2202. $h.addCss($initThumbs, $h.SORT_CSS);
  2203. self._initSortable();
  2204. }
  2205. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  2206. self.uploadCount = 0;
  2207. self.uploadStatus = {};
  2208. self.uploadLog = [];
  2209. self._setProgress(101);
  2210. }, 100);
  2211. };
  2212. fnBefore = function (jqXHR) {
  2213. outData = self._getOutData(jqXHR);
  2214. self.fileBatchCompleted = false;
  2215. if (self.showPreview) {
  2216. if (!$thumb.hasClass('file-preview-success')) {
  2217. self._setThumbStatus($thumb, 'Loading');
  2218. $h.addCss($thumb, 'file-uploading');
  2219. }
  2220. $btnUpload.attr('disabled', true);
  2221. $btnDelete.attr('disabled', true);
  2222. }
  2223. if (!allFiles) {
  2224. self.lock();
  2225. }
  2226. self._raise('filepreupload', [outData, previewId, i]);
  2227. $.extend(true, params, outData);
  2228. if (self._abort(params)) {
  2229. jqXHR.abort();
  2230. self._setProgressCancelled();
  2231. }
  2232. };
  2233. fnSuccess = function (data, textStatus, jqXHR) {
  2234. var pid = self.showPreview && $thumb.attr('id') ? $thumb.attr('id') : previewId;
  2235. outData = self._getOutData(jqXHR, data);
  2236. $.extend(true, params, outData);
  2237. setTimeout(function () {
  2238. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  2239. if (self.showPreview) {
  2240. self._setThumbStatus($thumb, 'Success');
  2241. $btnUpload.hide();
  2242. self._initUploadSuccess(data, $thumb, allFiles);
  2243. self._setProgress(101, $prog);
  2244. }
  2245. self._raise('fileuploaded', [outData, pid, i]);
  2246. if (!allFiles) {
  2247. self.updateStack(i, undefined);
  2248. } else {
  2249. updateUploadLog(i, pid);
  2250. }
  2251. } else {
  2252. uploadFailed = true;
  2253. self._showUploadError(data.error, params);
  2254. self._setPreviewError($thumb, i, self.filestack[i], self.retryErrorUploads);
  2255. if (!self.retryErrorUploads) {
  2256. $btnUpload.hide();
  2257. }
  2258. if (allFiles) {
  2259. updateUploadLog(i, pid);
  2260. }
  2261. self._setProgress(101, $('#' + pid).find('.file-thumb-progress'), self.msgUploadError);
  2262. }
  2263. }, 100);
  2264. };
  2265. fnComplete = function () {
  2266. setTimeout(function () {
  2267. if (self.showPreview) {
  2268. $btnUpload.removeAttr('disabled');
  2269. $btnDelete.removeAttr('disabled');
  2270. $thumb.removeClass('file-uploading');
  2271. }
  2272. if (!allFiles) {
  2273. self.unlock(false);
  2274. self._clearFileInput();
  2275. } else {
  2276. chkComplete();
  2277. }
  2278. self._initSuccessThumbs();
  2279. }, 100);
  2280. };
  2281. fnError = function (jqXHR, textStatus, errorThrown) {
  2282. var op = self.ajaxOperations.uploadThumb,
  2283. errMsg = self._parseError(op, jqXHR, errorThrown, (allFiles && self.filestack[i].name ? self.filestack[i].name : null));
  2284. uploadFailed = true;
  2285. setTimeout(function () {
  2286. if (allFiles) {
  2287. updateUploadLog(i, previewId);
  2288. }
  2289. self.uploadStatus[previewId] = 100;
  2290. self._setPreviewError($thumb, i, self.filestack[i], self.retryErrorUploads);
  2291. if (!self.retryErrorUploads) {
  2292. $btnUpload.hide();
  2293. }
  2294. $.extend(true, params, self._getOutData(jqXHR));
  2295. self._setProgress(101, $prog, self.msgAjaxProgressError.replace('{operation}', op));
  2296. self._setProgress(101, $('#' + previewId).find('.file-thumb-progress'), self.msgUploadError);
  2297. self._showUploadError(errMsg, params);
  2298. }, 100);
  2299. };
  2300. formdata.append(self.uploadFileAttr, self.filestack[i], self.filenames[i]);
  2301. formdata.append('file_id', i);
  2302. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, previewId, i);
  2303. },
  2304. _uploadBatch: function () {
  2305. var self = this, files = self.filestack, total = files.length, params = {}, fnBefore, fnSuccess, fnError,
  2306. fnComplete, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  2307. setAllUploaded;
  2308. self.formdata = new FormData();
  2309. if (total === 0 || !hasPostData || self._abort(params)) {
  2310. return;
  2311. }
  2312. setAllUploaded = function () {
  2313. $.each(files, function (key) {
  2314. self.updateStack(key, undefined);
  2315. });
  2316. self._clearFileInput();
  2317. };
  2318. fnBefore = function (jqXHR) {
  2319. self.lock();
  2320. var outData = self._getOutData(jqXHR);
  2321. if (self.showPreview) {
  2322. self._getThumbs().each(function () {
  2323. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  2324. $btnDelete = $thumb.find('.kv-file-remove');
  2325. if (!$thumb.hasClass('file-preview-success')) {
  2326. self._setThumbStatus($thumb, 'Loading');
  2327. $h.addCss($thumb, 'file-uploading');
  2328. }
  2329. $btnUpload.attr('disabled', true);
  2330. $btnDelete.attr('disabled', true);
  2331. });
  2332. }
  2333. self._raise('filebatchpreupload', [outData]);
  2334. if (self._abort(outData)) {
  2335. jqXHR.abort();
  2336. self._setProgressCancelled();
  2337. }
  2338. };
  2339. fnSuccess = function (data, textStatus, jqXHR) {
  2340. /** @namespace data.errorkeys */
  2341. var outData = self._getOutData(jqXHR, data), key = 0,
  2342. $thumbs = self._getThumbs(':not(.file-preview-success)'),
  2343. keys = $h.isEmpty(data) || $h.isEmpty(data.errorkeys) ? [] : data.errorkeys;
  2344. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  2345. self._raise('filebatchuploadsuccess', [outData]);
  2346. setAllUploaded();
  2347. if (self.showPreview) {
  2348. $thumbs.each(function () {
  2349. var $thumb = $(this);
  2350. self._setThumbStatus($thumb, 'Success');
  2351. $thumb.removeClass('file-uploading');
  2352. $thumb.find('.kv-file-upload').hide().removeAttr('disabled');
  2353. });
  2354. self._initUploadSuccess(data);
  2355. } else {
  2356. self.reset();
  2357. }
  2358. self._setProgress(101);
  2359. } else {
  2360. if (self.showPreview) {
  2361. $thumbs.each(function () {
  2362. var $thumb = $(this), i = $thumb.attr('data-fileindex');
  2363. $thumb.removeClass('file-uploading');
  2364. $thumb.find('.kv-file-upload').removeAttr('disabled');
  2365. $thumb.find('.kv-file-remove').removeAttr('disabled');
  2366. if (keys.length === 0 || $.inArray(key, keys) !== -1) {
  2367. self._setPreviewError($thumb, i, self.filestack[i], self.retryErrorUploads);
  2368. if (!self.retryErrorUploads) {
  2369. $thumb.find('.kv-file-upload').hide();
  2370. self.updateStack(i, undefined);
  2371. }
  2372. } else {
  2373. $thumb.find('.kv-file-upload').hide();
  2374. self._setThumbStatus($thumb, 'Success');
  2375. self.updateStack(i, undefined);
  2376. }
  2377. if (!$thumb.hasClass('file-preview-error') || self.retryErrorUploads) {
  2378. key++;
  2379. }
  2380. });
  2381. self._initUploadSuccess(data);
  2382. }
  2383. self._showUploadError(data.error, outData, 'filebatchuploaderror');
  2384. self._setProgress(101, self.$progress, self.msgUploadError);
  2385. }
  2386. };
  2387. fnComplete = function () {
  2388. self.unlock();
  2389. self._initSuccessThumbs();
  2390. self._clearFileInput();
  2391. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  2392. };
  2393. fnError = function (jqXHR, textStatus, errorThrown) {
  2394. var outData = self._getOutData(jqXHR), op = self.ajaxOperations.uploadBatch,
  2395. errMsg = self._parseError(op, jqXHR, errorThrown);
  2396. self._showUploadError(errMsg, outData, 'filebatchuploaderror');
  2397. self.uploadFileCount = total - 1;
  2398. if (!self.showPreview) {
  2399. return;
  2400. }
  2401. self._getThumbs().each(function () {
  2402. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  2403. $thumb.removeClass('file-uploading');
  2404. if (self.filestack[key] !== undefined) {
  2405. self._setPreviewError($thumb);
  2406. }
  2407. });
  2408. self._getThumbs().removeClass('file-uploading');
  2409. self._getThumbs(' .kv-file-upload').removeAttr('disabled');
  2410. self._getThumbs(' .kv-file-delete').removeAttr('disabled');
  2411. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  2412. };
  2413. $.each(files, function (key, data) {
  2414. if (!$h.isEmpty(files[key])) {
  2415. self.formdata.append(self.uploadFileAttr, data, self.filenames[key]);
  2416. }
  2417. });
  2418. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  2419. },
  2420. _uploadExtraOnly: function () {
  2421. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  2422. self.formdata = new FormData();
  2423. if (self._abort(params)) {
  2424. return;
  2425. }
  2426. fnBefore = function (jqXHR) {
  2427. self.lock();
  2428. var outData = self._getOutData(jqXHR);
  2429. self._raise('filebatchpreupload', [outData]);
  2430. self._setProgress(50);
  2431. params.data = outData;
  2432. params.xhr = jqXHR;
  2433. if (self._abort(params)) {
  2434. jqXHR.abort();
  2435. self._setProgressCancelled();
  2436. }
  2437. };
  2438. fnSuccess = function (data, textStatus, jqXHR) {
  2439. var outData = self._getOutData(jqXHR, data);
  2440. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  2441. self._raise('filebatchuploadsuccess', [outData]);
  2442. self._clearFileInput();
  2443. self._initUploadSuccess(data);
  2444. self._setProgress(101);
  2445. } else {
  2446. self._showUploadError(data.error, outData, 'filebatchuploaderror');
  2447. }
  2448. };
  2449. fnComplete = function () {
  2450. self.unlock();
  2451. self._clearFileInput();
  2452. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  2453. };
  2454. fnError = function (jqXHR, textStatus, errorThrown) {
  2455. var outData = self._getOutData(jqXHR), op = self.ajaxOperations.uploadExtra,
  2456. errMsg = self._parseError(op, jqXHR, errorThrown);
  2457. params.data = outData;
  2458. self._showUploadError(errMsg, outData, 'filebatchuploaderror');
  2459. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  2460. };
  2461. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  2462. },
  2463. _deleteFileIndex: function ($frame) {
  2464. var self = this, ind = $frame.attr('data-fileindex');
  2465. if (ind.substring(0, 5) === 'init_') {
  2466. ind = parseInt(ind.replace('init_', ''));
  2467. self.initialPreview = $h.spliceArray(self.initialPreview, ind);
  2468. self.initialPreviewConfig = $h.spliceArray(self.initialPreviewConfig, ind);
  2469. self.initialPreviewThumbTags = $h.spliceArray(self.initialPreviewThumbTags, ind);
  2470. self.getFrames().each(function () {
  2471. var $nFrame = $(this), nInd = $nFrame.attr('data-fileindex');
  2472. if (nInd.substring(0, 5) === 'init_') {
  2473. nInd = parseInt(nInd.replace('init_', ''));
  2474. if (nInd > ind) {
  2475. nInd--;
  2476. $nFrame.attr('data-fileindex', 'init_' + nInd);
  2477. }
  2478. }
  2479. });
  2480. if (self.uploadAsync) {
  2481. self.cacheInitialPreview = self.getPreview();
  2482. }
  2483. }
  2484. },
  2485. _initFileActions: function () {
  2486. var self = this, $preview = self.$preview;
  2487. if (!self.showPreview) {
  2488. return;
  2489. }
  2490. self._initZoomButton();
  2491. self.getFrames(' .kv-file-remove').each(function () {
  2492. var $el = $(this), $frame = $el.closest($h.FRAMES), hasError, id = $frame.attr('id'),
  2493. ind = $frame.attr('data-fileindex'), n, cap, status;
  2494. self._handler($el, 'click', function () {
  2495. status = self._raise('filepreremove', [id, ind]);
  2496. if (status === false || !self._validateMinCount()) {
  2497. return false;
  2498. }
  2499. hasError = $frame.hasClass('file-preview-error');
  2500. $h.cleanMemory($frame);
  2501. $frame.fadeOut('slow', function () {
  2502. $h.cleanZoomCache($preview.find('#zoom-' + id));
  2503. self.updateStack(ind, undefined);
  2504. self._clearObjects($frame);
  2505. $frame.remove();
  2506. if (id && hasError) {
  2507. self.$errorContainer.find('li[data-file-id="' + id + '"]').fadeOut('fast', function () {
  2508. $(this).remove();
  2509. if (!self._errorsExist()) {
  2510. self._resetErrors();
  2511. }
  2512. });
  2513. }
  2514. self._clearFileInput();
  2515. var filestack = self.getFileStack(true), chk = self.previewCache.count(),
  2516. len = filestack.length, hasThumb = self.showPreview && self.getFrames().length;
  2517. if (len === 0 && chk === 0 && !hasThumb) {
  2518. self.reset();
  2519. } else {
  2520. n = chk + len;
  2521. cap = n > 1 ? self._getMsgSelected(n) : (filestack[0] ? self._getFileNames()[0] : '');
  2522. self._setCaption(cap);
  2523. }
  2524. self._raise('fileremoved', [id, ind]);
  2525. });
  2526. });
  2527. });
  2528. self.getFrames(' .kv-file-upload').each(function () {
  2529. var $el = $(this);
  2530. self._handler($el, 'click', function () {
  2531. var $frame = $el.closest($h.FRAMES), ind = $frame.attr('data-fileindex');
  2532. self.$progress.hide();
  2533. if ($frame.hasClass('file-preview-error') && !self.retryErrorUploads) {
  2534. return;
  2535. }
  2536. self._uploadSingle(ind, false);
  2537. });
  2538. });
  2539. },
  2540. _initPreviewActions: function () {
  2541. var self = this, $preview = self.$preview, deleteExtraData = self.deleteExtraData || {},
  2542. btnRemove = $h.FRAMES + ' .kv-file-remove', settings = self.fileActionSettings,
  2543. origClass = settings.removeClass, errClass = settings.removeErrorClass,
  2544. resetProgress = function () {
  2545. var hasFiles = self.isAjaxUpload ? self.previewCache.count() : self.$element.get(0).files.length;
  2546. if (!$preview.find($h.FRAMES).length && !hasFiles) {
  2547. self._setCaption('');
  2548. self.reset();
  2549. self.initialCaption = '';
  2550. }
  2551. };
  2552. self._initZoomButton();
  2553. $preview.find(btnRemove).each(function () {
  2554. var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key'),
  2555. fnBefore, fnSuccess, fnError;
  2556. if ($h.isEmpty(vUrl) || vKey === undefined) {
  2557. return;
  2558. }
  2559. var $frame = $el.closest($h.FRAMES), cache = self.previewCache.data,
  2560. settings, params, index = $frame.attr('data-fileindex'), config, extraData;
  2561. index = parseInt(index.replace('init_', ''));
  2562. config = $h.isEmpty(cache.config) && $h.isEmpty(cache.config[index]) ? null : cache.config[index];
  2563. extraData = $h.isEmpty(config) || $h.isEmpty(config.extra) ? deleteExtraData : config.extra;
  2564. if (typeof extraData === "function") {
  2565. extraData = extraData();
  2566. }
  2567. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  2568. fnBefore = function (jqXHR) {
  2569. self.ajaxAborted = false;
  2570. self._raise('filepredelete', [vKey, jqXHR, extraData]);
  2571. $el.removeClass(errClass);
  2572. if (self._abort()) {
  2573. jqXHR.abort();
  2574. } else {
  2575. $h.addCss($frame, 'file-uploading');
  2576. $h.addCss($el, 'disabled ' + origClass);
  2577. }
  2578. };
  2579. fnSuccess = function (data, textStatus, jqXHR) {
  2580. var n, cap;
  2581. if (!$h.isEmpty(data) && !$h.isEmpty(data.error)) {
  2582. params.jqXHR = jqXHR;
  2583. params.response = data;
  2584. self._showError(data.error, params, 'filedeleteerror');
  2585. $frame.removeClass('file-uploading');
  2586. $el.removeClass('disabled ' + origClass).addClass(errClass);
  2587. resetProgress();
  2588. return;
  2589. }
  2590. $frame.removeClass('file-uploading').addClass('file-deleted');
  2591. $frame.fadeOut('slow', function () {
  2592. index = parseInt(($frame.attr('data-fileindex')).replace('init_', ''));
  2593. self.previewCache.unset(index);
  2594. n = self.previewCache.count();
  2595. cap = n > 0 ? self._getMsgSelected(n) : '';
  2596. self._deleteFileIndex($frame);
  2597. self._setCaption(cap);
  2598. self._raise('filedeleted', [vKey, jqXHR, extraData]);
  2599. $h.cleanZoomCache($preview.find('#zoom-' + $frame.attr('id')));
  2600. self._clearObjects($frame);
  2601. $frame.remove();
  2602. resetProgress();
  2603. });
  2604. };
  2605. fnError = function (jqXHR, textStatus, errorThrown) {
  2606. var op = self.ajaxOperations.deleteThumb, errMsg = self._parseError(op, jqXHR, errorThrown);
  2607. params.jqXHR = jqXHR;
  2608. params.response = {};
  2609. self._showError(errMsg, params, 'filedeleteerror');
  2610. $frame.removeClass('file-uploading');
  2611. $el.removeClass('disabled ' + origClass).addClass(errClass);
  2612. resetProgress();
  2613. };
  2614. self._mergeAjaxCallback('beforeSend', fnBefore, 'delete');
  2615. self._mergeAjaxCallback('success', fnSuccess, 'delete');
  2616. self._mergeAjaxCallback('error', fnError, 'delete');
  2617. settings = $.extend(true, {}, {
  2618. url: vUrl,
  2619. type: 'POST',
  2620. dataType: 'json',
  2621. data: $.extend(true, {}, {key: vKey}, extraData)
  2622. }, self.ajaxDeleteSettings);
  2623. self._handler($el, 'click', function () {
  2624. if (!self._validateMinCount()) {
  2625. return false;
  2626. }
  2627. self.ajaxAborted = false;
  2628. self._raise('filebeforedelete', [vKey, extraData]);
  2629. //noinspection JSUnresolvedVariable,JSHint
  2630. if (self.ajaxAborted instanceof Promise) {
  2631. self.ajaxAborted.then(function (result) {
  2632. if (!result) {
  2633. $.ajax(settings);
  2634. }
  2635. });
  2636. } else {
  2637. if (!self.ajaxAborted) {
  2638. $.ajax(settings);
  2639. }
  2640. }
  2641. });
  2642. });
  2643. },
  2644. _hideFileIcon: function () {
  2645. var self = this;
  2646. if (self.overwriteInitial) {
  2647. self.$captionContainer.removeClass('icon-visible');
  2648. }
  2649. },
  2650. _showFileIcon: function () {
  2651. var self = this;
  2652. $h.addCss(self.$captionContainer, 'icon-visible');
  2653. },
  2654. _getSize: function (bytes) {
  2655. var self = this, size = parseFloat(bytes), i, func = self.fileSizeGetter, sizes, out;
  2656. if (!$.isNumeric(bytes) || !$.isNumeric(size)) {
  2657. return '';
  2658. }
  2659. if (typeof func === 'function') {
  2660. out = func(size);
  2661. } else {
  2662. if (size === 0) {
  2663. out = '0.00 B';
  2664. } else {
  2665. i = Math.floor(Math.log(size) / Math.log(1024));
  2666. sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  2667. out = (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + sizes[i];
  2668. }
  2669. }
  2670. return self._getLayoutTemplate('size').replace('{sizeText}', out);
  2671. },
  2672. _generatePreviewTemplate: function (cat, data, fname, ftype, previewId, isError, size, frameClass, foot, ind, templ) {
  2673. var self = this, caption = self.slug(fname), prevContent, zoomContent = '', styleAttribs = '',
  2674. screenW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
  2675. config = screenW < 400 ? (self.previewSettingsSmall[cat] || self.defaults.previewSettingsSmall[cat]) :
  2676. (self.previewSettings[cat] || self.defaults.previewSettings[cat]),
  2677. footer = foot || self._renderFileFooter(caption, size, 'auto', isError),
  2678. hasIconSetting = self._getPreviewIcon(fname), typeCss = 'type-default',
  2679. forcePrevIcon = hasIconSetting && self.preferIconicPreview,
  2680. forceZoomIcon = hasIconSetting && self.preferIconicZoomPreview, getContent;
  2681. if (config) {
  2682. $.each(config, function (key, val) {
  2683. styleAttribs += key + ':' + val + ';';
  2684. });
  2685. }
  2686. getContent = function (c, d, zoom, frameCss) {
  2687. var id = zoom ? 'zoom-' + previewId : previewId, tmplt = self._getPreviewTemplate(c),
  2688. css = (frameClass || '') + ' ' + frameCss;
  2689. if (self.frameClass) {
  2690. css = self.frameClass + ' ' + css;
  2691. }
  2692. if (zoom) {
  2693. css = css.replace(' ' + $h.SORT_CSS, '');
  2694. }
  2695. tmplt = self._parseFilePreviewIcon(tmplt, fname);
  2696. if (c === 'text') {
  2697. d = $h.htmlEncode(d);
  2698. }
  2699. if (cat === 'object' && !ftype) {
  2700. $.each(self.defaults.fileTypeSettings, function (key, func) {
  2701. if (key === 'object' || key === 'other') {
  2702. return;
  2703. }
  2704. if (func(fname, ftype)) {
  2705. typeCss = 'type-' + key;
  2706. }
  2707. });
  2708. }
  2709. return tmplt.setTokens({
  2710. 'previewId': id,
  2711. 'caption': caption,
  2712. 'frameClass': css,
  2713. 'type': ftype,
  2714. 'fileindex': ind,
  2715. 'typeCss': typeCss,
  2716. 'footer': footer,
  2717. 'data': d,
  2718. 'template': templ || cat,
  2719. 'style': styleAttribs ? 'style="' + styleAttribs + '"' : ''
  2720. });
  2721. };
  2722. ind = ind || previewId.slice(previewId.lastIndexOf('-') + 1);
  2723. if (self.fileActionSettings.showZoom) {
  2724. zoomContent = getContent((forceZoomIcon ? 'other' : cat), data, true, 'kv-zoom-thumb');
  2725. }
  2726. zoomContent = '\n' + self._getLayoutTemplate('zoomCache').replace('{zoomContent}', zoomContent);
  2727. prevContent = getContent((forcePrevIcon ? 'other' : cat), data, false, 'kv-preview-thumb');
  2728. return prevContent + zoomContent;
  2729. },
  2730. _previewDefault: function (file, previewId, isDisabled) {
  2731. var self = this, $preview = self.$preview;
  2732. if (!self.showPreview) {
  2733. return;
  2734. }
  2735. var fname = file ? file.name : '', ftype = file ? file.type : '', content, size = file.size || 0,
  2736. caption = self.slug(fname), isError = isDisabled === true && !self.isAjaxUpload,
  2737. data = $h.objUrl.createObjectURL(file);
  2738. self._clearDefaultPreview();
  2739. content = self._generatePreviewTemplate('other', data, fname, ftype, previewId, isError, size);
  2740. $preview.append("\n" + content);
  2741. self._setThumbAttr(previewId, caption, size);
  2742. if (isDisabled === true && self.isAjaxUpload) {
  2743. self._setThumbStatus($('#' + previewId), 'Error');
  2744. }
  2745. },
  2746. _previewFile: function (i, file, theFile, previewId, data, fileInfo) {
  2747. if (!this.showPreview) {
  2748. return;
  2749. }
  2750. var self = this, fname = file ? file.name : '', ftype = fileInfo.type, caption = fileInfo.name,
  2751. cat = self._parseFileType(ftype, fname), types = self.allowedPreviewTypes, content,
  2752. mimes = self.allowedPreviewMimeTypes, $preview = self.$preview, fsize = file.size || 0,
  2753. chkTypes = types && types.indexOf(cat) >= 0, chkMimes = mimes && mimes.indexOf(ftype) !== -1,
  2754. iData = (cat === 'text' || cat === 'html' || cat === 'image') ? theFile.target.result : data;
  2755. /** @namespace window.DOMPurify */
  2756. if (cat === 'html' && self.purifyHtml && window.DOMPurify) {
  2757. iData = window.DOMPurify.sanitize(iData);
  2758. }
  2759. if (chkTypes || chkMimes) {
  2760. content = self._generatePreviewTemplate(cat, iData, fname, ftype, previewId, false, fsize);
  2761. self._clearDefaultPreview();
  2762. $preview.append("\n" + content);
  2763. var $img = $preview.find('#' + previewId + ' img');
  2764. if ($img.length && self.autoOrientImage) {
  2765. $h.validateOrientation(file, function (value) {
  2766. if (!value) {
  2767. self._validateImage(previewId, caption, ftype, fsize, iData);
  2768. return;
  2769. }
  2770. var $zoomImg = $preview.find('#zoom-' + previewId + ' img'), css = 'rotate-' + value;
  2771. if (value > 4) {
  2772. css += ($img.width() > $img.height() ? ' is-portrait-gt4' : ' is-landscape-gt4');
  2773. }
  2774. $h.addCss($img, css);
  2775. $h.addCss($zoomImg, css);
  2776. self._raise('fileimageoriented', {'$img': $img, 'file': file});
  2777. self._validateImage(previewId, caption, ftype, fsize, iData);
  2778. $h.adjustOrientedImage($img);
  2779. });
  2780. } else {
  2781. self._validateImage(previewId, caption, ftype, fsize, iData);
  2782. }
  2783. } else {
  2784. self._previewDefault(file, previewId);
  2785. }
  2786. self._setThumbAttr(previewId, caption, fsize);
  2787. self._initSortable();
  2788. },
  2789. _setThumbAttr: function (id, caption, size) {
  2790. var self = this, $frame = $('#' + id);
  2791. if ($frame.length) {
  2792. size = size && size > 0 ? self._getSize(size) : '';
  2793. $frame.data({'caption': caption, 'size': size});
  2794. }
  2795. },
  2796. _setInitThumbAttr: function () {
  2797. var self = this, data = self.previewCache.data, len = self.previewCache.count(), config,
  2798. caption, size, previewId;
  2799. if (len === 0) {
  2800. return;
  2801. }
  2802. for (var i = 0; i < len; i++) {
  2803. config = data.config[i];
  2804. previewId = self.previewInitId + '-' + 'init_' + i;
  2805. caption = $h.ifSet('caption', config, $h.ifSet('filename', config));
  2806. size = $h.ifSet('size', config);
  2807. self._setThumbAttr(previewId, caption, size);
  2808. }
  2809. },
  2810. _slugDefault: function (text) {
  2811. return $h.isEmpty(text) ? '' : String(text).replace(/[\-\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_');
  2812. },
  2813. _readFiles: function (files) {
  2814. this.reader = new FileReader();
  2815. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  2816. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  2817. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  2818. settings = self.fileTypeSettings, ctr = self.filestack.length, readFile,
  2819. fileTypes = self.allowedFileTypes, typLen = fileTypes ? fileTypes.length : 0,
  2820. fileExt = self.allowedFileExtensions, strExt = $h.isEmpty(fileExt) ? '' : fileExt.join(', '),
  2821. maxPreviewSize = self.maxFilePreviewSize && parseFloat(self.maxFilePreviewSize),
  2822. canPreview = $preview.length && (!maxPreviewSize || isNaN(maxPreviewSize)),
  2823. throwError = function (msg, file, previewId, index) {
  2824. var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}),
  2825. p2 = {id: previewId, index: index, file: file, files: files}, $thumb;
  2826. self._previewDefault(file, previewId, true);
  2827. if (self.isAjaxUpload) {
  2828. self.addToStack(undefined);
  2829. setTimeout(function () {
  2830. readFile(index + 1);
  2831. }, 100);
  2832. } else {
  2833. numFiles = 0;
  2834. }
  2835. self._initFileActions();
  2836. $thumb = $('#' + previewId);
  2837. $thumb.find('.kv-file-upload').hide();
  2838. if (self.removeFromPreviewOnError) {
  2839. $thumb.remove();
  2840. }
  2841. self.isError = self.isAjaxUpload ? self._showUploadError(msg, p1) : self._showError(msg, p2);
  2842. self._updateFileDetails(numFiles);
  2843. };
  2844. self.loadedImages = [];
  2845. self.totalImagesCount = 0;
  2846. $.each(files, function (key, file) {
  2847. var func = self.fileTypeSettings.image;
  2848. if (func && func(file.type)) {
  2849. self.totalImagesCount++;
  2850. }
  2851. });
  2852. readFile = function (i) {
  2853. if ($h.isEmpty($el.attr('multiple'))) {
  2854. numFiles = 1;
  2855. }
  2856. if (i >= numFiles) {
  2857. if (self.isAjaxUpload && self.filestack.length > 0) {
  2858. self._raise('filebatchselected', [self.getFileStack()]);
  2859. } else {
  2860. self._raise('filebatchselected', [files]);
  2861. }
  2862. $container.removeClass('file-thumb-loading');
  2863. $status.html('');
  2864. return;
  2865. }
  2866. var node = ctr + i, previewId = previewInitId + "-" + node, file = files[i], fSizeKB, j, msg,
  2867. fnText = settings.text, fnImage = settings.image, fnHtml = settings.html, typ, chk, typ1, typ2,
  2868. caption = file.name ? self.slug(file.name) : '', fileSize = (file.size || 0) / 1000,
  2869. fileExtExpr = '', previewData = $h.objUrl.createObjectURL(file), fileCount = 0, strTypes = '',
  2870. func, knownTypes = 0, isText, isHtml, isImage, txtFlag, processFileLoaded = function () {
  2871. var msg = msgProgress.setTokens({
  2872. 'index': i + 1,
  2873. 'files': numFiles,
  2874. 'percent': 50,
  2875. 'name': caption
  2876. });
  2877. setTimeout(function () {
  2878. $status.html(msg);
  2879. self._updateFileDetails(numFiles);
  2880. readFile(i + 1);
  2881. }, 100);
  2882. self._raise('fileloaded', [file, previewId, i, reader]);
  2883. };
  2884. if (typLen > 0) {
  2885. for (j = 0; j < typLen; j++) {
  2886. typ1 = fileTypes[j];
  2887. typ2 = self.msgFileTypes[typ1] || typ1;
  2888. strTypes += j === 0 ? typ2 : ', ' + typ2;
  2889. }
  2890. }
  2891. if (caption === false) {
  2892. readFile(i + 1);
  2893. return;
  2894. }
  2895. if (caption.length === 0) {
  2896. msg = self.msgInvalidFileName.replace('{name}', $h.htmlEncode(file.name));
  2897. throwError(msg, file, previewId, i);
  2898. return;
  2899. }
  2900. if (!$h.isEmpty(fileExt)) {
  2901. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  2902. }
  2903. fSizeKB = fileSize.toFixed(2);
  2904. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  2905. msg = self.msgSizeTooLarge.setTokens({
  2906. 'name': caption,
  2907. 'size': fSizeKB,
  2908. 'maxSize': self.maxFileSize
  2909. });
  2910. throwError(msg, file, previewId, i);
  2911. return;
  2912. }
  2913. if (self.minFileSize !== null && fileSize <= $h.getNum(self.minFileSize)) {
  2914. msg = self.msgSizeTooSmall.setTokens({
  2915. 'name': caption,
  2916. 'size': fSizeKB,
  2917. 'minSize': self.minFileSize
  2918. });
  2919. throwError(msg, file, previewId, i);
  2920. return;
  2921. }
  2922. if (!$h.isEmpty(fileTypes) && $h.isArray(fileTypes)) {
  2923. for (j = 0; j < fileTypes.length; j += 1) {
  2924. typ = fileTypes[j];
  2925. func = settings[typ];
  2926. fileCount += !func || (typeof func !== 'function') ? 0 : (func(file.type, file.name) ? 1 : 0);
  2927. }
  2928. if (fileCount === 0) {
  2929. msg = self.msgInvalidFileType.setTokens({'name': caption, 'types': strTypes});
  2930. throwError(msg, file, previewId, i);
  2931. return;
  2932. }
  2933. }
  2934. if (fileCount === 0 && !$h.isEmpty(fileExt) && $h.isArray(fileExt) && !$h.isEmpty(fileExtExpr)) {
  2935. chk = $h.compare(caption, fileExtExpr);
  2936. fileCount += $h.isEmpty(chk) ? 0 : chk.length;
  2937. if (fileCount === 0) {
  2938. msg = self.msgInvalidFileExtension.setTokens({'name': caption, 'extensions': strExt});
  2939. throwError(msg, file, previewId, i);
  2940. return;
  2941. }
  2942. }
  2943. if (!self.showPreview) {
  2944. if (self.isAjaxUpload) {
  2945. self.addToStack(file);
  2946. }
  2947. setTimeout(function () {
  2948. readFile(i + 1);
  2949. self._updateFileDetails(numFiles);
  2950. }, 100);
  2951. self._raise('fileloaded', [file, previewId, i, reader]);
  2952. return;
  2953. }
  2954. if (!canPreview && fileSize > maxPreviewSize) {
  2955. self.addToStack(file);
  2956. $container.addClass('file-thumb-loading');
  2957. self._previewDefault(file, previewId);
  2958. self._initFileActions();
  2959. self._updateFileDetails(numFiles);
  2960. readFile(i + 1);
  2961. return;
  2962. }
  2963. if ($preview.length && FileReader !== undefined) {
  2964. isText = fnText(file.type, caption);
  2965. isHtml = fnHtml(file.type, caption);
  2966. isImage = fnImage(file.type, caption);
  2967. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  2968. $container.addClass('file-thumb-loading');
  2969. reader.onerror = function (evt) {
  2970. self._errorHandler(evt, caption);
  2971. };
  2972. reader.onload = function (theFile) {
  2973. var hex, fileInfo, uint, byte, bytes = [], contents, mime, readTextImage = function (textFlag) {
  2974. var newReader = new FileReader();
  2975. newReader.onerror = function (theFileNew) {
  2976. self._errorHandler(theFileNew, caption);
  2977. };
  2978. newReader.onload = function (theFileNew) {
  2979. self._previewFile(i, file, theFileNew, previewId, previewData, fileInfo);
  2980. self._initFileActions();
  2981. processFileLoaded();
  2982. };
  2983. if (textFlag) {
  2984. newReader.readAsText(file, self.textEncoding);
  2985. } else {
  2986. newReader.readAsDataURL(file);
  2987. }
  2988. };
  2989. fileInfo = {'name': caption, 'type': file.type};
  2990. $.each(settings, function (key, func) {
  2991. if (key !== 'object' && key !== 'other' && func(file.type, caption)) {
  2992. knownTypes++;
  2993. }
  2994. });
  2995. if (knownTypes === 0) {// auto detect mime types from content if no known file types detected
  2996. uint = new Uint8Array(theFile.target.result);
  2997. for (j = 0; j < uint.length; j++) {
  2998. byte = uint[j].toString(16);
  2999. bytes.push(byte);
  3000. }
  3001. hex = bytes.join('').toLowerCase().substring(0, 8);
  3002. mime = $h.getMimeType(hex, '', '');
  3003. if ($h.isEmpty(mime)) { // look for ascii text content
  3004. contents = $h.arrayBuffer2String(reader.result);
  3005. mime = $h.isSvg(contents) ? 'image/svg+xml' : $h.getMimeType(hex, contents, file.type);
  3006. }
  3007. fileInfo = {'name': caption, 'type': mime};
  3008. isText = fnText(mime, '');
  3009. isHtml = fnHtml(mime, '');
  3010. isImage = fnImage(mime, '');
  3011. txtFlag = isText || isHtml;
  3012. if (txtFlag || isImage) {
  3013. readTextImage(txtFlag);
  3014. return;
  3015. }
  3016. }
  3017. self._previewFile(i, file, theFile, previewId, previewData, fileInfo);
  3018. self._initFileActions();
  3019. processFileLoaded();
  3020. };
  3021. reader.onprogress = function (data) {
  3022. if (data.lengthComputable) {
  3023. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  3024. msg = msgProgress.setTokens({
  3025. 'index': i + 1,
  3026. 'files': numFiles,
  3027. 'percent': progress,
  3028. 'name': caption
  3029. });
  3030. setTimeout(function () {
  3031. $status.html(msg);
  3032. }, 100);
  3033. }
  3034. };
  3035. if (isText || isHtml) {
  3036. reader.readAsText(file, self.textEncoding);
  3037. } else {
  3038. if (isImage) {
  3039. reader.readAsDataURL(file);
  3040. } else {
  3041. reader.readAsArrayBuffer(file);
  3042. }
  3043. }
  3044. } else {
  3045. self._previewDefault(file, previewId);
  3046. setTimeout(function () {
  3047. readFile(i + 1);
  3048. self._updateFileDetails(numFiles);
  3049. }, 100);
  3050. self._raise('fileloaded', [file, previewId, i, reader]);
  3051. }
  3052. self.addToStack(file);
  3053. };
  3054. readFile(0);
  3055. self._updateFileDetails(numFiles, false);
  3056. },
  3057. _updateFileDetails: function (numFiles) {
  3058. var self = this, $el = self.$element, fileStack = self.getFileStack(),
  3059. name = ($h.isIE(9) && $h.findFileName($el.val())) ||
  3060. ($el[0].files[0] && $el[0].files[0].name) || (fileStack.length && fileStack[0].name) || '',
  3061. label = self.slug(name), n = self.isAjaxUpload ? fileStack.length : numFiles,
  3062. nFiles = self.previewCache.count() + n, log = n === 1 ? label : self._getMsgSelected(nFiles);
  3063. if (self.isError) {
  3064. self.$previewContainer.removeClass('file-thumb-loading');
  3065. self.$previewStatus.html('');
  3066. self.$captionContainer.removeClass('icon-visible');
  3067. } else {
  3068. self._showFileIcon();
  3069. }
  3070. self._setCaption(log, self.isError);
  3071. self.$container.removeClass('file-input-new file-input-ajax-new');
  3072. if (arguments.length === 1) {
  3073. self._raise('fileselect', [numFiles, label]);
  3074. }
  3075. if (self.previewCache.count()) {
  3076. self._initPreviewActions();
  3077. }
  3078. },
  3079. _setThumbStatus: function ($thumb, status) {
  3080. var self = this;
  3081. if (!self.showPreview) {
  3082. return;
  3083. }
  3084. var icon = 'indicator' + status, msg = icon + 'Title',
  3085. css = 'file-preview-' + status.toLowerCase(),
  3086. $indicator = $thumb.find('.file-upload-indicator'),
  3087. config = self.fileActionSettings;
  3088. $thumb.removeClass('file-preview-success file-preview-error file-preview-loading');
  3089. if (status === 'Success') {
  3090. $thumb.find('.file-drag-handle').remove();
  3091. }
  3092. $indicator.html(config[icon]);
  3093. $indicator.attr('title', config[msg]);
  3094. $thumb.addClass(css);
  3095. if (status === 'Error' && !self.retryErrorUploads) {
  3096. $thumb.find('.kv-file-upload').attr('disabled', true);
  3097. }
  3098. },
  3099. _setProgressCancelled: function () {
  3100. var self = this;
  3101. self._setProgress(101, self.$progress, self.msgCancelled);
  3102. },
  3103. _setProgress: function (p, $el, error) {
  3104. var self = this, pct = Math.min(p, 100), out, pctLimit = self.progressUploadThreshold,
  3105. t = p <= 100 ? self.progressTemplate : self.progressCompleteTemplate,
  3106. template = pct < 100 ? self.progressTemplate : (error ? self.progressErrorTemplate : t);
  3107. $el = $el || self.$progress;
  3108. if (!$h.isEmpty(template)) {
  3109. if (pctLimit && pct > pctLimit && p <= 100) {
  3110. out = template.setTokens({'percent': pctLimit, 'status': self.msgUploadThreshold});
  3111. } else {
  3112. out = template.setTokens({'percent': pct, 'status': (p > 100 ? self.msgUploadEnd : pct + '%')});
  3113. }
  3114. $el.html(out);
  3115. if (error) {
  3116. $el.find('[role="progressbar"]').html(error);
  3117. }
  3118. }
  3119. },
  3120. _setFileDropZoneTitle: function () {
  3121. var self = this, $zone = self.$container.find('.file-drop-zone'), title = self.dropZoneTitle, strFiles;
  3122. if (self.isClickable) {
  3123. strFiles = $h.isEmpty(self.$element.attr('multiple')) ? self.fileSingle : self.filePlural;
  3124. title += self.dropZoneClickTitle.replace('{files}', strFiles);
  3125. }
  3126. $zone.find('.' + self.dropZoneTitleClass).remove();
  3127. if (!self.isAjaxUpload || !self.showPreview || $zone.length === 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled) {
  3128. return;
  3129. }
  3130. if ($zone.find($h.FRAMES).length === 0 && $h.isEmpty(self.defaultPreviewContent)) {
  3131. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + title + '</div>');
  3132. }
  3133. self.$container.removeClass('file-input-new');
  3134. $h.addCss(self.$container, 'file-input-ajax-new');
  3135. },
  3136. _setAsyncUploadStatus: function (previewId, pct, total) {
  3137. var self = this, sum = 0;
  3138. self._setProgress(pct, $('#' + previewId).find('.file-thumb-progress'));
  3139. self.uploadStatus[previewId] = pct;
  3140. $.each(self.uploadStatus, function (key, value) {
  3141. sum += value;
  3142. });
  3143. self._setProgress(Math.floor(sum / total));
  3144. },
  3145. _validateMinCount: function () {
  3146. var self = this, len = self.isAjaxUpload ? self.getFileStack().length : self.$element.get(0).files.length;
  3147. if (self.validateInitialCount && self.minFileCount > 0 && self._getFileCount(len - 1) < self.minFileCount) {
  3148. self._noFilesError({});
  3149. return false;
  3150. }
  3151. return true;
  3152. },
  3153. _getFileCount: function (fileCount) {
  3154. var self = this, addCount = 0;
  3155. if (self.validateInitialCount && !self.overwriteInitial) {
  3156. addCount = self.previewCache.count();
  3157. fileCount += addCount;
  3158. }
  3159. return fileCount;
  3160. },
  3161. _getFileId: function (file) {
  3162. var self = this, custom = self.generateFileId, relativePath;
  3163. if (typeof custom === 'function') {
  3164. return custom(file, event);
  3165. }
  3166. if (!file) {
  3167. return null;
  3168. }
  3169. /** @namespace file.webkitRelativePath */
  3170. relativePath = String(file.webkitRelativePath || file.fileName || file.name || null);
  3171. if (!relativePath) {
  3172. return null;
  3173. }
  3174. return (file.size + '-' + relativePath.replace(/[^0-9a-zA-Z_-]/img, ''));
  3175. },
  3176. _getFileName: function (file) {
  3177. return file && file.name ? this.slug(file.name) : undefined;
  3178. },
  3179. _getFileIds: function (skipNull) {
  3180. var self = this;
  3181. return self.fileids.filter(function (n) {
  3182. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  3183. });
  3184. },
  3185. _getFileNames: function (skipNull) {
  3186. var self = this;
  3187. return self.filenames.filter(function (n) {
  3188. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  3189. });
  3190. },
  3191. _setPreviewError: function ($thumb, i, val, repeat) {
  3192. var self = this;
  3193. if (i !== undefined) {
  3194. self.updateStack(i, val);
  3195. }
  3196. if (!self.showPreview) {
  3197. return;
  3198. }
  3199. if (self.removeFromPreviewOnError && !repeat) {
  3200. $thumb.remove();
  3201. return;
  3202. } else {
  3203. self._setThumbStatus($thumb, 'Error');
  3204. }
  3205. self._refreshUploadButton($thumb, repeat);
  3206. },
  3207. _refreshUploadButton: function ($thumb, repeat) {
  3208. var self = this, $btn = $thumb.find('.kv-file-upload'), cfg = self.fileActionSettings,
  3209. icon = cfg.uploadIcon, title = cfg.uploadTitle;
  3210. if (!$btn.length) {
  3211. return;
  3212. }
  3213. if (repeat) {
  3214. icon = cfg.uploadRetryIcon;
  3215. title = cfg.uploadRetryTitle;
  3216. }
  3217. $btn.attr('title', title).html(icon);
  3218. },
  3219. _checkDimensions: function (i, chk, $img, $thumb, fname, type, params) {
  3220. var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max', limit = self[tag + 'Image' + type],
  3221. $imgEl, isValid;
  3222. if ($h.isEmpty(limit) || !$img.length) {
  3223. return;
  3224. }
  3225. $imgEl = $img[0];
  3226. dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height;
  3227. isValid = chk === 'Small' ? dim >= limit : dim <= limit;
  3228. if (isValid) {
  3229. return;
  3230. }
  3231. msg = self['msgImage' + type + chk].setTokens({'name': fname, 'size': limit});
  3232. self._showUploadError(msg, params);
  3233. self._setPreviewError($thumb, i, null);
  3234. },
  3235. _validateImage: function (previewId, fname, ftype, fsize, iData) {
  3236. var self = this, $preview = self.$preview, params, w1, w2, $thumb = $preview.find("#" + previewId),
  3237. i = $thumb.attr('data-fileindex'), $img = $thumb.find('img'), exifObject;
  3238. fname = fname || 'Untitled';
  3239. $img.one('load', function () {
  3240. w1 = $thumb.width();
  3241. w2 = $preview.width();
  3242. if (w1 > w2) {
  3243. $img.css('width', '100%');
  3244. }
  3245. params = {ind: i, id: previewId};
  3246. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
  3247. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
  3248. if (!self.resizeImage) {
  3249. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
  3250. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
  3251. }
  3252. self._raise('fileimageloaded', [previewId]);
  3253. try {
  3254. exifObject = window.piexif ? window.piexif.load(iData) : null;
  3255. } catch (err) {
  3256. exifObject = null;
  3257. }
  3258. self.loadedImages.push({
  3259. ind: i,
  3260. img: $img,
  3261. thumb: $thumb,
  3262. pid: previewId,
  3263. typ: ftype,
  3264. siz: fsize,
  3265. validated: false,
  3266. imgData: iData,
  3267. exifObj: exifObject
  3268. });
  3269. $thumb.data('exif', exifObject);
  3270. self._validateAllImages();
  3271. }).one('error', function () {
  3272. self._raise('fileimageloaderror', [previewId]);
  3273. }).each(function () {
  3274. if (this.complete) {
  3275. $(this).trigger('load');
  3276. } else {
  3277. if (this.error) {
  3278. $(this).trigger('error');
  3279. }
  3280. }
  3281. });
  3282. },
  3283. _validateAllImages: function () {
  3284. var self = this, i, counter = {val: 0}, numImgs = self.loadedImages.length, config,
  3285. fsize, minSize = self.resizeIfSizeMoreThan;
  3286. if (numImgs !== self.totalImagesCount) {
  3287. return;
  3288. }
  3289. self._raise('fileimagesloaded');
  3290. if (!self.resizeImage) {
  3291. return;
  3292. }
  3293. for (i = 0; i < self.loadedImages.length; i++) {
  3294. config = self.loadedImages[i];
  3295. if (config.validated) {
  3296. continue;
  3297. }
  3298. fsize = config.siz;
  3299. if (fsize && fsize > minSize * 1000) {
  3300. self._getResizedImage(config, counter, numImgs);
  3301. }
  3302. self.loadedImages[i].validated = true;
  3303. }
  3304. },
  3305. _getResizedImage: function (config, counter, numImgs) {
  3306. var self = this, img = $(config.img)[0], width = img.naturalWidth, height = img.naturalHeight, blob,
  3307. ratio = 1, maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height,
  3308. isValidImage = !!(width && height), chkWidth, chkHeight, canvas = self.imageCanvas, dataURI,
  3309. context = self.imageCanvasContext, type = config.typ, pid = config.pid, ind = config.ind,
  3310. $thumb = config.thumb, throwError, msg, exifObj = config.exifObj, exifStr;
  3311. throwError = function (msg, params, ev) {
  3312. if (self.isAjaxUpload) {
  3313. self._showUploadError(msg, params, ev);
  3314. } else {
  3315. self._showError(msg, params, ev);
  3316. }
  3317. self._setPreviewError($thumb, ind);
  3318. };
  3319. if (!self.filestack[ind] || !isValidImage || (width <= maxWidth && height <= maxHeight)) {
  3320. if (isValidImage && self.filestack[ind]) {
  3321. self._raise('fileimageresized', [pid, ind]);
  3322. }
  3323. counter.val++;
  3324. if (counter.val === numImgs) {
  3325. self._raise('fileimagesresized');
  3326. }
  3327. if (!isValidImage) {
  3328. throwError(self.msgImageResizeError, {id: pid, 'index': ind}, 'fileimageresizeerror');
  3329. return;
  3330. }
  3331. }
  3332. type = type || self.resizeDefaultImageType;
  3333. chkWidth = width > maxWidth;
  3334. chkHeight = height > maxHeight;
  3335. if (self.resizePreference === 'width') {
  3336. ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1);
  3337. } else {
  3338. ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1);
  3339. }
  3340. self._resetCanvas();
  3341. width *= ratio;
  3342. height *= ratio;
  3343. canvas.width = width;
  3344. canvas.height = height;
  3345. try {
  3346. context.drawImage(img, 0, 0, width, height);
  3347. dataURI = canvas.toDataURL(type, self.resizeQuality);
  3348. if (exifObj) {
  3349. exifStr = window.piexif.dump(exifObj);
  3350. dataURI = window.piexif.insert(exifStr, dataURI);
  3351. }
  3352. blob = $h.dataURI2Blob(dataURI);
  3353. self.filestack[ind] = blob;
  3354. self._raise('fileimageresized', [pid, ind]);
  3355. counter.val++;
  3356. if (counter.val === numImgs) {
  3357. self._raise('fileimagesresized', [undefined, undefined]);
  3358. }
  3359. if (!(blob instanceof Blob)) {
  3360. throwError(self.msgImageResizeError, {id: pid, 'index': ind}, 'fileimageresizeerror');
  3361. }
  3362. }
  3363. catch (err) {
  3364. counter.val++;
  3365. if (counter.val === numImgs) {
  3366. self._raise('fileimagesresized', [undefined, undefined]);
  3367. }
  3368. msg = self.msgImageResizeException.replace('{errors}', err.message);
  3369. throwError(msg, {id: pid, 'index': ind}, 'fileimageresizeexception');
  3370. }
  3371. },
  3372. _initBrowse: function ($container) {
  3373. var self = this;
  3374. if (self.showBrowse) {
  3375. self.$btnFile = $container.find('.btn-file');
  3376. self.$btnFile.append(self.$element);
  3377. } else {
  3378. self.$element.hide();
  3379. }
  3380. },
  3381. _initCaption: function () {
  3382. var self = this, cap = self.initialCaption || '';
  3383. if (self.overwriteInitial || $h.isEmpty(cap)) {
  3384. self.$caption.val('');
  3385. return false;
  3386. }
  3387. self._setCaption(cap);
  3388. return true;
  3389. },
  3390. _setCaption: function (content, isError) {
  3391. var self = this, title, out, icon, n, cap, stack = self.getFileStack();
  3392. if (!self.$caption.length) {
  3393. return;
  3394. }
  3395. self.$captionContainer.removeClass('icon-visible');
  3396. if (isError) {
  3397. title = $('<div>' + self.msgValidationError + '</div>').text();
  3398. n = stack.length;
  3399. if (n) {
  3400. cap = n === 1 && stack[0] ? self._getFileNames()[0] : self._getMsgSelected(n);
  3401. } else {
  3402. cap = self._getMsgSelected(self.msgNo);
  3403. }
  3404. out = $h.isEmpty(content) ? cap : content;
  3405. icon = '<span class="' + self.msgValidationErrorClass + '">' + self.msgValidationErrorIcon + '</span>';
  3406. } else {
  3407. if ($h.isEmpty(content)) {
  3408. return;
  3409. }
  3410. title = $('<div>' + content + '</div>').text();
  3411. out = title;
  3412. icon = self._getLayoutTemplate('fileIcon');
  3413. }
  3414. self.$captionContainer.addClass('icon-visible');
  3415. self.$caption.attr('title', title).val(out);
  3416. self.$captionIcon.html(icon);
  3417. },
  3418. _createContainer: function () {
  3419. var self = this, attribs = {"class": 'file-input file-input-new' + (self.rtl ? ' kv-rtl' : '')},
  3420. $container = $(document.createElement("div")).attr(attribs).html(self._renderMain());
  3421. self.$element.before($container);
  3422. self._initBrowse($container);
  3423. if (self.theme) {
  3424. $container.addClass('theme-' + self.theme);
  3425. }
  3426. return $container;
  3427. },
  3428. _refreshContainer: function () {
  3429. var self = this, $container = self.$container;
  3430. $container.before(self.$element);
  3431. $container.html(self._renderMain());
  3432. self._initBrowse($container);
  3433. self._validateDisabled();
  3434. },
  3435. _validateDisabled: function () {
  3436. var self = this;
  3437. self.$caption.attr({readonly: self.isDisabled});
  3438. },
  3439. _renderMain: function () {
  3440. var self = this,
  3441. dropCss = (self.isAjaxUpload && self.dropZoneEnabled) ? ' file-drop-zone' : 'file-drop-disabled',
  3442. close = !self.showClose ? '' : self._getLayoutTemplate('close'),
  3443. preview = !self.showPreview ? '' : self._getLayoutTemplate('preview')
  3444. .setTokens({'class': self.previewClass, 'dropClass': dropCss}),
  3445. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  3446. caption = self.captionTemplate.setTokens({'class': css + ' kv-fileinput-caption'});
  3447. return self.mainTemplate.setTokens({
  3448. 'class': self.mainClass + (!self.showBrowse && self.showCaption ? ' no-browse' : ''),
  3449. 'preview': preview,
  3450. 'close': close,
  3451. 'caption': caption,
  3452. 'upload': self._renderButton('upload'),
  3453. 'remove': self._renderButton('remove'),
  3454. 'cancel': self._renderButton('cancel'),
  3455. 'browse': self._renderButton('browse')
  3456. });
  3457. },
  3458. _renderButton: function (type) {
  3459. var self = this, tmplt = self._getLayoutTemplate('btnDefault'), css = self[type + 'Class'],
  3460. title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'],
  3461. status = self.isDisabled ? ' disabled' : '', btnType = 'button';
  3462. switch (type) {
  3463. case 'remove':
  3464. if (!self.showRemove) {
  3465. return '';
  3466. }
  3467. break;
  3468. case 'cancel':
  3469. if (!self.showCancel) {
  3470. return '';
  3471. }
  3472. css += ' kv-hidden';
  3473. break;
  3474. case 'upload':
  3475. if (!self.showUpload) {
  3476. return '';
  3477. }
  3478. if (self.isAjaxUpload && !self.isDisabled) {
  3479. tmplt = self._getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl);
  3480. } else {
  3481. btnType = 'submit';
  3482. }
  3483. break;
  3484. case 'browse':
  3485. if (!self.showBrowse) {
  3486. return '';
  3487. }
  3488. tmplt = self._getLayoutTemplate('btnBrowse');
  3489. break;
  3490. default:
  3491. return '';
  3492. }
  3493. css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button';
  3494. if (!$h.isEmpty(label)) {
  3495. label = ' <span class="' + self.buttonLabelClass + '">' + label + '</span>';
  3496. }
  3497. return tmplt.setTokens({
  3498. 'type': btnType, 'css': css, 'title': title, 'status': status, 'icon': icon, 'label': label
  3499. });
  3500. },
  3501. _renderThumbProgress: function () {
  3502. var self = this;
  3503. return '<div class="file-thumb-progress kv-hidden">' +
  3504. self.progressTemplate.setTokens({'percent': '0', 'status': self.msgUploadBegin}) +
  3505. '</div>';
  3506. },
  3507. _renderFileFooter: function (caption, size, width, isError) {
  3508. var self = this, config = self.fileActionSettings, rem = config.showRemove, drg = config.showDrag,
  3509. upl = config.showUpload, zoom = config.showZoom, out,
  3510. template = self._getLayoutTemplate('footer'), tInd = self._getLayoutTemplate('indicator'),
  3511. ind = isError ? config.indicatorError : config.indicatorNew,
  3512. title = isError ? config.indicatorErrorTitle : config.indicatorNewTitle,
  3513. indicator = tInd.setTokens({'indicator': ind, 'indicatorTitle': title});
  3514. size = self._getSize(size);
  3515. if (self.isAjaxUpload) {
  3516. out = template.setTokens({
  3517. 'actions': self._renderFileActions(upl, false, rem, zoom, drg, false, false, false),
  3518. 'caption': caption,
  3519. 'size': size,
  3520. 'width': width,
  3521. 'progress': self._renderThumbProgress(),
  3522. 'indicator': indicator
  3523. });
  3524. } else {
  3525. out = template.setTokens({
  3526. 'actions': self._renderFileActions(false, false, false, zoom, drg, false, false, false),
  3527. 'caption': caption,
  3528. 'size': size,
  3529. 'width': width,
  3530. 'progress': '',
  3531. 'indicator': indicator
  3532. });
  3533. }
  3534. out = $h.replaceTags(out, self.previewThumbTags);
  3535. return out;
  3536. },
  3537. _renderFileActions: function (showUpl, showDwn, showDel, showZoom, showDrag, disabled, url, key, isInit, dUrl, dFile) {
  3538. if (!showUpl && !showDwn && !showDel && !showZoom && !showDrag) {
  3539. return '';
  3540. }
  3541. var self = this, vUrl = url === false ? '' : ' data-url="' + url + '"',
  3542. vKey = key === false ? '' : ' data-key="' + key + '"', btnDelete = '', btnUpload = '', btnDownload = '',
  3543. btnZoom = '', btnDrag = '', css, template = self._getLayoutTemplate('actions'),
  3544. config = self.fileActionSettings,
  3545. otherButtons = self.otherActionButtons.setTokens({'dataKey': vKey, 'key': key}),
  3546. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  3547. if (showDel) {
  3548. btnDelete = self._getLayoutTemplate('actionDelete').setTokens({
  3549. 'removeClass': removeClass,
  3550. 'removeIcon': config.removeIcon,
  3551. 'removeTitle': config.removeTitle,
  3552. 'dataUrl': vUrl,
  3553. 'dataKey': vKey,
  3554. 'key': key
  3555. });
  3556. }
  3557. if (showUpl) {
  3558. btnUpload = self._getLayoutTemplate('actionUpload').setTokens({
  3559. 'uploadClass': config.uploadClass,
  3560. 'uploadIcon': config.uploadIcon,
  3561. 'uploadTitle': config.uploadTitle
  3562. });
  3563. }
  3564. if (showDwn) {
  3565. btnDownload = self._getLayoutTemplate('actionDownload').setTokens({
  3566. 'downloadClass': config.downloadClass,
  3567. 'downloadIcon': config.downloadIcon,
  3568. 'downloadTitle': config.downloadTitle,
  3569. 'downloadUrl': dUrl || self.initialPreviewDownloadUrl
  3570. });
  3571. btnDownload = btnDownload.setTokens({'filename': dFile, 'key': key});
  3572. }
  3573. if (showZoom) {
  3574. btnZoom = self._getLayoutTemplate('actionZoom').setTokens({
  3575. 'zoomClass': config.zoomClass,
  3576. 'zoomIcon': config.zoomIcon,
  3577. 'zoomTitle': config.zoomTitle
  3578. });
  3579. }
  3580. if (showDrag && isInit) {
  3581. css = 'drag-handle-init ' + config.dragClass;
  3582. btnDrag = self._getLayoutTemplate('actionDrag').setTokens({
  3583. 'dragClass': css,
  3584. 'dragTitle': config.dragTitle,
  3585. 'dragIcon': config.dragIcon
  3586. });
  3587. }
  3588. return template.setTokens({
  3589. 'delete': btnDelete,
  3590. 'upload': btnUpload,
  3591. 'download': btnDownload,
  3592. 'zoom': btnZoom,
  3593. 'drag': btnDrag,
  3594. 'other': otherButtons
  3595. });
  3596. },
  3597. _browse: function (e) {
  3598. var self = this;
  3599. self._raise('filebrowse');
  3600. if (e && e.isDefaultPrevented()) {
  3601. return;
  3602. }
  3603. if (self.isError && !self.isAjaxUpload) {
  3604. self.clear();
  3605. }
  3606. self.$captionContainer.focus();
  3607. },
  3608. _filterDuplicate: function (file, files, fileIds) {
  3609. var self = this, fileId = self._getFileId(file);
  3610. if (fileId && fileIds && fileIds.indexOf(fileId) > -1) {
  3611. return;
  3612. }
  3613. if (!fileIds) {
  3614. fileIds = [];
  3615. }
  3616. files.push(file);
  3617. fileIds.push(fileId);
  3618. },
  3619. _change: function (e) {
  3620. var self = this, $el = self.$element;
  3621. if (!self.isAjaxUpload && $h.isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix
  3622. self.fileInputCleared = false;
  3623. return;
  3624. }
  3625. self.fileInputCleared = false;
  3626. var tfiles = [], msg, total, isDragDrop = arguments.length > 1, isAjaxUpload = self.isAjaxUpload, n, len,
  3627. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files, ctr = self.filestack.length,
  3628. isSingleUpload = $h.isEmpty($el.attr('multiple')), flagSingle = (isSingleUpload && ctr > 0),
  3629. folders = 0, fileIds = self._getFileIds(), throwError = function (mesg, file, previewId, index) {
  3630. var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}),
  3631. p2 = {id: previewId, index: index, file: file, files: files};
  3632. return self.isAjaxUpload ? self._showUploadError(mesg, p1) : self._showError(mesg, p2);
  3633. };
  3634. self.reader = null;
  3635. self._resetUpload();
  3636. self._hideFileIcon();
  3637. if (self.isAjaxUpload) {
  3638. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  3639. }
  3640. if (isDragDrop) {
  3641. $.each(files, function (i, f) {
  3642. if (f && !f.type && f.size !== undefined && f.size % 4096 === 0) {
  3643. folders++;
  3644. } else {
  3645. self._filterDuplicate(f, tfiles, fileIds);
  3646. }
  3647. });
  3648. } else {
  3649. if (e.target && e.target.files === undefined) {
  3650. files = e.target.value ? [{name: e.target.value.replace(/^.+\\/, '')}] : [];
  3651. } else {
  3652. files = e.target.files || {};
  3653. }
  3654. if (isAjaxUpload) {
  3655. $.each(files, function (i, f) {
  3656. self._filterDuplicate(f, tfiles, fileIds);
  3657. });
  3658. } else {
  3659. tfiles = files;
  3660. }
  3661. }
  3662. if ($h.isEmpty(tfiles) || tfiles.length === 0) {
  3663. if (!isAjaxUpload) {
  3664. self.clear();
  3665. }
  3666. self._showFolderError(folders);
  3667. self._raise('fileselectnone');
  3668. return;
  3669. }
  3670. self._resetErrors();
  3671. len = tfiles.length;
  3672. total = self._getFileCount(self.isAjaxUpload ? (self.getFileStack().length + len) : len);
  3673. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  3674. if (!self.autoReplace || len > self.maxFileCount) {
  3675. n = (self.autoReplace && len > self.maxFileCount) ? len : total;
  3676. msg = self.msgFilesTooMany.replace('{m}', self.maxFileCount).replace('{n}', n);
  3677. self.isError = throwError(msg, null, null, null);
  3678. self.$captionContainer.removeClass('icon-visible');
  3679. self._setCaption('', true);
  3680. self.$container.removeClass('file-input-new file-input-ajax-new');
  3681. return;
  3682. }
  3683. if (total > self.maxFileCount) {
  3684. self._resetPreviewThumbs(isAjaxUpload);
  3685. }
  3686. } else {
  3687. if (!isAjaxUpload || flagSingle) {
  3688. self._resetPreviewThumbs(false);
  3689. if (flagSingle) {
  3690. self.clearStack();
  3691. }
  3692. } else {
  3693. if (isAjaxUpload && ctr === 0 && (!self.previewCache.count() || self.overwriteInitial)) {
  3694. self._resetPreviewThumbs(true);
  3695. }
  3696. }
  3697. }
  3698. if (self.isPreviewable) {
  3699. self._readFiles(tfiles);
  3700. } else {
  3701. self._updateFileDetails(1);
  3702. }
  3703. self._showFolderError(folders);
  3704. },
  3705. _abort: function (params) {
  3706. var self = this, data;
  3707. if (self.ajaxAborted && typeof self.ajaxAborted === "object" && self.ajaxAborted.message !== undefined) {
  3708. data = $.extend(true, {}, self._getOutData(), params);
  3709. data.abortData = self.ajaxAborted.data || {};
  3710. data.abortMessage = self.ajaxAborted.message;
  3711. self._setProgress(101, self.$progress, self.msgCancelled);
  3712. self._showUploadError(self.ajaxAborted.message, data, 'filecustomerror');
  3713. self.cancel();
  3714. return true;
  3715. }
  3716. return false;
  3717. },
  3718. _resetFileStack: function () {
  3719. var self = this, i = 0, newstack = [], newnames = [], newids = [];
  3720. self._getThumbs().each(function () {
  3721. var $thumb = $(this), ind = $thumb.attr('data-fileindex'), file = self.filestack[ind],
  3722. pid = $thumb.attr('id'), newId;
  3723. if (ind === '-1' || ind === -1) {
  3724. return;
  3725. }
  3726. if (file !== undefined) {
  3727. newstack[i] = file;
  3728. newnames[i] = self._getFileName(file);
  3729. newids[i] = self._getFileId(file);
  3730. $thumb.attr({'id': self.previewInitId + '-' + i, 'data-fileindex': i});
  3731. i++;
  3732. } else {
  3733. newId = 'uploaded-' + $h.uniqId();
  3734. $thumb.attr({'id': newId, 'data-fileindex': '-1'});
  3735. self.$preview.find('#zoom-' + pid).attr('id', 'zoom-' + newId);
  3736. }
  3737. });
  3738. self.filestack = newstack;
  3739. self.filenames = newnames;
  3740. self.fileids = newids;
  3741. },
  3742. _isFileSelectionValid: function (cnt) {
  3743. var self = this;
  3744. cnt = cnt || 0;
  3745. if (self.required && !self.getFilesCount()) {
  3746. self.$errorContainer.html('');
  3747. self._showUploadError(self.msgFileRequired);
  3748. return false;
  3749. }
  3750. if (self.minFileCount > 0 && self._getFileCount(cnt) < self.minFileCount) {
  3751. self._noFilesError({});
  3752. return false;
  3753. }
  3754. return true;
  3755. },
  3756. clearStack: function () {
  3757. var self = this;
  3758. self.filestack = [];
  3759. self.filenames = [];
  3760. self.fileids = [];
  3761. return self.$element;
  3762. },
  3763. updateStack: function (i, file) {
  3764. var self = this;
  3765. self.filestack[i] = file;
  3766. self.filenames[i] = self._getFileName(file);
  3767. self.fileids[i] = file && self._getFileId(file) || null;
  3768. return self.$element;
  3769. },
  3770. addToStack: function (file) {
  3771. var self = this;
  3772. self.filestack.push(file);
  3773. self.filenames.push(self._getFileName(file));
  3774. self.fileids.push(self._getFileId(file));
  3775. return self.$element;
  3776. },
  3777. getFileStack: function (skipNull) {
  3778. var self = this;
  3779. return self.filestack.filter(function (n) {
  3780. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  3781. });
  3782. },
  3783. getFilesCount: function () {
  3784. var self = this, len = self.isAjaxUpload ? self.getFileStack().length : self.$element.get(0).files.length;
  3785. return self._getFileCount(len);
  3786. },
  3787. lock: function () {
  3788. var self = this;
  3789. self._resetErrors();
  3790. self.disable();
  3791. if (self.showRemove) {
  3792. self.$container.find('.fileinput-remove').hide();
  3793. }
  3794. if (self.showCancel) {
  3795. self.$container.find('.fileinput-cancel').show();
  3796. }
  3797. self._raise('filelock', [self.filestack, self._getExtraData()]);
  3798. return self.$element;
  3799. },
  3800. unlock: function (reset) {
  3801. var self = this;
  3802. if (reset === undefined) {
  3803. reset = true;
  3804. }
  3805. self.enable();
  3806. if (self.showCancel) {
  3807. self.$container.find('.fileinput-cancel').hide();
  3808. }
  3809. if (self.showRemove) {
  3810. self.$container.find('.fileinput-remove').show();
  3811. }
  3812. if (reset) {
  3813. self._resetFileStack();
  3814. }
  3815. self._raise('fileunlock', [self.filestack, self._getExtraData()]);
  3816. return self.$element;
  3817. },
  3818. cancel: function () {
  3819. var self = this, xhr = self.ajaxRequests, len = xhr.length, i;
  3820. if (len > 0) {
  3821. for (i = 0; i < len; i += 1) {
  3822. self.cancelling = true;
  3823. xhr[i].abort();
  3824. }
  3825. }
  3826. self._setProgressCancelled();
  3827. self._getThumbs().each(function () {
  3828. var $thumb = $(this), ind = $thumb.attr('data-fileindex');
  3829. $thumb.removeClass('file-uploading');
  3830. if (self.filestack[ind] !== undefined) {
  3831. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  3832. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  3833. }
  3834. self.unlock();
  3835. });
  3836. return self.$element;
  3837. },
  3838. clear: function () {
  3839. var self = this, cap;
  3840. if (!self._raise('fileclear')) {
  3841. return;
  3842. }
  3843. self.$btnUpload.removeAttr('disabled');
  3844. self._getThumbs().find('video,audio,img').each(function () {
  3845. $h.cleanMemory($(this));
  3846. });
  3847. self._resetUpload();
  3848. self.clearStack();
  3849. self._clearFileInput();
  3850. self._resetErrors(true);
  3851. if (self._hasInitialPreview()) {
  3852. self._showFileIcon();
  3853. self._resetPreview();
  3854. self._initPreviewActions();
  3855. self.$container.removeClass('file-input-new');
  3856. } else {
  3857. self._getThumbs().each(function () {
  3858. self._clearObjects($(this));
  3859. });
  3860. if (self.isAjaxUpload) {
  3861. self.previewCache.data = {};
  3862. }
  3863. self.$preview.html('');
  3864. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  3865. self.$caption.attr('title', '').val(cap);
  3866. $h.addCss(self.$container, 'file-input-new');
  3867. self._validateDefaultPreview();
  3868. }
  3869. if (self.$container.find($h.FRAMES).length === 0) {
  3870. if (!self._initCaption()) {
  3871. self.$captionContainer.removeClass('icon-visible');
  3872. }
  3873. }
  3874. self._hideFileIcon();
  3875. self._raise('filecleared');
  3876. self.$captionContainer.focus();
  3877. self._setFileDropZoneTitle();
  3878. return self.$element;
  3879. },
  3880. reset: function () {
  3881. var self = this;
  3882. if (!self._raise('filereset')) {
  3883. return;
  3884. }
  3885. self._resetPreview();
  3886. self.$container.find('.fileinput-filename').text('');
  3887. $h.addCss(self.$container, 'file-input-new');
  3888. if (self.getFrames().length || self.isAjaxUpload && self.dropZoneEnabled) {
  3889. self.$container.removeClass('file-input-new');
  3890. }
  3891. self.clearStack();
  3892. self.formdata = {};
  3893. self._setFileDropZoneTitle();
  3894. return self.$element;
  3895. },
  3896. disable: function () {
  3897. var self = this;
  3898. self.isDisabled = true;
  3899. self._raise('filedisabled');
  3900. self.$element.attr('disabled', 'disabled');
  3901. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  3902. self.$container.find(".fileinput-remove, .fileinput-upload, .file-preview-frame button")
  3903. .attr("disabled", true);
  3904. $h.addCss(self.$container.find('.btn-file'), 'disabled');
  3905. self._initDragDrop();
  3906. return self.$element;
  3907. },
  3908. enable: function () {
  3909. var self = this;
  3910. self.isDisabled = false;
  3911. self._raise('fileenabled');
  3912. self.$element.removeAttr('disabled');
  3913. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  3914. self.$container.find(".fileinput-remove, .fileinput-upload, .file-preview-frame button")
  3915. .removeAttr("disabled");
  3916. self.$container.find('.btn-file').removeClass('disabled');
  3917. self._initDragDrop();
  3918. return self.$element;
  3919. },
  3920. upload: function () {
  3921. var self = this, totLen = self.getFileStack().length, i, outData, len,
  3922. hasExtraData = !$.isEmptyObject(self._getExtraData());
  3923. if (!self.isAjaxUpload || self.isDisabled || !self._isFileSelectionValid(totLen)) {
  3924. return;
  3925. }
  3926. self._resetUpload();
  3927. if (totLen === 0 && !hasExtraData) {
  3928. self._showUploadError(self.msgUploadEmpty);
  3929. return;
  3930. }
  3931. self.$progress.show();
  3932. self.uploadCount = 0;
  3933. self.uploadStatus = {};
  3934. self.uploadLog = [];
  3935. self.lock();
  3936. self._setProgress(2);
  3937. if (totLen === 0 && hasExtraData) {
  3938. self._uploadExtraOnly();
  3939. return;
  3940. }
  3941. len = self.filestack.length;
  3942. self.hasInitData = false;
  3943. if (self.uploadAsync) {
  3944. outData = self._getOutData();
  3945. self._raise('filebatchpreupload', [outData]);
  3946. self.fileBatchCompleted = false;
  3947. self.uploadCache = {content: [], config: [], tags: [], append: true};
  3948. self.uploadAsyncCount = self.getFileStack().length;
  3949. for (i = 0; i < len; i++) {
  3950. self.uploadCache.content[i] = null;
  3951. self.uploadCache.config[i] = null;
  3952. self.uploadCache.tags[i] = null;
  3953. }
  3954. self.$preview.find('.file-preview-initial').removeClass($h.SORT_CSS);
  3955. self._initSortable();
  3956. self.cacheInitialPreview = self.getPreview();
  3957. for (i = 0; i < len; i++) {
  3958. if (self.filestack[i]) {
  3959. self._uploadSingle(i, true);
  3960. }
  3961. }
  3962. return;
  3963. }
  3964. self._uploadBatch();
  3965. return self.$element;
  3966. },
  3967. destroy: function () {
  3968. var self = this, $form = self.$form, $cont = self.$container, $el = self.$element, ns = self.namespace;
  3969. $(document).off(ns);
  3970. $(window).off(ns);
  3971. if ($form && $form.length) {
  3972. $form.off(ns);
  3973. }
  3974. if (self.isAjaxUpload) {
  3975. self._clearFileInput();
  3976. }
  3977. self._cleanup();
  3978. self._initPreviewCache();
  3979. $el.insertBefore($cont).off(ns).removeData();
  3980. $cont.off().remove();
  3981. return $el;
  3982. },
  3983. refresh: function (options, triggerChange) {
  3984. var self = this, $el = self.$element;
  3985. if (typeof options !== 'object' || $h.isEmpty(options)) {
  3986. options = self.options;
  3987. } else {
  3988. options = $.extend(true, {}, self.options, options);
  3989. }
  3990. self._init(options, true);
  3991. self._listen();
  3992. if (triggerChange) {
  3993. $el.trigger('change' + self.namespace);
  3994. }
  3995. return $el;
  3996. },
  3997. zoom: function (frameId) {
  3998. var self = this, $frame = self._getFrame(frameId), $modal = self.$modal;
  3999. if (!$frame) {
  4000. return;
  4001. }
  4002. $h.initModal($modal);
  4003. $modal.html(self._getModalContent());
  4004. self._setZoomContent($frame);
  4005. $modal.modal('show');
  4006. self._initZoomButtons();
  4007. },
  4008. getExif: function (frameId) {
  4009. var self = this, $frame = self._getFrame(frameId);
  4010. return $frame && $frame.data('exif') || null;
  4011. },
  4012. getFrames: function (cssFilter) {
  4013. var self = this;
  4014. cssFilter = cssFilter || '';
  4015. return self.$preview.find($h.FRAMES + cssFilter);
  4016. },
  4017. getPreview: function () {
  4018. var self = this;
  4019. return {
  4020. content: self.initialPreview,
  4021. config: self.initialPreviewConfig,
  4022. tags: self.initialPreviewThumbTags
  4023. };
  4024. }
  4025. };
  4026. $.fn.fileinput = function (option) {
  4027. if (!$h.hasFileAPISupport() && !$h.isIE(9)) {
  4028. return;
  4029. }
  4030. var args = Array.apply(null, arguments), retvals = [];
  4031. args.shift();
  4032. this.each(function () {
  4033. var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option,
  4034. theme = options.theme || self.data('theme'), l = {}, t = {},
  4035. lang = options.language || self.data('language') || $.fn.fileinput.defaults.language || 'en', opt;
  4036. if (!data) {
  4037. if (theme) {
  4038. t = $.fn.fileinputThemes[theme] || {};
  4039. }
  4040. if (lang !== 'en' && !$h.isEmpty($.fn.fileinputLocales[lang])) {
  4041. l = $.fn.fileinputLocales[lang] || {};
  4042. }
  4043. opt = $.extend(true, {}, $.fn.fileinput.defaults, t, $.fn.fileinputLocales.en, l, options, self.data());
  4044. data = new FileInput(this, opt);
  4045. self.data('fileinput', data);
  4046. }
  4047. if (typeof option === 'string') {
  4048. retvals.push(data[option].apply(data, args));
  4049. }
  4050. });
  4051. switch (retvals.length) {
  4052. case 0:
  4053. return this;
  4054. case 1:
  4055. return retvals[0];
  4056. default:
  4057. return retvals;
  4058. }
  4059. };
  4060. $.fn.fileinput.defaults = {
  4061. language: 'en',
  4062. showCaption: true,
  4063. showBrowse: true,
  4064. showPreview: true,
  4065. showRemove: true,
  4066. showUpload: true,
  4067. showCancel: true,
  4068. showClose: true,
  4069. showUploadedThumbs: true,
  4070. browseOnZoneClick: false,
  4071. autoReplace: false,
  4072. autoOrientImage: true, // for JPEG images based on EXIF orientation tag
  4073. required: false,
  4074. rtl: false,
  4075. hideThumbnailContent: false,
  4076. generateFileId: null,
  4077. previewClass: '',
  4078. captionClass: '',
  4079. frameClass: 'krajee-default',
  4080. mainClass: 'file-caption-main',
  4081. mainTemplate: null,
  4082. purifyHtml: true,
  4083. fileSizeGetter: null,
  4084. initialCaption: '',
  4085. initialPreview: [],
  4086. initialPreviewDelimiter: '*$$*',
  4087. initialPreviewAsData: false,
  4088. initialPreviewFileType: 'image',
  4089. initialPreviewConfig: [],
  4090. initialPreviewThumbTags: [],
  4091. previewThumbTags: {},
  4092. initialPreviewShowDelete: true,
  4093. initialPreviewDownloadUrl: '',
  4094. removeFromPreviewOnError: false,
  4095. deleteUrl: '',
  4096. deleteExtraData: {},
  4097. overwriteInitial: true,
  4098. previewZoomButtonIcons: {
  4099. prev: '<i class="glyphicon glyphicon-triangle-left"></i>',
  4100. next: '<i class="glyphicon glyphicon-triangle-right"></i>',
  4101. toggleheader: '<i class="glyphicon glyphicon-resize-vertical"></i>',
  4102. fullscreen: '<i class="glyphicon glyphicon-fullscreen"></i>',
  4103. borderless: '<i class="glyphicon glyphicon-resize-full"></i>',
  4104. close: '<i class="glyphicon glyphicon-remove"></i>'
  4105. },
  4106. previewZoomButtonClasses: {
  4107. prev: 'btn btn-navigate',
  4108. next: 'btn btn-navigate',
  4109. toggleheader: 'btn btn-kv btn-default btn-outline-secondary',
  4110. fullscreen: 'btn btn-kv btn-default btn-outline-secondary',
  4111. borderless: 'btn btn-kv btn-default btn-outline-secondary',
  4112. close: 'btn btn-kv btn-default btn-outline-secondary'
  4113. },
  4114. preferIconicPreview: false,
  4115. preferIconicZoomPreview: false,
  4116. allowedPreviewTypes: undefined,
  4117. allowedPreviewMimeTypes: null,
  4118. allowedFileTypes: null,
  4119. allowedFileExtensions: null,
  4120. defaultPreviewContent: null,
  4121. customLayoutTags: {},
  4122. customPreviewTags: {},
  4123. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  4124. previewFileIconClass: 'file-other-icon',
  4125. previewFileIconSettings: {},
  4126. previewFileExtSettings: {},
  4127. buttonLabelClass: 'hidden-xs',
  4128. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i>&nbsp;',
  4129. browseClass: 'btn btn-primary',
  4130. removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
  4131. removeClass: 'btn btn-default btn-secondary',
  4132. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i>',
  4133. cancelClass: 'btn btn-default btn-secondary',
  4134. uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
  4135. uploadClass: 'btn btn-default btn-secondary',
  4136. uploadUrl: null,
  4137. uploadUrlThumb: null,
  4138. uploadAsync: true,
  4139. uploadExtraData: {},
  4140. zoomModalHeight: 480,
  4141. minImageWidth: null,
  4142. minImageHeight: null,
  4143. maxImageWidth: null,
  4144. maxImageHeight: null,
  4145. resizeImage: false,
  4146. resizePreference: 'width',
  4147. resizeQuality: 0.92,
  4148. resizeDefaultImageType: 'image/jpeg',
  4149. resizeIfSizeMoreThan: 0, // in KB
  4150. minFileSize: 0,
  4151. maxFileSize: 0,
  4152. maxFilePreviewSize: 25600, // 25 MB
  4153. minFileCount: 0,
  4154. maxFileCount: 0,
  4155. validateInitialCount: false,
  4156. msgValidationErrorClass: 'text-danger',
  4157. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  4158. msgErrorClass: 'file-error-message',
  4159. progressThumbClass: "progress-bar bg-success progress-bar-success progress-bar-striped active",
  4160. progressClass: "progress-bar bg-success progress-bar-success progress-bar-striped active",
  4161. progressCompleteClass: "progress-bar bg-success progress-bar-success",
  4162. progressErrorClass: "progress-bar bg-danger progress-bar-danger",
  4163. progressUploadThreshold: 99,
  4164. previewFileType: 'image',
  4165. elCaptionContainer: null,
  4166. elCaptionText: null,
  4167. elPreviewContainer: null,
  4168. elPreviewImage: null,
  4169. elPreviewStatus: null,
  4170. elErrorContainer: null,
  4171. errorCloseButton: '<button type="button" class="close kv-error-close">&times;</button>',
  4172. slugCallback: null,
  4173. dropZoneEnabled: true,
  4174. dropZoneTitleClass: 'file-drop-zone-title',
  4175. fileActionSettings: {},
  4176. otherActionButtons: '',
  4177. textEncoding: 'UTF-8',
  4178. ajaxSettings: {},
  4179. ajaxDeleteSettings: {},
  4180. showAjaxErrorDetails: true,
  4181. mergeAjaxCallbacks: false,
  4182. mergeAjaxDeleteCallbacks: false,
  4183. retryErrorUploads: true
  4184. };
  4185. $.fn.fileinputLocales.en = {
  4186. fileSingle: 'file',
  4187. filePlural: 'files',
  4188. browseLabel: 'Browse &hellip;',
  4189. removeLabel: 'Remove',
  4190. removeTitle: 'Clear selected files',
  4191. cancelLabel: 'Cancel',
  4192. cancelTitle: 'Abort ongoing upload',
  4193. uploadLabel: 'Upload',
  4194. uploadTitle: 'Upload selected files',
  4195. msgNo: 'No',
  4196. msgNoFilesSelected: 'No files selected',
  4197. msgCancelled: 'Cancelled',
  4198. msgPlaceholder: 'Select {files}...',
  4199. msgZoomModalHeading: 'Detailed Preview',
  4200. msgFileRequired: 'You must select a file to upload.',
  4201. msgSizeTooSmall: 'File "{name}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.',
  4202. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
  4203. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
  4204. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
  4205. msgFileNotFound: 'File "{name}" not found!',
  4206. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  4207. msgFileNotReadable: 'File "{name}" is not readable.',
  4208. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  4209. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  4210. msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".',
  4211. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  4212. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  4213. msgFileTypes: {
  4214. 'image': 'image',
  4215. 'html': 'HTML',
  4216. 'text': 'text',
  4217. 'video': 'video',
  4218. 'audio': 'audio',
  4219. 'flash': 'flash',
  4220. 'pdf': 'PDF',
  4221. 'object': 'object'
  4222. },
  4223. msgUploadAborted: 'The file upload was aborted',
  4224. msgUploadThreshold: 'Processing...',
  4225. msgUploadBegin: 'Initializing...',
  4226. msgUploadEnd: 'Done',
  4227. msgUploadEmpty: 'No valid data available for upload.',
  4228. msgUploadError: 'Error',
  4229. msgValidationError: 'Validation Error',
  4230. msgLoading: 'Loading file {index} of {files} &hellip;',
  4231. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  4232. msgSelected: '{n} {files} selected',
  4233. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  4234. msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
  4235. msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
  4236. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
  4237. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
  4238. msgImageResizeError: 'Could not get the image dimensions to resize.',
  4239. msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>',
  4240. msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!',
  4241. msgAjaxProgressError: '{operation} failed',
  4242. ajaxOperations: {
  4243. deleteThumb: 'file delete',
  4244. uploadThumb: 'file upload',
  4245. uploadBatch: 'batch file upload',
  4246. uploadExtra: 'form data upload'
  4247. },
  4248. dropZoneTitle: 'Drag & drop files here &hellip;',
  4249. dropZoneClickTitle: '<br>(or click to select {files})',
  4250. previewZoomButtonTitles: {
  4251. prev: 'View previous file',
  4252. next: 'View next file',
  4253. toggleheader: 'Toggle header',
  4254. fullscreen: 'Toggle full screen',
  4255. borderless: 'Toggle borderless mode',
  4256. close: 'Close detailed preview'
  4257. }
  4258. };
  4259. $.fn.fileinput.Constructor = FileInput;
  4260. /**
  4261. * Convert automatically file inputs with class 'file' into a bootstrap fileinput control.
  4262. */
  4263. $(document).ready(function () {
  4264. var $input = $('input.file[type=file]');
  4265. if ($input.length) {
  4266. $input.fileinput();
  4267. }
  4268. });
  4269. }));