fileinput.js 166 KB

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