fileinput.js 145 KB

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