fileinput.js 197 KB

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