fileinput.js 166 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582
  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 (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. },
  1497. _resetCanvas: function () {
  1498. var self = this;
  1499. if (self.canvas && self.imageCanvasContext) {
  1500. self.imageCanvasContext.clearRect(0, 0, self.canvas.width, self.canvas.height);
  1501. }
  1502. },
  1503. _hasInitialPreview: function () {
  1504. var self = this;
  1505. return !self.overwriteInitial && self.previewCache.count();
  1506. },
  1507. _resetPreview: function () {
  1508. var self = this, out, cap;
  1509. if (self.previewCache.count()) {
  1510. out = self.previewCache.out();
  1511. self.$preview.html(out.content);
  1512. self._setInitThumbAttr();
  1513. cap = self.initialCaption ? self.initialCaption : out.caption;
  1514. self._setCaption(cap);
  1515. } else {
  1516. self._clearPreview();
  1517. self._initCaption();
  1518. }
  1519. if (self.showPreview) {
  1520. self._initZoom();
  1521. self._initSortable();
  1522. }
  1523. },
  1524. _clearDefaultPreview: function () {
  1525. var self = this;
  1526. self.$preview.find('.file-default-preview').remove();
  1527. },
  1528. _validateDefaultPreview: function () {
  1529. var self = this;
  1530. if (!self.showPreview || $h.isEmpty(self.defaultPreviewContent)) {
  1531. return;
  1532. }
  1533. self.$preview.html('<div class="file-default-preview">' + self.defaultPreviewContent + '</div>');
  1534. self.$container.removeClass('file-input-new');
  1535. self._initClickable();
  1536. },
  1537. _resetPreviewThumbs: function (isAjax) {
  1538. var self = this, out;
  1539. if (isAjax) {
  1540. self._clearPreview();
  1541. self.clearStack();
  1542. return;
  1543. }
  1544. if (self._hasInitialPreview()) {
  1545. out = self.previewCache.out();
  1546. self.$preview.html(out.content);
  1547. self._setInitThumbAttr();
  1548. self._setCaption(out.caption);
  1549. self._initPreviewActions();
  1550. } else {
  1551. self._clearPreview();
  1552. }
  1553. },
  1554. _getLayoutTemplate: function (t) {
  1555. var self = this, template = self.layoutTemplates[t];
  1556. if ($h.isEmpty(self.customLayoutTags)) {
  1557. return template;
  1558. }
  1559. return $h.replaceTags(template, self.customLayoutTags);
  1560. },
  1561. _getPreviewTemplate: function (t) {
  1562. var self = this, template = self.previewTemplates[t];
  1563. if ($h.isEmpty(self.customPreviewTags)) {
  1564. return template;
  1565. }
  1566. return $h.replaceTags(template, self.customPreviewTags);
  1567. },
  1568. _getOutData: function (jqXHR, responseData, filesData) {
  1569. var self = this;
  1570. jqXHR = jqXHR || {};
  1571. responseData = responseData || {};
  1572. filesData = filesData || self.filestack.slice(0) || {};
  1573. return {
  1574. form: self.formdata,
  1575. files: filesData,
  1576. filenames: self.filenames,
  1577. filescount: self.getFilesCount(),
  1578. extra: self._getExtraData(),
  1579. response: responseData,
  1580. reader: self.reader,
  1581. jqXHR: jqXHR
  1582. };
  1583. },
  1584. _getMsgSelected: function (n) {
  1585. var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural;
  1586. return n > 0 ? self.msgSelected.replace('{n}', n).replace('{files}', strFiles) : self.msgNoFilesSelected;
  1587. },
  1588. _getThumbs: function (css) {
  1589. css = css || '';
  1590. return this.$preview.find($h.FRAMES + ':not(.file-preview-initial)' + css);
  1591. },
  1592. _getExtraData: function (previewId, index) {
  1593. var self = this, data = self.uploadExtraData;
  1594. if (typeof self.uploadExtraData === "function") {
  1595. data = self.uploadExtraData(previewId, index);
  1596. }
  1597. return data;
  1598. },
  1599. _initXhr: function (xhrobj, previewId, fileCount) {
  1600. var self = this;
  1601. if (xhrobj.upload) {
  1602. xhrobj.upload.addEventListener('progress', function (event) {
  1603. var pct = 0, total = event.total, position = event.loaded || event.position;
  1604. /** @namespace event.lengthComputable */
  1605. if (event.lengthComputable) {
  1606. pct = Math.floor(position / total * 100);
  1607. }
  1608. if (previewId) {
  1609. self._setAsyncUploadStatus(previewId, pct, fileCount);
  1610. } else {
  1611. self._setProgress(pct);
  1612. }
  1613. }, false);
  1614. }
  1615. return xhrobj;
  1616. },
  1617. _ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, previewId, index) {
  1618. var self = this, settings;
  1619. if (!self._raise('filepreajax', [previewId, index])) {
  1620. return;
  1621. }
  1622. self._uploadExtra(previewId, index);
  1623. settings = $.extend(true, {}, {
  1624. xhr: function () {
  1625. var xhrobj = $.ajaxSettings.xhr();
  1626. return self._initXhr(xhrobj, previewId, self.getFileStack().length);
  1627. },
  1628. url: self.uploadUrl,
  1629. type: 'POST',
  1630. dataType: 'json',
  1631. data: self.formdata,
  1632. cache: false,
  1633. processData: false,
  1634. contentType: false,
  1635. beforeSend: fnBefore,
  1636. success: fnSuccess,
  1637. complete: fnComplete,
  1638. error: fnError
  1639. }, self.ajaxSettings);
  1640. self.ajaxRequests.push($.ajax(settings));
  1641. },
  1642. _mergeArray: function (prop, content) {
  1643. var self = this, arr1 = $h.cleanArray(self[prop]), arr2 = $h.cleanArray(content);
  1644. self[prop] = arr1.concat(arr2);
  1645. },
  1646. _initUploadSuccess: function (out, $thumb, allFiles) {
  1647. var self = this, append, data, index, $div, $newCache, content, config, tags, i;
  1648. if (!self.showPreview || typeof out !== 'object' || $.isEmptyObject(out)) {
  1649. return;
  1650. }
  1651. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  1652. self.hasInitData = true;
  1653. content = out.initialPreview || [];
  1654. config = out.initialPreviewConfig || [];
  1655. tags = out.initialPreviewThumbTags || [];
  1656. append = out.append === undefined || out.append ? true : false;
  1657. if (content.length > 0 && !$h.isArray(content)) {
  1658. content = content.split(self.initialPreviewDelimiter);
  1659. }
  1660. self.overwriteInitial = false;
  1661. self._mergeArray('initialPreview', content);
  1662. self._mergeArray('initialPreviewConfig', config);
  1663. self._mergeArray('initialPreviewThumbTags', tags);
  1664. if ($thumb !== undefined) {
  1665. if (!allFiles) {
  1666. index = self.previewCache.add(content, config[0], tags[0], append);
  1667. data = self.previewCache.get(index, false);
  1668. $div = $(document.createElement('div')).html(data).hide().insertAfter($thumb);
  1669. $newCache = $div.find('.kv-zoom-cache');
  1670. if ($newCache && $newCache.length) {
  1671. $newCache.insertAfter($thumb);
  1672. }
  1673. $thumb.fadeOut('slow', function () {
  1674. var $newThumb = $div.find('.file-preview-frame');
  1675. if ($newThumb && $newThumb.length) {
  1676. $newThumb.insertBefore($thumb).fadeIn('slow').css('display:inline-block');
  1677. }
  1678. self._initPreviewActions();
  1679. self._clearFileInput();
  1680. $h.cleanZoomCache(self.$preview.find('#zoom-' + $thumb.attr('id')));
  1681. $thumb.remove();
  1682. $div.remove();
  1683. self._initSortable();
  1684. });
  1685. } else {
  1686. i = $thumb.attr('data-fileindex');
  1687. self.uploadCache.content[i] = content[0];
  1688. self.uploadCache.config[i] = config[0] || [];
  1689. self.uploadCache.tags[i] = tags[0] || [];
  1690. self.uploadCache.append = append;
  1691. }
  1692. } else {
  1693. self.previewCache.set(content, config, tags, append);
  1694. self._initPreview();
  1695. self._initPreviewActions();
  1696. }
  1697. }
  1698. },
  1699. _initSuccessThumbs: function () {
  1700. var self = this;
  1701. if (!self.showPreview) {
  1702. return;
  1703. }
  1704. self._getThumbs($h.FRAMES + '.file-preview-success').each(function () {
  1705. var $thumb = $(this), $preview = self.$preview, $remove = $thumb.find('.kv-file-remove');
  1706. $remove.removeAttr('disabled');
  1707. self._handler($remove, 'click', function () {
  1708. var id = $thumb.attr('id'), out = self._raise('filesuccessremove', [id, $thumb.data('fileindex')]);
  1709. $h.cleanMemory($thumb);
  1710. if (out === false) {
  1711. return;
  1712. }
  1713. $thumb.fadeOut('slow', function () {
  1714. $h.cleanZoomCache($preview.find('#zoom-' + id));
  1715. $thumb.remove();
  1716. if (!$preview.find($h.FRAMES).length) {
  1717. self.reset();
  1718. }
  1719. });
  1720. });
  1721. });
  1722. },
  1723. _checkAsyncComplete: function () {
  1724. var self = this, previewId, i;
  1725. for (i = 0; i < self.filestack.length; i++) {
  1726. if (self.filestack[i]) {
  1727. previewId = self.previewInitId + "-" + i;
  1728. if ($.inArray(previewId, self.uploadLog) === -1) {
  1729. return false;
  1730. }
  1731. }
  1732. }
  1733. return (self.uploadAsyncCount === self.uploadLog.length);
  1734. },
  1735. _uploadExtra: function (previewId, index) {
  1736. var self = this, data = self._getExtraData(previewId, index);
  1737. if (data.length === 0) {
  1738. return;
  1739. }
  1740. $.each(data, function (key, value) {
  1741. self.formdata.append(key, value);
  1742. });
  1743. },
  1744. _uploadSingle: function (i, files, allFiles) {
  1745. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  1746. previewId = self.previewInitId + "-" + i, $thumb, chkComplete, $btnUpload, $btnDelete,
  1747. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1748. $prog = $('#' + previewId).find('.file-thumb-progress'),
  1749. fnBefore, fnSuccess, fnComplete, fnError, updateUploadLog, params = {id: previewId, index: i};
  1750. self.formdata = formdata;
  1751. if (self.showPreview) {
  1752. $thumb = $('#' + previewId + ':not(.file-preview-initial)');
  1753. $btnUpload = $thumb.find('.kv-file-upload');
  1754. $btnDelete = $thumb.find('.kv-file-remove');
  1755. $prog.removeClass('hide');
  1756. }
  1757. if (total === 0 || !hasPostData || ($btnUpload && $btnUpload.hasClass('disabled')) || self._abort(params)) {
  1758. return;
  1759. }
  1760. updateUploadLog = function (i, previewId) {
  1761. self.updateStack(i, undefined);
  1762. self.uploadLog.push(previewId);
  1763. if (self._checkAsyncComplete()) {
  1764. self.fileBatchCompleted = true;
  1765. }
  1766. };
  1767. chkComplete = function () {
  1768. var u = self.uploadCache, $initThumbs, i, j, len = 0, data = self.cacheInitialPreview;
  1769. if (!self.fileBatchCompleted) {
  1770. return;
  1771. }
  1772. if (data && data.content) {
  1773. len = data.content.length;
  1774. }
  1775. setTimeout(function () {
  1776. if (self.showPreview) {
  1777. self.previewCache.set(u.content, u.config, u.tags, u.append);
  1778. if (len) {
  1779. for (i = 0; i < u.content.length; i++) {
  1780. j = i + len;
  1781. data.content[j] = u.content[i];
  1782. if (data.config.length) {
  1783. data.config[j] = u.config[i];
  1784. }
  1785. if (data.tags.length) {
  1786. data.tags[j] = u.tags[i];
  1787. }
  1788. }
  1789. self.initialPreview = $h.cleanArray(data.content);
  1790. self.initialPreviewConfig = $h.cleanArray(data.config);
  1791. self.initialPreviewThumbTags = $h.cleanArray(data.tags);
  1792. } else {
  1793. self.initialPreview = u.content;
  1794. self.initialPreviewConfig = u.config;
  1795. self.initialPreviewThumbTags = u.tags;
  1796. }
  1797. self.cacheInitialPreview = {};
  1798. if (self.hasInitData) {
  1799. self._initPreview();
  1800. self._initPreviewActions();
  1801. }
  1802. }
  1803. self.unlock();
  1804. self._clearFileInput();
  1805. $initThumbs = self.$preview.find('.file-preview-initial');
  1806. if (self.uploadAsync && $initThumbs.length) {
  1807. $h.addCss($initThumbs, $h.SORT_CSS);
  1808. self._initSortable();
  1809. }
  1810. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  1811. self.uploadCount = 0;
  1812. self.uploadStatus = {};
  1813. self.uploadLog = [];
  1814. self._setProgress(101);
  1815. }, 100);
  1816. };
  1817. fnBefore = function (jqXHR) {
  1818. outData = self._getOutData(jqXHR);
  1819. self.fileBatchCompleted = false;
  1820. if (self.showPreview) {
  1821. if (!$thumb.hasClass('file-preview-success')) {
  1822. self._setThumbStatus($thumb, 'Loading');
  1823. $h.addCss($thumb, 'file-uploading');
  1824. }
  1825. $btnUpload.attr('disabled', true);
  1826. $btnDelete.attr('disabled', true);
  1827. }
  1828. if (!allFiles) {
  1829. self.lock();
  1830. }
  1831. self._raise('filepreupload', [outData, previewId, i]);
  1832. $.extend(true, params, outData);
  1833. if (self._abort(params)) {
  1834. jqXHR.abort();
  1835. self._setProgressCancelled();
  1836. }
  1837. };
  1838. fnSuccess = function (data, textStatus, jqXHR) {
  1839. var pid = self.showPreview && $thumb.attr('id') ? $thumb.attr('id') : previewId;
  1840. outData = self._getOutData(jqXHR, data);
  1841. $.extend(true, params, outData);
  1842. setTimeout(function () {
  1843. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  1844. if (self.showPreview) {
  1845. self._setThumbStatus($thumb, 'Success');
  1846. $btnUpload.hide();
  1847. self._initUploadSuccess(data, $thumb, allFiles);
  1848. self._setProgress(101, $prog);
  1849. }
  1850. self._raise('fileuploaded', [outData, pid, i]);
  1851. if (!allFiles) {
  1852. self.updateStack(i, undefined);
  1853. } else {
  1854. updateUploadLog(i, pid);
  1855. }
  1856. } else {
  1857. self._showUploadError(data.error, params);
  1858. self._setPreviewError($thumb, i);
  1859. if (allFiles) {
  1860. updateUploadLog(i, pid);
  1861. }
  1862. }
  1863. }, 100);
  1864. };
  1865. fnComplete = function () {
  1866. setTimeout(function () {
  1867. if (self.showPreview) {
  1868. $btnUpload.removeAttr('disabled');
  1869. $btnDelete.removeAttr('disabled');
  1870. $thumb.removeClass('file-uploading');
  1871. }
  1872. if (!allFiles) {
  1873. self.unlock(false);
  1874. self._clearFileInput();
  1875. } else {
  1876. chkComplete();
  1877. }
  1878. self._initSuccessThumbs();
  1879. }, 100);
  1880. };
  1881. fnError = function (jqXHR, textStatus, errorThrown) {
  1882. var op = self.ajaxOperations.uploadThumb,
  1883. errMsg = self._parseError(op, jqXHR, errorThrown, (allFiles ? files[i].name : null));
  1884. setTimeout(function () {
  1885. if (allFiles) {
  1886. updateUploadLog(i, previewId);
  1887. }
  1888. self.uploadStatus[previewId] = 100;
  1889. self._setPreviewError($thumb, i);
  1890. $.extend(true, params, self._getOutData(jqXHR));
  1891. self._setProgress(101, $prog, self.msgAjaxProgressError.replace('{operation}', op));
  1892. self._showUploadError(errMsg, params);
  1893. }, 100);
  1894. };
  1895. formdata.append(self.uploadFileAttr, files[i], self.filenames[i]);
  1896. formdata.append('file_id', i);
  1897. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, previewId, i);
  1898. },
  1899. _uploadBatch: function () {
  1900. var self = this, files = self.filestack, total = files.length, params = {}, fnBefore, fnSuccess, fnError,
  1901. fnComplete, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1902. setAllUploaded;
  1903. self.formdata = new FormData();
  1904. if (total === 0 || !hasPostData || self._abort(params)) {
  1905. return;
  1906. }
  1907. setAllUploaded = function () {
  1908. $.each(files, function (key) {
  1909. self.updateStack(key, undefined);
  1910. });
  1911. self._clearFileInput();
  1912. };
  1913. fnBefore = function (jqXHR) {
  1914. self.lock();
  1915. var outData = self._getOutData(jqXHR);
  1916. if (self.showPreview) {
  1917. self._getThumbs().each(function () {
  1918. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  1919. $btnDelete = $thumb.find('.kv-file-remove');
  1920. if (!$thumb.hasClass('file-preview-success')) {
  1921. self._setThumbStatus($thumb, 'Loading');
  1922. $h.addCss($thumb, 'file-uploading');
  1923. }
  1924. $btnUpload.attr('disabled', true);
  1925. $btnDelete.attr('disabled', true);
  1926. });
  1927. }
  1928. self._raise('filebatchpreupload', [outData]);
  1929. if (self._abort(outData)) {
  1930. jqXHR.abort();
  1931. self._setProgressCancelled();
  1932. }
  1933. };
  1934. fnSuccess = function (data, textStatus, jqXHR) {
  1935. /** @namespace data.errorkeys */
  1936. var outData = self._getOutData(jqXHR, data), $thumbs = self._getThumbs(':not(.file-preview-error)'), key = 0,
  1937. keys = $h.isEmpty(data) || $h.isEmpty(data.errorkeys) ? [] : data.errorkeys;
  1938. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  1939. self._raise('filebatchuploadsuccess', [outData]);
  1940. setAllUploaded();
  1941. if (self.showPreview) {
  1942. $thumbs.each(function () {
  1943. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload');
  1944. $thumb.find('.kv-file-upload').hide();
  1945. self._setThumbStatus($thumb, 'Success');
  1946. $thumb.removeClass('file-uploading');
  1947. $btnUpload.removeAttr('disabled');
  1948. });
  1949. self._initUploadSuccess(data);
  1950. } else {
  1951. self.reset();
  1952. }
  1953. self._setProgress(101);
  1954. } else {
  1955. if (self.showPreview) {
  1956. $thumbs.each(function () {
  1957. var $thumb = $(this), $btnDelete = $thumb.find('.kv-file-remove'),
  1958. $btnUpload = $thumb.find('.kv-file-upload');
  1959. $thumb.removeClass('file-uploading');
  1960. $btnUpload.removeAttr('disabled');
  1961. $btnDelete.removeAttr('disabled');
  1962. if (keys.length === 0) {
  1963. self._setPreviewError($thumb);
  1964. return;
  1965. }
  1966. if ($.inArray(key, keys) !== -1) {
  1967. self._setPreviewError($thumb);
  1968. } else {
  1969. $thumb.find('.kv-file-upload').hide();
  1970. self._setThumbStatus($thumb, 'Success');
  1971. self.updateStack(key, undefined);
  1972. }
  1973. key++;
  1974. });
  1975. self._initUploadSuccess(data);
  1976. }
  1977. self._showUploadError(data.error, outData, 'filebatchuploaderror');
  1978. }
  1979. };
  1980. fnComplete = function () {
  1981. self.unlock();
  1982. self._initSuccessThumbs();
  1983. self._clearFileInput();
  1984. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  1985. };
  1986. fnError = function (jqXHR, textStatus, errorThrown) {
  1987. var outData = self._getOutData(jqXHR), op = self.ajaxOperations.uploadBatch,
  1988. errMsg = self._parseError(op, jqXHR, errorThrown);
  1989. self._showUploadError(errMsg, outData, 'filebatchuploaderror');
  1990. self.uploadFileCount = total - 1;
  1991. if (!self.showPreview) {
  1992. return;
  1993. }
  1994. self._getThumbs().each(function () {
  1995. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1996. $thumb.removeClass('file-uploading');
  1997. if (self.filestack[key] !== undefined) {
  1998. self._setPreviewError($thumb);
  1999. }
  2000. });
  2001. self._getThumbs().removeClass('file-uploading');
  2002. self._getThumbs(' .kv-file-upload').removeAttr('disabled');
  2003. self._getThumbs(' .kv-file-delete').removeAttr('disabled');
  2004. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  2005. };
  2006. $.each(files, function (key, data) {
  2007. if (!$h.isEmpty(files[key])) {
  2008. self.formdata.append(self.uploadFileAttr, data, self.filenames[key]);
  2009. }
  2010. });
  2011. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  2012. },
  2013. _uploadExtraOnly: function () {
  2014. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  2015. self.formdata = new FormData();
  2016. if (self._abort(params)) {
  2017. return;
  2018. }
  2019. fnBefore = function (jqXHR) {
  2020. self.lock();
  2021. var outData = self._getOutData(jqXHR);
  2022. self._raise('filebatchpreupload', [outData]);
  2023. self._setProgress(50);
  2024. params.data = outData;
  2025. params.xhr = jqXHR;
  2026. if (self._abort(params)) {
  2027. jqXHR.abort();
  2028. self._setProgressCancelled();
  2029. }
  2030. };
  2031. fnSuccess = function (data, textStatus, jqXHR) {
  2032. var outData = self._getOutData(jqXHR, data);
  2033. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  2034. self._raise('filebatchuploadsuccess', [outData]);
  2035. self._clearFileInput();
  2036. self._initUploadSuccess(data);
  2037. self._setProgress(101);
  2038. } else {
  2039. self._showUploadError(data.error, outData, 'filebatchuploaderror');
  2040. }
  2041. };
  2042. fnComplete = function () {
  2043. self.unlock();
  2044. self._clearFileInput();
  2045. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  2046. };
  2047. fnError = function (jqXHR, textStatus, errorThrown) {
  2048. var outData = self._getOutData(jqXHR), op = self.ajaxOperations.uploadExtra,
  2049. errMsg = self._parseError(op, jqXHR, errorThrown);
  2050. params.data = outData;
  2051. self._showUploadError(errMsg, outData, 'filebatchuploaderror');
  2052. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  2053. };
  2054. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  2055. },
  2056. _deleteFileIndex: function ($frame) {
  2057. var self = this, ind = $frame.attr('data-fileindex');
  2058. if (ind.substring(0, 5) === 'init_') {
  2059. ind = parseInt(ind.replace('init_', ''));
  2060. self.initialPreview = $h.spliceArray(self.initialPreview, ind);
  2061. self.initialPreviewConfig = $h.spliceArray(self.initialPreviewConfig, ind);
  2062. self.initialPreviewThumbTags = $h.spliceArray(self.initialPreviewThumbTags, ind);
  2063. self.$preview.find($h.FRAMES).each(function () {
  2064. var $nFrame = $(this), nInd = $nFrame.attr('data-fileindex');
  2065. if (nInd.substring(0, 5) === 'init_') {
  2066. nInd = parseInt(nInd.replace('init_', ''));
  2067. if (nInd > ind) {
  2068. nInd--;
  2069. $nFrame.attr('data-fileindex', 'init_' + nInd);
  2070. }
  2071. }
  2072. });
  2073. if (self.uploadAsync) {
  2074. self.cacheInitialPreview = self.getPreview();
  2075. }
  2076. }
  2077. },
  2078. _initFileActions: function () {
  2079. var self = this, $preview = self.$preview;
  2080. if (!self.showPreview) {
  2081. return;
  2082. }
  2083. self._initZoomButton();
  2084. $preview.find($h.FRAMES + ' .kv-file-remove').each(function () {
  2085. var $el = $(this), $frame = $el.closest($h.FRAMES), hasError, id = $frame.attr('id'),
  2086. ind = $frame.attr('data-fileindex'), n, cap, status;
  2087. self._handler($el, 'click', function () {
  2088. status = self._raise('filepreremove', [id, ind]);
  2089. if (status === false || !self._validateMinCount()) {
  2090. return false;
  2091. }
  2092. hasError = $frame.hasClass('file-preview-error');
  2093. $h.cleanMemory($frame);
  2094. $frame.fadeOut('slow', function () {
  2095. $h.cleanZoomCache($preview.find('#zoom-' + id));
  2096. self.updateStack(ind, undefined);
  2097. self._clearObjects($frame);
  2098. $frame.remove();
  2099. if (id && hasError) {
  2100. self.$errorContainer.find('li[data-file-id="' + id + '"]').fadeOut('fast', function () {
  2101. $(this).remove();
  2102. if (!self._errorsExist()) {
  2103. self._resetErrors();
  2104. }
  2105. });
  2106. }
  2107. self._clearFileInput();
  2108. var filestack = self.getFileStack(true), chk = self.previewCache.count(),
  2109. len = filestack.length,
  2110. hasThumb = self.showPreview && $preview.find($h.FRAMES).length;
  2111. if (len === 0 && chk === 0 && !hasThumb) {
  2112. self.reset();
  2113. } else {
  2114. n = chk + len;
  2115. cap = n > 1 ? self._getMsgSelected(n) : (filestack[0] ? self._getFileNames()[0] : '');
  2116. self._setCaption(cap);
  2117. }
  2118. self._raise('fileremoved', [id, ind]);
  2119. });
  2120. });
  2121. });
  2122. self.$preview.find($h.FRAMES + ' .kv-file-upload').each(function () {
  2123. var $el = $(this);
  2124. self._handler($el, 'click', function () {
  2125. var $frame = $el.closest($h.FRAMES), ind = $frame.attr('data-fileindex');
  2126. if (!$frame.hasClass('file-preview-error')) {
  2127. self._uploadSingle(ind, self.filestack, false);
  2128. }
  2129. });
  2130. });
  2131. },
  2132. _initPreviewActions: function () {
  2133. var self = this, $preview = self.$preview, deleteExtraData = self.deleteExtraData || {},
  2134. btnRemove = $h.FRAMES + ' .kv-file-remove',
  2135. resetProgress = function () {
  2136. var hasFiles = self.isUploadable ? self.previewCache.count() : self.$element.get(0).files.length;
  2137. if ($preview.find(btnRemove).length === 0 && !hasFiles) {
  2138. self.reset();
  2139. self.initialCaption = '';
  2140. }
  2141. };
  2142. self._initZoomButton();
  2143. $preview.find(btnRemove).each(function () {
  2144. var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key');
  2145. if ($h.isEmpty(vUrl) || vKey === undefined) {
  2146. return;
  2147. }
  2148. var $frame = $el.closest($h.FRAMES), cache = self.previewCache.data,
  2149. settings, params, index = $frame.data('fileindex'), config, extraData;
  2150. index = parseInt(index.replace('init_', ''));
  2151. config = $h.isEmpty(cache.config) && $h.isEmpty(cache.config[index]) ? null : cache.config[index];
  2152. extraData = $h.isEmpty(config) || $h.isEmpty(config.extra) ? deleteExtraData : config.extra;
  2153. if (typeof extraData === "function") {
  2154. extraData = extraData();
  2155. }
  2156. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  2157. settings = $.extend(true, {}, {
  2158. url: vUrl,
  2159. type: 'POST',
  2160. dataType: 'json',
  2161. data: $.extend(true, {}, {key: vKey}, extraData),
  2162. beforeSend: function (jqXHR) {
  2163. self.ajaxAborted = false;
  2164. self._raise('filepredelete', [vKey, jqXHR, extraData]);
  2165. if (self.ajaxAborted) {
  2166. jqXHR.abort();
  2167. } else {
  2168. $h.addCss($frame, 'file-uploading');
  2169. $h.addCss($el, 'disabled');
  2170. }
  2171. },
  2172. success: function (data, textStatus, jqXHR) {
  2173. var n, cap;
  2174. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  2175. self.previewCache.init();
  2176. index = parseInt(($frame.data('fileindex')).replace('init_', ''));
  2177. self.previewCache.unset(index);
  2178. n = self.previewCache.count();
  2179. cap = n > 0 ? self._getMsgSelected(n) : '';
  2180. self._deleteFileIndex($frame);
  2181. self._setCaption(cap);
  2182. self._raise('filedeleted', [vKey, jqXHR, extraData]);
  2183. } else {
  2184. params.jqXHR = jqXHR;
  2185. params.response = data;
  2186. self._showError(data.error, params, 'filedeleteerror');
  2187. $frame.removeClass('file-uploading');
  2188. $el.removeClass('disabled');
  2189. resetProgress();
  2190. return;
  2191. }
  2192. $frame.removeClass('file-uploading').addClass('file-deleted');
  2193. $frame.fadeOut('slow', function () {
  2194. $h.cleanZoomCache($preview.find('#zoom-' + $frame.attr('id')));
  2195. self._clearObjects($frame);
  2196. $frame.remove();
  2197. resetProgress();
  2198. if (!n && self.getFileStack().length === 0) {
  2199. self._setCaption('');
  2200. self.reset();
  2201. }
  2202. });
  2203. },
  2204. error: function (jqXHR, textStatus, errorThrown) {
  2205. var op = self.ajaxOperations.deleteThumb, errMsg = self._parseError(op, jqXHR, errorThrown);
  2206. params.jqXHR = jqXHR;
  2207. params.response = {};
  2208. self._showError(errMsg, params, 'filedeleteerror');
  2209. $frame.removeClass('file-uploading');
  2210. resetProgress();
  2211. }
  2212. }, self.ajaxDeleteSettings);
  2213. self._handler($el, 'click', function () {
  2214. if (!self._validateMinCount()) {
  2215. return false;
  2216. }
  2217. $.ajax(settings);
  2218. });
  2219. });
  2220. },
  2221. _hideFileIcon: function () {
  2222. if (this.overwriteInitial) {
  2223. this.$captionContainer.find('.kv-caption-icon').hide();
  2224. }
  2225. },
  2226. _showFileIcon: function () {
  2227. this.$captionContainer.find('.kv-caption-icon').show();
  2228. },
  2229. _getSize: function (bytes) {
  2230. var self = this, size = parseFloat(bytes), i, func = self.fileSizeGetter, sizes, out;
  2231. if (!$.isNumeric(bytes) || !$.isNumeric(size)) {
  2232. return '';
  2233. }
  2234. if (typeof func === 'function') {
  2235. out = func(size);
  2236. } else {
  2237. if (size === 0) {
  2238. out = '0.00 B';
  2239. } else {
  2240. i = Math.floor(Math.log(size) / Math.log(1024));
  2241. sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  2242. out = (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + sizes[i];
  2243. }
  2244. }
  2245. return self._getLayoutTemplate('size').replace('{sizeText}', out);
  2246. },
  2247. _generatePreviewTemplate: function (cat, data, fname, ftype, previewId, isError, size, frameClass, foot, ind, templ) {
  2248. var self = this, caption = self.slug(fname), prevContent, zoomContent = '',
  2249. config = self.previewSettings[cat] || self.defaults.previewSettings[cat],
  2250. w = config && config.width ? config.width : '', h = config && config.height ? config.height : '',
  2251. footer = foot || self._renderFileFooter(caption, size, ($h.isEmpty(w) ? 'auto' : w), isError),
  2252. hasIconSetting = self._getPreviewIcon(fname),
  2253. forcePrevIcon = hasIconSetting && self.preferIconicPreview,
  2254. forceZoomIcon = hasIconSetting && self.preferIconicZoomPreview,
  2255. getContent = function (c, d, zoom, frameCss) {
  2256. var id = zoom ? 'zoom-' + previewId : previewId, tmplt = self._getPreviewTemplate(c),
  2257. css = (frameClass || '') + ' ' + frameCss;
  2258. if (self.frameClass) {
  2259. css = self.frameClass + ' ' + css;
  2260. }
  2261. if (zoom) {
  2262. css = css.replace(' ' + $h.SORT_CSS, '');
  2263. }
  2264. tmplt = self._parseFilePreviewIcon(tmplt, fname);
  2265. if (c === 'text') {
  2266. d = $h.htmlEncode(d);
  2267. }
  2268. return tmplt.replace(/\{previewId}/g, id).replace(/\{caption}/g, caption)
  2269. .replace(/\{frameClass}/g, css).replace(/\{type}/g, ftype).replace(/\{fileindex}/g, ind)
  2270. .replace(/\{width}/g, w).replace(/\{height}/g, h)
  2271. .replace(/\{footer}/g, footer).replace(/\{data}/g, d).replace(/\{template}/g, templ || cat);
  2272. };
  2273. ind = ind || previewId.slice(previewId.lastIndexOf('-') + 1);
  2274. if (self.fileActionSettings.showZoom) {
  2275. zoomContent = getContent((forceZoomIcon ? 'other' : cat), data, true, 'kv-zoom-thumb');
  2276. }
  2277. zoomContent = '\n' + self._getLayoutTemplate('zoomCache').replace('{zoomContent}', zoomContent);
  2278. prevContent = getContent((forcePrevIcon ? 'other' : cat), data, false, 'kv-preview-thumb');
  2279. return prevContent + zoomContent;
  2280. },
  2281. _previewDefault: function (file, previewId, isDisabled) {
  2282. var self = this, $preview = self.$preview;
  2283. if (!self.showPreview) {
  2284. return;
  2285. }
  2286. var fname = file ? file.name : '', ftype = file ? file.type : '', content, size = file.size || 0,
  2287. caption = self.slug(fname), isError = isDisabled === true && !self.isUploadable,
  2288. data = $h.objUrl.createObjectURL(file);
  2289. self._clearDefaultPreview();
  2290. content = self._generatePreviewTemplate('other', data, fname, ftype, previewId, isError, size);
  2291. $preview.append("\n" + content);
  2292. self._setThumbAttr(previewId, caption, size);
  2293. if (isDisabled === true && self.isUploadable) {
  2294. self._setThumbStatus($('#' + previewId), 'Error');
  2295. }
  2296. },
  2297. _previewFile: function (i, file, theFile, previewId, data) {
  2298. if (!this.showPreview) {
  2299. return;
  2300. }
  2301. var self = this, cat = self._parseFileType(file), fname = file ? file.name : '', caption = self.slug(fname),
  2302. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes, $preview = self.$preview,
  2303. chkTypes = types && types.indexOf(cat) >= 0, size = file.size || 0,
  2304. iData = (cat === 'text' || cat === 'html' || cat === 'image') ? theFile.target.result : data, content,
  2305. chkMimes = mimes && mimes.indexOf(file.type) !== -1;
  2306. /** @namespace window.DOMPurify */
  2307. if (cat === 'html' && self.purifyHtml && window.DOMPurify) {
  2308. iData = window.DOMPurify.sanitize(iData);
  2309. }
  2310. if (chkTypes || chkMimes) {
  2311. content = self._generatePreviewTemplate(cat, iData, fname, file.type, previewId, false, size);
  2312. self._clearDefaultPreview();
  2313. $preview.append("\n" + content);
  2314. self._validateImage(previewId, caption, file.type);
  2315. } else {
  2316. self._previewDefault(file, previewId);
  2317. }
  2318. self._setThumbAttr(previewId, caption, size);
  2319. self._initSortable();
  2320. },
  2321. _setThumbAttr: function (id, caption, size) {
  2322. var self = this, $frame = $('#' + id);
  2323. if ($frame.length) {
  2324. size = size && size > 0 ? self._getSize(size) : '';
  2325. $frame.data({'caption': caption, 'size': size});
  2326. }
  2327. },
  2328. _setInitThumbAttr: function () {
  2329. var self = this, data = self.previewCache.data, len = self.previewCache.count(true), config,
  2330. caption, size, previewId;
  2331. if (len === 0) {
  2332. return;
  2333. }
  2334. for (var i = 0; i < len; i++) {
  2335. config = data.config[i];
  2336. previewId = self.previewInitId + '-' + 'init_' + i;
  2337. caption = $h.ifSet('caption', config, $h.ifSet('filename', config));
  2338. size = $h.ifSet('size', config);
  2339. self._setThumbAttr(previewId, caption, size);
  2340. }
  2341. },
  2342. _slugDefault: function (text) {
  2343. return $h.isEmpty(text) ? '' : String(text).replace(/[\-\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_');
  2344. },
  2345. _readFiles: function (files) {
  2346. this.reader = new FileReader();
  2347. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  2348. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  2349. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  2350. settings = self.fileTypeSettings, ctr = self.filestack.length, readFile,
  2351. fileTypes = self.allowedFileTypes, typLen = fileTypes ? fileTypes.length : 0,
  2352. fileExt = self.allowedFileExtensions, strExt = $h.isEmpty(fileExt) ? '' : fileExt.join(', '),
  2353. maxPreviewSize = self.maxFilePreviewSize && parseFloat(self.maxFilePreviewSize),
  2354. canPreview = $preview.length && (!maxPreviewSize || isNaN(maxPreviewSize)),
  2355. throwError = function (msg, file, previewId, index) {
  2356. var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}),
  2357. p2 = {id: previewId, index: index, file: file, files: files};
  2358. self._previewDefault(file, previewId, true);
  2359. if (self.isUploadable) {
  2360. self.addToStack(undefined);
  2361. setTimeout(function () {
  2362. readFile(index + 1);
  2363. }, 100);
  2364. }
  2365. self._initFileActions();
  2366. if (self.removeFromPreviewOnError) {
  2367. $('#' + previewId).remove();
  2368. }
  2369. return self.isUploadable ? self._showUploadError(msg, p1) : self._showError(msg, p2);
  2370. };
  2371. self.loadedImages = [];
  2372. self.totalImagesCount = 0;
  2373. $.each(files, function (key, file) {
  2374. var func = self.fileTypeSettings.image;
  2375. if (func && func(file.type)) {
  2376. self.totalImagesCount++;
  2377. }
  2378. });
  2379. readFile = function (i) {
  2380. if ($h.isEmpty($el.attr('multiple'))) {
  2381. numFiles = 1;
  2382. }
  2383. if (i >= numFiles) {
  2384. if (self.isUploadable && self.filestack.length > 0) {
  2385. self._raise('filebatchselected', [self.getFileStack()]);
  2386. } else {
  2387. self._raise('filebatchselected', [files]);
  2388. }
  2389. $container.removeClass('file-thumb-loading');
  2390. $status.html('');
  2391. return;
  2392. }
  2393. var node = ctr + i, previewId = previewInitId + "-" + node, isText, isImage, file = files[i], fSizeKB,
  2394. caption = file.name ? self.slug(file.name) : '', fileSize = (file.size || 0) / 1000, j, msg,
  2395. fileExtExpr = '', previewData = $h.objUrl.createObjectURL(file), typ, chk, typ1, typ2,
  2396. fileCount = 0, strTypes = '', func;
  2397. if (typLen > 0) {
  2398. for (j = 0; j < typLen; j++) {
  2399. typ1 = fileTypes[j];
  2400. typ2 = self.msgFileTypes[typ1] || typ1;
  2401. strTypes += j === 0 ? typ2 : ', ' + typ2;
  2402. }
  2403. }
  2404. if (caption === false) {
  2405. readFile(i + 1);
  2406. return;
  2407. }
  2408. if (caption.length === 0) {
  2409. msg = self.msgInvalidFileName.replace('{name}', $h.htmlEncode(file.name));
  2410. self.isError = throwError(msg, file, previewId, i);
  2411. return;
  2412. }
  2413. if (!$h.isEmpty(fileExt)) {
  2414. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  2415. }
  2416. fSizeKB = fileSize.toFixed(2);
  2417. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  2418. msg = self.msgSizeTooLarge.replace('{name}', caption).replace('{size}', fSizeKB)
  2419. .replace('{maxSize}', self.maxFileSize);
  2420. self.isError = throwError(msg, file, previewId, i);
  2421. return;
  2422. }
  2423. if (self.minFileSize !== null && fileSize <= $h.getNum(self.minFileSize)) {
  2424. msg = self.msgSizeTooSmall.replace('{name}', caption).replace('{size}', fSizeKB)
  2425. .replace('{minSize}', self.minFileSize);
  2426. self.isError = throwError(msg, file, previewId, i);
  2427. return;
  2428. }
  2429. if (!$h.isEmpty(fileTypes) && $h.isArray(fileTypes)) {
  2430. for (j = 0; j < fileTypes.length; j += 1) {
  2431. typ = fileTypes[j];
  2432. func = settings[typ];
  2433. fileCount += !func || (typeof func !== 'function') ? 0 : (func(file.type, file.name) ? 1 : 0);
  2434. }
  2435. if (fileCount === 0) {
  2436. msg = self.msgInvalidFileType.replace('{name}', caption).replace('{types}', strTypes);
  2437. self.isError = throwError(msg, file, previewId, i);
  2438. return;
  2439. }
  2440. }
  2441. if (fileCount === 0 && !$h.isEmpty(fileExt) && $h.isArray(fileExt) && !$h.isEmpty(fileExtExpr)) {
  2442. chk = $h.compare(caption, fileExtExpr);
  2443. fileCount += $h.isEmpty(chk) ? 0 : chk.length;
  2444. if (fileCount === 0) {
  2445. msg = self.msgInvalidFileExtension.replace('{name}', caption).replace('{extensions}', strExt);
  2446. self.isError = throwError(msg, file, previewId, i);
  2447. return;
  2448. }
  2449. }
  2450. if (!self.showPreview) {
  2451. self.addToStack(file);
  2452. setTimeout(function () {
  2453. readFile(i + 1);
  2454. }, 100);
  2455. self._raise('fileloaded', [file, previewId, i, reader]);
  2456. return;
  2457. }
  2458. if (!canPreview && fileSize > maxPreviewSize) {
  2459. self.addToStack(file);
  2460. $container.addClass('file-thumb-loading');
  2461. self._previewDefault(file, previewId);
  2462. self._initFileActions();
  2463. self._updateFileDetails(numFiles);
  2464. readFile(i + 1);
  2465. return;
  2466. }
  2467. if ($preview.length && FileReader !== undefined) {
  2468. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  2469. $container.addClass('file-thumb-loading');
  2470. reader.onerror = function (evt) {
  2471. self._errorHandler(evt, caption);
  2472. };
  2473. reader.onload = function (theFile) {
  2474. self._previewFile(i, file, theFile, previewId, previewData);
  2475. self._initFileActions();
  2476. };
  2477. reader.onloadend = function () {
  2478. msg = msgProgress.replace('{index}', i + 1).replace('{files}', numFiles)
  2479. .replace('{percent}', 50).replace('{name}', caption);
  2480. setTimeout(function () {
  2481. $status.html(msg);
  2482. self._updateFileDetails(numFiles);
  2483. readFile(i + 1);
  2484. }, 100);
  2485. self._raise('fileloaded', [file, previewId, i, reader]);
  2486. };
  2487. reader.onprogress = function (data) {
  2488. if (data.lengthComputable) {
  2489. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  2490. msg = msgProgress.replace('{index}', i + 1).replace('{files}', numFiles)
  2491. .replace('{percent}', progress).replace('{name}', caption);
  2492. setTimeout(function () {
  2493. $status.html(msg);
  2494. }, 100);
  2495. }
  2496. };
  2497. isText = settings.text;
  2498. isImage = settings.image;
  2499. if (isText(file.type, caption)) {
  2500. reader.readAsText(file, self.textEncoding);
  2501. } else {
  2502. if (isImage(file.type, caption)) {
  2503. reader.readAsDataURL(file);
  2504. } else {
  2505. reader.readAsArrayBuffer(file);
  2506. }
  2507. }
  2508. } else {
  2509. self._previewDefault(file, previewId);
  2510. setTimeout(function () {
  2511. readFile(i + 1);
  2512. self._updateFileDetails(numFiles);
  2513. }, 100);
  2514. self._raise('fileloaded', [file, previewId, i, reader]);
  2515. }
  2516. self.addToStack(file);
  2517. };
  2518. readFile(0);
  2519. self._updateFileDetails(numFiles, false);
  2520. },
  2521. _updateFileDetails: function (numFiles) {
  2522. var self = this, $el = self.$element, fileStack = self.getFileStack(),
  2523. name = ($h.isIE(9) && $h.findFileName($el.val())) ||
  2524. ($el[0].files[0] && $el[0].files[0].name) || (fileStack.length && fileStack[0].name) || '',
  2525. label = self.slug(name), n = self.isUploadable ? fileStack.length : numFiles,
  2526. nFiles = self.previewCache.count() + n, log = n > 1 ? self._getMsgSelected(nFiles) : label;
  2527. if (self.isError) {
  2528. self.$previewContainer.removeClass('file-thumb-loading');
  2529. self.$previewStatus.html('');
  2530. self.$captionContainer.find('.kv-caption-icon').hide();
  2531. } else {
  2532. self._showFileIcon();
  2533. }
  2534. self._setCaption(log, self.isError);
  2535. self.$container.removeClass('file-input-new file-input-ajax-new');
  2536. if (arguments.length === 1) {
  2537. self._raise('fileselect', [numFiles, label]);
  2538. }
  2539. if (self.previewCache.count()) {
  2540. self._initPreviewActions();
  2541. }
  2542. },
  2543. _setThumbStatus: function ($thumb, status) {
  2544. var self = this;
  2545. if (!self.showPreview) {
  2546. return;
  2547. }
  2548. var icon = 'indicator' + status, msg = icon + 'Title',
  2549. css = 'file-preview-' + status.toLowerCase(),
  2550. $indicator = $thumb.find('.file-upload-indicator'),
  2551. config = self.fileActionSettings;
  2552. $thumb.removeClass('file-preview-success file-preview-error file-preview-loading');
  2553. if (status === 'Error') {
  2554. $thumb.find('.kv-file-upload').attr('disabled', true);
  2555. }
  2556. if (status === 'Success') {
  2557. $thumb.find('.file-drag-handle').remove();
  2558. $indicator.css('margin-left', 0);
  2559. }
  2560. $indicator.html(config[icon]);
  2561. $indicator.attr('title', config[msg]);
  2562. $thumb.addClass(css);
  2563. },
  2564. _setProgressCancelled: function () {
  2565. var self = this;
  2566. self._setProgress(101, self.$progress, self.msgCancelled);
  2567. },
  2568. _setProgress: function (p, $el, error) {
  2569. var self = this, pct = Math.min(p, 100), out, status, pctLimit = self.progressUploadThreshold,
  2570. t = p <= 100 ? self.progressTemplate : self.progressCompleteTemplate,
  2571. template = pct < 100 ? self.progressTemplate : (error ? self.progressErrorTemplate : t);
  2572. $el = $el || self.$progress;
  2573. if (!$h.isEmpty(template)) {
  2574. if (pctLimit && pct > pctLimit && p <= 100) {
  2575. out = template.replace(/\{percent}/g, pctLimit).replace(/\{status}/g, self.msgUploadThreshold);
  2576. } else {
  2577. status = p > 100 ? self.msgUploadEnd : pct + '%';
  2578. out = template.replace(/\{percent}/g, pct).replace(/\{status}/g, status);
  2579. }
  2580. $el.html(out);
  2581. if (error) {
  2582. $el.find('[role="progressbar"]').html(error);
  2583. }
  2584. }
  2585. },
  2586. _setFileDropZoneTitle: function () {
  2587. var self = this, $zone = self.$container.find('.file-drop-zone'), title = self.dropZoneTitle, strFiles;
  2588. if (self.isClickable) {
  2589. strFiles = $h.isEmpty(self.$element.attr('multiple')) ? self.fileSingle : self.filePlural;
  2590. title += self.dropZoneClickTitle.replace('{files}', strFiles);
  2591. }
  2592. $zone.find('.' + self.dropZoneTitleClass).remove();
  2593. if (!self.isUploadable || !self.showPreview || $zone.length === 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled) {
  2594. return;
  2595. }
  2596. if ($zone.find($h.FRAMES).length === 0 && $h.isEmpty(self.defaultPreviewContent)) {
  2597. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + title + '</div>');
  2598. }
  2599. self.$container.removeClass('file-input-new');
  2600. $h.addCss(self.$container, 'file-input-ajax-new');
  2601. },
  2602. _setAsyncUploadStatus: function (previewId, pct, total) {
  2603. var self = this, sum = 0;
  2604. self._setProgress(pct, $('#' + previewId).find('.file-thumb-progress'));
  2605. self.uploadStatus[previewId] = pct;
  2606. $.each(self.uploadStatus, function (key, value) {
  2607. sum += value;
  2608. });
  2609. self._setProgress(Math.floor(sum / total));
  2610. },
  2611. _validateMinCount: function () {
  2612. var self = this, len = self.isUploadable ? self.getFileStack().length : self.$element.get(0).files.length;
  2613. if (self.validateInitialCount && self.minFileCount > 0 && self._getFileCount(len - 1) < self.minFileCount) {
  2614. self._noFilesError({});
  2615. return false;
  2616. }
  2617. return true;
  2618. },
  2619. _getFileCount: function (fileCount) {
  2620. var self = this, addCount = 0;
  2621. if (self.validateInitialCount && !self.overwriteInitial) {
  2622. addCount = self.previewCache.count();
  2623. fileCount += addCount;
  2624. }
  2625. return fileCount;
  2626. },
  2627. _getFileName: function (file) {
  2628. return file && file.name ? this.slug(file.name) : undefined;
  2629. },
  2630. _getFileNames: function (skipNull) {
  2631. var self = this;
  2632. return self.filenames.filter(function (n) {
  2633. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  2634. });
  2635. },
  2636. _setPreviewError: function ($thumb, i, val) {
  2637. var self = this;
  2638. if (i !== undefined) {
  2639. self.updateStack(i, val);
  2640. }
  2641. if (self.removeFromPreviewOnError) {
  2642. $thumb.remove();
  2643. } else {
  2644. self._setThumbStatus($thumb, 'Error');
  2645. }
  2646. },
  2647. _checkDimensions: function (i, chk, $img, $thumb, fname, type, params) {
  2648. var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max', limit = self[tag + 'Image' + type],
  2649. $imgEl, isValid;
  2650. if ($h.isEmpty(limit) || !$img.length) {
  2651. return;
  2652. }
  2653. $imgEl = $img[0];
  2654. dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height;
  2655. isValid = chk === 'Small' ? dim >= limit : dim <= limit;
  2656. if (isValid) {
  2657. return;
  2658. }
  2659. msg = self['msgImage' + type + chk].replace('{name}', fname).replace('{size}', limit);
  2660. self._showUploadError(msg, params);
  2661. self._setPreviewError($thumb, i, null);
  2662. },
  2663. _validateImage: function (previewId, fname, ftype) {
  2664. var self = this, $preview = self.$preview, params, w1, w2, $thumb = $preview.find("#" + previewId),
  2665. i = $thumb.attr('data-fileindex'), $img = $thumb.find('img');
  2666. fname = fname || 'Untitled';
  2667. if (!$img.length) {
  2668. return;
  2669. }
  2670. self._handler($img, 'load', function () {
  2671. w1 = $thumb.width();
  2672. w2 = $preview.width();
  2673. if (w1 > w2) {
  2674. $img.css('width', '100%');
  2675. $thumb.css('width', '97%');
  2676. }
  2677. params = {ind: i, id: previewId};
  2678. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
  2679. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
  2680. if (!self.resizeImage) {
  2681. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
  2682. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
  2683. }
  2684. self._raise('fileimageloaded', [previewId]);
  2685. self.loadedImages.push({ind: i, img: $img, thumb: $thumb, pid: previewId, typ: ftype});
  2686. self._validateAllImages();
  2687. });
  2688. },
  2689. _validateAllImages: function () {
  2690. var self = this, i, counter = {val: 0}, numImgs = self.loadedImages.length;
  2691. if (numImgs !== self.totalImagesCount) {
  2692. return;
  2693. }
  2694. self._raise('fileimagesloaded');
  2695. if (!self.resizeImage) {
  2696. return;
  2697. }
  2698. for (i = 0; i < self.loadedImages.length; i++) {
  2699. self._getResizedImage(self.loadedImages[i], counter, numImgs);
  2700. }
  2701. },
  2702. _getResizedImage: function (config, counter, numImgs) {
  2703. var self = this, img = $(config.img)[0], width = img.naturalWidth, height = img.naturalHeight,
  2704. ratio = 1, maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height,
  2705. isValidImage = !!(width && height), chkWidth, chkHeight, canvas = self.imageCanvas,
  2706. context = self.imageCanvasContext, type = config.typ, pid = config.pid, ind = config.ind,
  2707. thumb = config.thumb, throwError, msg;
  2708. throwError = function (msg, params, ev) {
  2709. if (self.isUploadable) {
  2710. self._showUploadError(msg, params, ev);
  2711. } else {
  2712. self._showError(msg, params, ev);
  2713. }
  2714. self._setPreviewError(thumb, ind);
  2715. };
  2716. if (!self.filestack[ind] || !isValidImage || (width <= maxWidth && height <= maxHeight)) {
  2717. if (isValidImage && self.filestack[ind]) {
  2718. self._raise('fileimageresized', [pid, ind]);
  2719. }
  2720. counter.val++;
  2721. if (counter.val === numImgs) {
  2722. self._raise('fileimagesresized');
  2723. }
  2724. if (!isValidImage) {
  2725. throwError(self.msgImageResizeError, {id: pid, 'index': ind}, 'fileimageresizeerror');
  2726. return;
  2727. }
  2728. }
  2729. type = type || self.resizeDefaultImageType;
  2730. chkWidth = width > maxWidth;
  2731. chkHeight = height > maxHeight;
  2732. if (self.resizePreference === 'width') {
  2733. ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1);
  2734. } else {
  2735. ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1);
  2736. }
  2737. self._resetCanvas();
  2738. width *= ratio;
  2739. height *= ratio;
  2740. canvas.width = width;
  2741. canvas.height = height;
  2742. try {
  2743. context.drawImage(img, 0, 0, width, height);
  2744. canvas.toBlob(function (blob) {
  2745. self.filestack[ind] = blob;
  2746. self._raise('fileimageresized', [pid, ind]);
  2747. counter.val++;
  2748. if (counter.val === numImgs) {
  2749. self._raise('fileimagesresized', [undefined, undefined]);
  2750. }
  2751. if (!(blob instanceof Blob)) {
  2752. throwError(self.msgImageResizeError, {id: pid, 'index': ind}, 'fileimageresizeerror');
  2753. }
  2754. }, type, self.resizeQuality);
  2755. }
  2756. catch (err) {
  2757. counter.val++;
  2758. if (counter.val === numImgs) {
  2759. self._raise('fileimagesresized', [undefined, undefined]);
  2760. }
  2761. msg = self.msgImageResizeException.replace('{errors}', err.message);
  2762. throwError(msg, {id: pid, 'index': ind}, 'fileimageresizeexception');
  2763. }
  2764. },
  2765. _initBrowse: function ($container) {
  2766. var self = this;
  2767. if (self.showBrowse) {
  2768. self.$btnFile = $container.find('.btn-file');
  2769. self.$btnFile.append(self.$element);
  2770. } else {
  2771. self.$element.hide();
  2772. }
  2773. },
  2774. _initCaption: function () {
  2775. var self = this, cap = self.initialCaption || '';
  2776. if (self.overwriteInitial || $h.isEmpty(cap)) {
  2777. self.$caption.html('');
  2778. return false;
  2779. }
  2780. self._setCaption(cap);
  2781. return true;
  2782. },
  2783. _setCaption: function (content, isError) {
  2784. var self = this, title, out, n, cap, stack = self.getFileStack();
  2785. if (!self.$caption.length) {
  2786. return;
  2787. }
  2788. if (isError) {
  2789. title = $('<div>' + self.msgValidationError + '</div>').text();
  2790. n = stack.length;
  2791. if (n) {
  2792. cap = n === 1 && stack[0] ? self._getFileNames()[0] : self._getMsgSelected(n);
  2793. } else {
  2794. cap = self._getMsgSelected(self.msgNo);
  2795. }
  2796. out = '<span class="' + self.msgValidationErrorClass + '">' + self.msgValidationErrorIcon +
  2797. ($h.isEmpty(content) ? cap : content) + '</span>';
  2798. } else {
  2799. if ($h.isEmpty(content)) {
  2800. return;
  2801. }
  2802. title = $('<div>' + content + '</div>').text();
  2803. out = self._getLayoutTemplate('fileIcon') + title;
  2804. }
  2805. self.$caption.html(out);
  2806. self.$caption.attr('title', title);
  2807. self.$captionContainer.find('.file-caption-ellipsis').attr('title', title);
  2808. },
  2809. _createContainer: function () {
  2810. var self = this, $container = $(document.createElement("div"))
  2811. .attr({"class": 'file-input file-input-new'})
  2812. .html(self._renderMain());
  2813. self.$element.before($container);
  2814. self._initBrowse($container);
  2815. if (self.theme) {
  2816. $container.addClass('theme-' + self.theme);
  2817. }
  2818. return $container;
  2819. },
  2820. _refreshContainer: function () {
  2821. var self = this, $container = self.$container;
  2822. $container.before(self.$element);
  2823. $container.html(self._renderMain());
  2824. self._initBrowse($container);
  2825. },
  2826. _renderMain: function () {
  2827. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : 'file-drop-disabled',
  2828. close = !self.showClose ? '' : self._getLayoutTemplate('close'),
  2829. preview = !self.showPreview ? '' : self._getLayoutTemplate('preview')
  2830. .replace(/\{class}/g, self.previewClass)
  2831. .replace(/\{dropClass}/g, dropCss),
  2832. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  2833. caption = self.captionTemplate.replace(/\{class}/g, css + ' kv-fileinput-caption');
  2834. return self.mainTemplate.replace(/\{class}/g, self.mainClass +
  2835. (!self.showBrowse && self.showCaption ? ' no-browse' : ''))
  2836. .replace(/\{preview}/g, preview)
  2837. .replace(/\{close}/g, close)
  2838. .replace(/\{caption}/g, caption)
  2839. .replace(/\{upload}/g, self._renderButton('upload'))
  2840. .replace(/\{remove}/g, self._renderButton('remove'))
  2841. .replace(/\{cancel}/g, self._renderButton('cancel'))
  2842. .replace(/\{browse}/g, self._renderButton('browse'));
  2843. },
  2844. _renderButton: function (type) {
  2845. var self = this, tmplt = self._getLayoutTemplate('btnDefault'), css = self[type + 'Class'],
  2846. title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'],
  2847. status = self.isDisabled ? ' disabled' : '', btnType = 'button';
  2848. switch (type) {
  2849. case 'remove':
  2850. if (!self.showRemove) {
  2851. return '';
  2852. }
  2853. break;
  2854. case 'cancel':
  2855. if (!self.showCancel) {
  2856. return '';
  2857. }
  2858. css += ' hide';
  2859. break;
  2860. case 'upload':
  2861. if (!self.showUpload) {
  2862. return '';
  2863. }
  2864. if (self.isUploadable && !self.isDisabled) {
  2865. tmplt = self._getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl);
  2866. } else {
  2867. btnType = 'submit';
  2868. }
  2869. break;
  2870. case 'browse':
  2871. if (!self.showBrowse) {
  2872. return '';
  2873. }
  2874. tmplt = self._getLayoutTemplate('btnBrowse');
  2875. break;
  2876. default:
  2877. return '';
  2878. }
  2879. css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button';
  2880. if (!$h.isEmpty(label)) {
  2881. label = ' <span class="' + self.buttonLabelClass + '">' + label + '</span>';
  2882. }
  2883. return tmplt.replace('{type}', btnType).replace('{css}', css).replace('{title}', title)
  2884. .replace('{status}', status).replace('{icon}', icon).replace('{label}', label);
  2885. },
  2886. _renderThumbProgress: function () {
  2887. var self = this;
  2888. return '<div class="file-thumb-progress hide">' + self.progressTemplate.replace(/\{percent}/g, '0')
  2889. .replace(/\{status}/g, self.msgUploadBegin) + '</div>';
  2890. },
  2891. _renderFileFooter: function (caption, size, width, isError) {
  2892. var self = this, config = self.fileActionSettings, rem = config.showRemove, drg = config.showDrag,
  2893. upl = config.showUpload, zoom = config.showZoom, out, template = self._getLayoutTemplate('footer'),
  2894. indicator = isError ? config.indicatorError : config.indicatorNew,
  2895. title = isError ? config.indicatorErrorTitle : config.indicatorNewTitle;
  2896. size = self._getSize(size);
  2897. if (self.isUploadable) {
  2898. out = template.replace(/\{actions}/g, self._renderFileActions(upl, rem, zoom, drg, false, false, false))
  2899. .replace(/\{caption}/g, caption).replace(/\{size}/g, size).replace(/\{width}/g, width)
  2900. .replace(/\{progress}/g, self._renderThumbProgress()).replace(/\{indicator}/g, indicator)
  2901. .replace(/\{indicatorTitle}/g, title);
  2902. } else {
  2903. out = template.replace(/\{actions}/g,
  2904. self._renderFileActions(false, false, zoom, drg, false, false, false))
  2905. .replace(/\{caption}/g, caption).replace(/\{size}/g, size).replace(/\{width}/g, width)
  2906. .replace(/\{progress}/g, '').replace(/\{indicator}/g, indicator)
  2907. .replace(/\{indicatorTitle}/g, title);
  2908. }
  2909. out = $h.replaceTags(out, self.previewThumbTags);
  2910. return out;
  2911. },
  2912. _renderFileActions: function (showUpload, showDelete, showZoom, showDrag, disabled, url, key, isInit) {
  2913. if (!showUpload && !showDelete && !showZoom && !showDrag) {
  2914. return '';
  2915. }
  2916. var self = this,
  2917. vUrl = url === false ? '' : ' data-url="' + url + '"',
  2918. vKey = key === false ? '' : ' data-key="' + key + '"',
  2919. btnDelete = '', btnUpload = '', btnZoom = '', btnDrag = '', css,
  2920. template = self._getLayoutTemplate('actions'), config = self.fileActionSettings,
  2921. otherButtons = self.otherActionButtons.replace(/\{dataKey}/g, vKey),
  2922. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  2923. if (showDelete) {
  2924. btnDelete = self._getLayoutTemplate('actionDelete')
  2925. .replace(/\{removeClass}/g, removeClass)
  2926. .replace(/\{removeIcon}/g, config.removeIcon)
  2927. .replace(/\{removeTitle}/g, config.removeTitle)
  2928. .replace(/\{dataUrl}/g, vUrl)
  2929. .replace(/\{dataKey}/g, vKey);
  2930. }
  2931. if (showUpload) {
  2932. btnUpload = self._getLayoutTemplate('actionUpload')
  2933. .replace(/\{uploadClass}/g, config.uploadClass)
  2934. .replace(/\{uploadIcon}/g, config.uploadIcon)
  2935. .replace(/\{uploadTitle}/g, config.uploadTitle);
  2936. }
  2937. if (showZoom) {
  2938. btnZoom = self._getLayoutTemplate('actionZoom')
  2939. .replace(/\{zoomClass}/g, config.zoomClass)
  2940. .replace(/\{zoomIcon}/g, config.zoomIcon)
  2941. .replace(/\{zoomTitle}/g, config.zoomTitle);
  2942. }
  2943. if (showDrag && isInit) {
  2944. css = 'drag-handle-init ' + config.dragClass;
  2945. btnDrag = self._getLayoutTemplate('actionDrag').replace(/\{dragClass}/g, css)
  2946. .replace(/\{dragTitle}/g, config.dragTitle)
  2947. .replace(/\{dragIcon}/g, config.dragIcon);
  2948. }
  2949. return template.replace(/\{delete}/g, btnDelete)
  2950. .replace(/\{upload}/g, btnUpload)
  2951. .replace(/\{zoom}/g, btnZoom)
  2952. .replace(/\{drag}/g, btnDrag)
  2953. .replace(/\{other}/g, otherButtons);
  2954. },
  2955. _browse: function (e) {
  2956. var self = this;
  2957. self._raise('filebrowse');
  2958. if (e && e.isDefaultPrevented()) {
  2959. return;
  2960. }
  2961. if (self.isError && !self.isUploadable) {
  2962. self.clear();
  2963. }
  2964. self.$captionContainer.focus();
  2965. },
  2966. _change: function (e) {
  2967. var self = this, $el = self.$element;
  2968. if (!self.isUploadable && $h.isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix
  2969. self.fileInputCleared = false;
  2970. return;
  2971. }
  2972. self.fileInputCleared = false;
  2973. var tfiles, msg, total, isDragDrop = arguments.length > 1, isAjaxUpload = self.isUploadable, i = 0, f, n, len,
  2974. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files, ctr = self.filestack.length,
  2975. isSingleUpload = $h.isEmpty($el.attr('multiple')), flagSingle = (isSingleUpload && ctr > 0), folders = 0,
  2976. throwError = function (mesg, file, previewId, index) {
  2977. var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}),
  2978. p2 = {id: previewId, index: index, file: file, files: files};
  2979. return self.isUploadable ? self._showUploadError(mesg, p1) : self._showError(mesg, p2);
  2980. };
  2981. self.reader = null;
  2982. self._resetUpload();
  2983. self._hideFileIcon();
  2984. if (self.isUploadable) {
  2985. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  2986. }
  2987. if (isDragDrop) {
  2988. tfiles = [];
  2989. while (files[i]) {
  2990. f = files[i];
  2991. if (!f.type && f.size % 4096 === 0) {
  2992. folders++;
  2993. } else {
  2994. tfiles.push(f);
  2995. }
  2996. i++;
  2997. }
  2998. } else {
  2999. if (e.target.files === undefined) {
  3000. tfiles = e.target && e.target.value ? [
  3001. {name: e.target.value.replace(/^.+\\/, '')}
  3002. ] : [];
  3003. } else {
  3004. tfiles = e.target.files;
  3005. }
  3006. }
  3007. if ($h.isEmpty(tfiles) || tfiles.length === 0) {
  3008. if (!isAjaxUpload) {
  3009. self.clear();
  3010. }
  3011. self._showFolderError(folders);
  3012. self._raise('fileselectnone');
  3013. return;
  3014. }
  3015. self._resetErrors();
  3016. len = tfiles.length;
  3017. total = self._getFileCount(self.isUploadable ? (self.getFileStack().length + len) : len);
  3018. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  3019. if (!self.autoReplace || len > self.maxFileCount) {
  3020. n = (self.autoReplace && len > self.maxFileCount) ? len : total;
  3021. msg = self.msgFilesTooMany.replace('{m}', self.maxFileCount).replace('{n}', n);
  3022. self.isError = throwError(msg, null, null, null);
  3023. self.$captionContainer.find('.kv-caption-icon').hide();
  3024. self._setCaption('', true);
  3025. self.$container.removeClass('file-input-new file-input-ajax-new');
  3026. return;
  3027. }
  3028. if (total > self.maxFileCount) {
  3029. self._resetPreviewThumbs(isAjaxUpload);
  3030. }
  3031. } else {
  3032. if (!isAjaxUpload || flagSingle) {
  3033. self._resetPreviewThumbs(false);
  3034. if (flagSingle) {
  3035. self.clearStack();
  3036. }
  3037. } else {
  3038. if (isAjaxUpload && ctr === 0 && (!self.previewCache.count() || self.overwriteInitial)) {
  3039. self._resetPreviewThumbs(true);
  3040. }
  3041. }
  3042. }
  3043. if (self.isPreviewable) {
  3044. self._readFiles(tfiles);
  3045. } else {
  3046. self._updateFileDetails(1);
  3047. }
  3048. self._showFolderError(folders);
  3049. },
  3050. _abort: function (params) {
  3051. var self = this, data;
  3052. if (self.ajaxAborted && typeof self.ajaxAborted === "object" && self.ajaxAborted.message !== undefined) {
  3053. data = $.extend(true, {}, self._getOutData(), params);
  3054. data.abortData = self.ajaxAborted.data || {};
  3055. data.abortMessage = self.ajaxAborted.message;
  3056. self.cancel();
  3057. self._setProgress(101, self.$progress, self.msgCancelled);
  3058. self._showUploadError(self.ajaxAborted.message, data, 'filecustomerror');
  3059. return true;
  3060. }
  3061. return false;
  3062. },
  3063. _resetFileStack: function () {
  3064. var self = this, i = 0, newstack = [], newnames = [];
  3065. self._getThumbs().each(function () {
  3066. var $thumb = $(this), ind = $thumb.attr('data-fileindex'),
  3067. file = self.filestack[ind];
  3068. if (ind === -1) {
  3069. return;
  3070. }
  3071. if (file !== undefined) {
  3072. newstack[i] = file;
  3073. newnames[i] = self._getFileName(file);
  3074. $thumb.attr({'id': self.previewInitId + '-' + i, 'data-fileindex': i});
  3075. i++;
  3076. } else {
  3077. $thumb.attr({'data-fileindex': '-1'});
  3078. }
  3079. });
  3080. self.filestack = newstack;
  3081. self.filenames = newnames;
  3082. },
  3083. clearStack: function () {
  3084. var self = this;
  3085. self.filestack = [];
  3086. self.filenames = [];
  3087. return self.$element;
  3088. },
  3089. updateStack: function (i, file) {
  3090. var self = this;
  3091. self.filestack[i] = file;
  3092. self.filenames[i] = self._getFileName(file);
  3093. return self.$element;
  3094. },
  3095. addToStack: function (file) {
  3096. var self = this;
  3097. self.filestack.push(file);
  3098. self.filenames.push(self._getFileName(file));
  3099. return self.$element;
  3100. },
  3101. getFileStack: function (skipNull) {
  3102. var self = this;
  3103. return self.filestack.filter(function (n) {
  3104. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  3105. });
  3106. },
  3107. getFilesCount: function () {
  3108. var self = this, len = self.isUploadable ? self.getFileStack().length : self.$element.get(0).files.length;
  3109. return self._getFileCount(len);
  3110. },
  3111. lock: function () {
  3112. var self = this;
  3113. self._resetErrors();
  3114. self.disable();
  3115. if (self.showRemove) {
  3116. $h.addCss(self.$container.find('.fileinput-remove'), 'hide');
  3117. }
  3118. if (self.showCancel) {
  3119. self.$container.find('.fileinput-cancel').removeClass('hide');
  3120. }
  3121. self._raise('filelock', [self.filestack, self._getExtraData()]);
  3122. return self.$element;
  3123. },
  3124. unlock: function (reset) {
  3125. var self = this;
  3126. if (reset === undefined) {
  3127. reset = true;
  3128. }
  3129. self.enable();
  3130. if (self.showCancel) {
  3131. $h.addCss(self.$container.find('.fileinput-cancel'), 'hide');
  3132. }
  3133. if (self.showRemove) {
  3134. self.$container.find('.fileinput-remove').removeClass('hide');
  3135. }
  3136. if (reset) {
  3137. self._resetFileStack();
  3138. }
  3139. self._raise('fileunlock', [self.filestack, self._getExtraData()]);
  3140. return self.$element;
  3141. },
  3142. cancel: function () {
  3143. var self = this, xhr = self.ajaxRequests, len = xhr.length, i;
  3144. if (len > 0) {
  3145. for (i = 0; i < len; i += 1) {
  3146. self.cancelling = true;
  3147. xhr[i].abort();
  3148. }
  3149. }
  3150. self._setProgressCancelled();
  3151. self._getThumbs().each(function () {
  3152. var $thumb = $(this), ind = $thumb.attr('data-fileindex');
  3153. $thumb.removeClass('file-uploading');
  3154. if (self.filestack[ind] !== undefined) {
  3155. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  3156. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  3157. }
  3158. self.unlock();
  3159. });
  3160. return self.$element;
  3161. },
  3162. clear: function () {
  3163. var self = this, cap;
  3164. if (!self._raise('fileclear')) {
  3165. return;
  3166. }
  3167. self.$btnUpload.removeAttr('disabled');
  3168. self._getThumbs().find('video,audio,img').each(function () {
  3169. $h.cleanMemory($(this));
  3170. });
  3171. self._resetUpload();
  3172. self.clearStack();
  3173. self._clearFileInput();
  3174. self._resetErrors(true);
  3175. if (self._hasInitialPreview()) {
  3176. self._showFileIcon();
  3177. self._resetPreview();
  3178. self._initPreviewActions();
  3179. self.$container.removeClass('file-input-new');
  3180. } else {
  3181. self._getThumbs().each(function () {
  3182. self._clearObjects($(this));
  3183. });
  3184. if (self.isUploadable) {
  3185. self.previewCache.data = {};
  3186. }
  3187. self.$preview.html('');
  3188. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  3189. self.$caption.html(cap);
  3190. self.$caption.attr('title', '');
  3191. $h.addCss(self.$container, 'file-input-new');
  3192. self._validateDefaultPreview();
  3193. }
  3194. if (self.$container.find($h.FRAMES).length === 0) {
  3195. if (!self._initCaption()) {
  3196. self.$captionContainer.find('.kv-caption-icon').hide();
  3197. }
  3198. }
  3199. self._hideFileIcon();
  3200. self._raise('filecleared');
  3201. self.$captionContainer.focus();
  3202. self._setFileDropZoneTitle();
  3203. return self.$element;
  3204. },
  3205. reset: function () {
  3206. var self = this;
  3207. if (!self._raise('filereset')) {
  3208. return;
  3209. }
  3210. self._resetPreview();
  3211. self.$container.find('.fileinput-filename').text('');
  3212. $h.addCss(self.$container, 'file-input-new');
  3213. if (self.$preview.find($h.FRAMES).length || self.isUploadable && self.dropZoneEnabled) {
  3214. self.$container.removeClass('file-input-new');
  3215. }
  3216. self._setFileDropZoneTitle();
  3217. self.clearStack();
  3218. self.formdata = {};
  3219. return self.$element;
  3220. },
  3221. disable: function () {
  3222. var self = this;
  3223. self.isDisabled = true;
  3224. self._raise('filedisabled');
  3225. self.$element.attr('disabled', 'disabled');
  3226. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  3227. self.$container.find(".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").attr(
  3228. "disabled",
  3229. true);
  3230. self._initDragDrop();
  3231. return self.$element;
  3232. },
  3233. enable: function () {
  3234. var self = this;
  3235. self.isDisabled = false;
  3236. self._raise('fileenabled');
  3237. self.$element.removeAttr('disabled');
  3238. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  3239. self.$container.find(
  3240. ".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").removeAttr("disabled");
  3241. self._initDragDrop();
  3242. return self.$element;
  3243. },
  3244. upload: function () {
  3245. var self = this, totLen = self.getFileStack().length, params = {}, i, outData, len,
  3246. hasExtraData = !$.isEmptyObject(self._getExtraData());
  3247. if (!self.isUploadable || self.isDisabled) {
  3248. return;
  3249. }
  3250. if (self.minFileCount > 0 && self._getFileCount(totLen) < self.minFileCount) {
  3251. self._noFilesError(params);
  3252. return;
  3253. }
  3254. if (totLen === 0 && !hasExtraData) {
  3255. self._resetUpload();
  3256. self._showUploadError(self.msgUploadEmpty);
  3257. return;
  3258. }
  3259. self._resetUpload();
  3260. self.$progress.removeClass('hide');
  3261. self.uploadCount = 0;
  3262. self.uploadStatus = {};
  3263. self.uploadLog = [];
  3264. self.lock();
  3265. self._setProgress(2);
  3266. if (totLen === 0 && hasExtraData) {
  3267. self._uploadExtraOnly();
  3268. return;
  3269. }
  3270. len = self.filestack.length;
  3271. self.hasInitData = false;
  3272. if (self.uploadAsync) {
  3273. outData = self._getOutData();
  3274. self._raise('filebatchpreupload', [outData]);
  3275. self.fileBatchCompleted = false;
  3276. self.uploadCache = {content: [], config: [], tags: [], append: true};
  3277. self.uploadAsyncCount = self.getFileStack().length;
  3278. for (i = 0; i < len; i++) {
  3279. self.uploadCache.content[i] = null;
  3280. self.uploadCache.config[i] = null;
  3281. self.uploadCache.tags[i] = null;
  3282. }
  3283. self.$preview.find('.file-preview-initial').removeClass($h.SORT_CSS);
  3284. self._initSortable();
  3285. self.cacheInitialPreview = self.getPreview();
  3286. for (i = 0; i < len; i++) {
  3287. if (self.filestack[i] !== undefined) {
  3288. self._uploadSingle(i, self.filestack, true);
  3289. }
  3290. }
  3291. return;
  3292. }
  3293. self._uploadBatch();
  3294. return self.$element;
  3295. },
  3296. destroy: function () {
  3297. var self = this, $form = self.$form, $cont = self.$container, $el = self.$element, ns = self.namespace;
  3298. $(document).off(ns);
  3299. $(window).off(ns);
  3300. if ($form && $form.length) {
  3301. $form.off(ns);
  3302. }
  3303. $el.insertBefore($cont).off(ns).removeData();
  3304. $cont.off().remove();
  3305. return $el;
  3306. },
  3307. refresh: function (options) {
  3308. var self = this, $el = self.$element;
  3309. options = options ? $.extend(true, {}, self.options, options) : self.options;
  3310. self.destroy();
  3311. $el.fileinput(options);
  3312. if ($el.val()) {
  3313. $el.trigger('change.fileinput');
  3314. }
  3315. return $el;
  3316. },
  3317. zoom: function (frameId) {
  3318. var self = this, $frame = $('#' + frameId), $modal = self.$modal;
  3319. if (!$frame.length) {
  3320. self._log('Cannot zoom to detailed preview! Invalid frame with id: "' + frameId + '".');
  3321. return;
  3322. }
  3323. $h.initModal($modal);
  3324. $modal.html(self._getModalContent());
  3325. self._setZoomContent($frame);
  3326. $modal.modal('show');
  3327. self._initZoomButtons();
  3328. },
  3329. getPreview: function() {
  3330. var self = this;
  3331. return {
  3332. content: self.initialPreview,
  3333. config: self.initialPreviewConfig,
  3334. tags: self.initialPreviewThumbTags
  3335. };
  3336. }
  3337. };
  3338. $.fn.fileinput = function (option) {
  3339. if (!$h.hasFileAPISupport() && !$h.isIE(9)) {
  3340. return;
  3341. }
  3342. var args = Array.apply(null, arguments), retvals = [];
  3343. args.shift();
  3344. this.each(function () {
  3345. var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option,
  3346. theme = options.theme || self.data('theme'), l = {}, t = {},
  3347. lang = options.language || self.data('language') || $.fn.fileinput.defaults.language || 'en', opt;
  3348. if (!data) {
  3349. if (theme) {
  3350. t = $.fn.fileinputThemes[theme] || {};
  3351. }
  3352. if (lang !== 'en' && !$h.isEmpty($.fn.fileinputLocales[lang])) {
  3353. l = $.fn.fileinputLocales[lang] || {};
  3354. }
  3355. opt = $.extend(true, {}, $.fn.fileinput.defaults, t, $.fn.fileinputLocales.en, l, options, self.data());
  3356. data = new FileInput(this, opt);
  3357. self.data('fileinput', data);
  3358. }
  3359. if (typeof option === 'string') {
  3360. retvals.push(data[option].apply(data, args));
  3361. }
  3362. });
  3363. switch (retvals.length) {
  3364. case 0:
  3365. return this;
  3366. case 1:
  3367. return retvals[0];
  3368. default:
  3369. return retvals;
  3370. }
  3371. };
  3372. $.fn.fileinput.defaults = {
  3373. language: 'en',
  3374. showCaption: true,
  3375. showBrowse: true,
  3376. showPreview: true,
  3377. showRemove: true,
  3378. showUpload: true,
  3379. showCancel: true,
  3380. showClose: true,
  3381. showUploadedThumbs: true,
  3382. browseOnZoneClick: false,
  3383. autoReplace: false,
  3384. previewClass: '',
  3385. captionClass: '',
  3386. frameClass: 'krajee-default',
  3387. mainClass: 'file-caption-main',
  3388. mainTemplate: null,
  3389. purifyHtml: true,
  3390. fileSizeGetter: null,
  3391. initialCaption: '',
  3392. initialPreview: [],
  3393. initialPreviewDelimiter: '*$$*',
  3394. initialPreviewAsData: false,
  3395. initialPreviewFileType: 'image',
  3396. initialPreviewConfig: [],
  3397. initialPreviewThumbTags: [],
  3398. previewThumbTags: {},
  3399. initialPreviewShowDelete: true,
  3400. removeFromPreviewOnError: false,
  3401. deleteUrl: '',
  3402. deleteExtraData: {},
  3403. overwriteInitial: true,
  3404. previewZoomButtonIcons: {
  3405. prev: '<i class="glyphicon glyphicon-triangle-left"></i>',
  3406. next: '<i class="glyphicon glyphicon-triangle-right"></i>',
  3407. toggleheader: '<i class="glyphicon glyphicon-resize-vertical"></i>',
  3408. fullscreen: '<i class="glyphicon glyphicon-fullscreen"></i>',
  3409. borderless: '<i class="glyphicon glyphicon-resize-full"></i>',
  3410. close: '<i class="glyphicon glyphicon-remove"></i>'
  3411. },
  3412. previewZoomButtonClasses: {
  3413. prev: 'btn btn-navigate',
  3414. next: 'btn btn-navigate',
  3415. toggleheader: 'btn btn-default btn-header-toggle',
  3416. fullscreen: 'btn btn-default',
  3417. borderless: 'btn btn-default',
  3418. close: 'btn btn-default'
  3419. },
  3420. preferIconicPreview: false,
  3421. preferIconicZoomPreview: false,
  3422. allowedPreviewTypes: undefined,
  3423. allowedPreviewMimeTypes: null,
  3424. allowedFileTypes: null,
  3425. allowedFileExtensions: null,
  3426. defaultPreviewContent: null,
  3427. customLayoutTags: {},
  3428. customPreviewTags: {},
  3429. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  3430. previewFileIconClass: 'file-other-icon',
  3431. previewFileIconSettings: {},
  3432. previewFileExtSettings: {},
  3433. buttonLabelClass: 'hidden-xs',
  3434. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i>&nbsp;',
  3435. browseClass: 'btn btn-primary',
  3436. removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
  3437. removeClass: 'btn btn-default',
  3438. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i>',
  3439. cancelClass: 'btn btn-default',
  3440. uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
  3441. uploadClass: 'btn btn-default',
  3442. uploadUrl: null,
  3443. uploadAsync: true,
  3444. uploadExtraData: {},
  3445. zoomModalHeight: 480,
  3446. minImageWidth: null,
  3447. minImageHeight: null,
  3448. maxImageWidth: null,
  3449. maxImageHeight: null,
  3450. resizeImage: false,
  3451. resizePreference: 'width',
  3452. resizeQuality: 0.92,
  3453. resizeDefaultImageType: 'image/jpeg',
  3454. minFileSize: 0,
  3455. maxFileSize: 0,
  3456. maxFilePreviewSize: 25600, // 25 MB
  3457. minFileCount: 0,
  3458. maxFileCount: 0,
  3459. validateInitialCount: false,
  3460. msgValidationErrorClass: 'text-danger',
  3461. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  3462. msgErrorClass: 'file-error-message',
  3463. progressThumbClass: "progress-bar progress-bar-success progress-bar-striped active",
  3464. progressClass: "progress-bar progress-bar-success progress-bar-striped active",
  3465. progressCompleteClass: "progress-bar progress-bar-success",
  3466. progressErrorClass: "progress-bar progress-bar-danger",
  3467. progressUploadThreshold: 99,
  3468. previewFileType: 'image',
  3469. elCaptionContainer: null,
  3470. elCaptionText: null,
  3471. elPreviewContainer: null,
  3472. elPreviewImage: null,
  3473. elPreviewStatus: null,
  3474. elErrorContainer: null,
  3475. errorCloseButton: '<span class="close kv-error-close">&times;</span>',
  3476. slugCallback: null,
  3477. dropZoneEnabled: true,
  3478. dropZoneTitleClass: 'file-drop-zone-title',
  3479. fileActionSettings: {},
  3480. otherActionButtons: '',
  3481. textEncoding: 'UTF-8',
  3482. ajaxSettings: {},
  3483. ajaxDeleteSettings: {},
  3484. showAjaxErrorDetails: true
  3485. };
  3486. $.fn.fileinputLocales.en = {
  3487. fileSingle: 'file',
  3488. filePlural: 'files',
  3489. browseLabel: 'Browse &hellip;',
  3490. removeLabel: 'Remove',
  3491. removeTitle: 'Clear selected files',
  3492. cancelLabel: 'Cancel',
  3493. cancelTitle: 'Abort ongoing upload',
  3494. uploadLabel: 'Upload',
  3495. uploadTitle: 'Upload selected files',
  3496. msgNo: 'No',
  3497. msgNoFilesSelected: 'No files selected',
  3498. msgCancelled: 'Cancelled',
  3499. msgZoomModalHeading: 'Detailed Preview',
  3500. msgSizeTooSmall: 'File "{name}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.',
  3501. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
  3502. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
  3503. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
  3504. msgFileNotFound: 'File "{name}" not found!',
  3505. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  3506. msgFileNotReadable: 'File "{name}" is not readable.',
  3507. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  3508. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  3509. msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".',
  3510. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  3511. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  3512. msgFileTypes: {
  3513. 'image': 'image',
  3514. 'html': 'HTML',
  3515. 'text': 'text',
  3516. 'video': 'video',
  3517. 'audio': 'audio',
  3518. 'flash': 'flash',
  3519. 'pdf': 'PDF',
  3520. 'object': 'object'
  3521. },
  3522. msgUploadAborted: 'The file upload was aborted',
  3523. msgUploadThreshold: 'Processing...',
  3524. msgUploadBegin: 'Initializing...',
  3525. msgUploadEnd: 'Done',
  3526. msgUploadEmpty: 'No valid data available for upload.',
  3527. msgValidationError: 'Validation Error',
  3528. msgLoading: 'Loading file {index} of {files} &hellip;',
  3529. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  3530. msgSelected: '{n} {files} selected',
  3531. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  3532. msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
  3533. msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
  3534. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
  3535. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
  3536. msgImageResizeError: 'Could not get the image dimensions to resize.',
  3537. msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>',
  3538. msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!',
  3539. msgAjaxProgressError: '{operation} failed',
  3540. ajaxOperations: {
  3541. deleteThumb: 'file delete',
  3542. uploadThumb: 'file upload',
  3543. uploadBatch: 'batch file upload',
  3544. uploadExtra: 'form data upload'
  3545. },
  3546. dropZoneTitle: 'Drag & drop files here &hellip;',
  3547. dropZoneClickTitle: '<br>(or click to select {files})',
  3548. previewZoomButtonTitles: {
  3549. prev: 'View previous file',
  3550. next: 'View next file',
  3551. toggleheader: 'Toggle header',
  3552. fullscreen: 'Toggle full screen',
  3553. borderless: 'Toggle borderless mode',
  3554. close: 'Close detailed preview'
  3555. }
  3556. };
  3557. $.fn.fileinput.Constructor = FileInput;
  3558. /**
  3559. * Convert automatically file inputs with class 'file' into a bootstrap fileinput control.
  3560. */
  3561. $(document).ready(function () {
  3562. var $input = $('input.file[type=file]');
  3563. if ($input.length) {
  3564. $input.fileinput();
  3565. }
  3566. });
  3567. }));