fileinput.js 157 KB

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