fileinput.js 161 KB

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