fileinput.js 146 KB

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