fileinput.js 174 KB

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