fileinput.js 168 KB

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