fileinput.js 168 KB

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