fileinput.js 154 KB

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