fileinput.js 170 KB

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