fileinput.js 149 KB

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