fileinput.js 164 KB

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