fileinput.js 168 KB

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