fileinput.js 174 KB

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