fileinput.js 156 KB

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