fileinput.js 172 KB

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