fileinput.js 151 KB

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