fileinput.js 124 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722
  1. /*!
  2. * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2015
  3. * @version 4.3.0
  4. *
  5. * File input styled for Bootstrap 3.0 that utilizes HTML5 File Input's advanced features including the FileReader API.
  6. *
  7. * The plugin drastically enhances the HTML file input to preview multiple files on the client before upload. In
  8. * addition it provides the ability to preview content of images, text, videos, audio, html, flash and other objects.
  9. * It also offers the ability to upload and delete files using AJAX, and add files in batches (i.e. preview, append,
  10. * or remove before upload).
  11. *
  12. * Author: Kartik Visweswaran
  13. * Copyright: 2015, Kartik Visweswaran, Krajee.com
  14. * For more JQuery plugins visit http://plugins.krajee.com
  15. * For more Yii related demos visit http://demos.krajee.com
  16. */
  17. (function (factory) {
  18. "use strict";
  19. if (typeof define === 'function' && define.amd) { // jshint ignore:line
  20. // AMD. Register as an anonymous module.
  21. define(['jquery'], factory); // jshint ignore:line
  22. } else { // noinspection JSUnresolvedVariable
  23. if (typeof module === 'object' && module.exports) { // jshint ignore:line
  24. // Node/CommonJS
  25. // noinspection JSUnresolvedVariable
  26. module.exports = factory(require('jquery')); // jshint ignore:line
  27. } else {
  28. // Browser globals
  29. factory(window.jQuery);
  30. }
  31. }
  32. }(function ($) {
  33. "use strict";
  34. $.fn.fileinputLocales = {};
  35. var isIE, isEdge, handler, previewCache, getNum, hasFileAPISupport, hasDragDropSupport, hasFileUploadSupport, addCss,
  36. STYLE_SETTING, OBJECT_PARAMS, DEFAULT_PREVIEW, defaultFileActionSettings, tMain1, tMain2, tPreview, tIcon, tClose,
  37. tCaption, tBtnDefault, tBtnLink, tBtnBrowse, tModal, tProgress, tFooter, tActions, tActionDelete, tActionUpload,
  38. tZoom, tGeneric, tHtml, tImage, tText, tVideo, tAudio, tFlash, tObject, tOther, defaultLayoutTemplates,
  39. defaultPreviewTemplates, defaultPreviewTypes, defaultPreviewSettings, defaultFileTypeSettings, isEmpty, isArray,
  40. isSet, getElement, uniqId, htmlEncode, replaceTags, objUrl, FileInput, NAMESPACE;
  41. NAMESPACE = '.fileinput';
  42. isIE = function (ver) {
  43. // check for IE versions < 11
  44. if (navigator.appName !== 'Microsoft Internet Explorer') {
  45. return false;
  46. }
  47. if (ver === 10) {
  48. return new RegExp('msie\\s' + ver, 'i').test(navigator.userAgent);
  49. }
  50. var div = document.createElement("div"), status;
  51. div.innerHTML = "<!--[if IE " + ver + "]> <i></i> <![endif]-->";
  52. status = div.getElementsByTagName("i").length;
  53. document.body.appendChild(div);
  54. div.parentNode.removeChild(div);
  55. return status;
  56. };
  57. isEdge = function () {
  58. return new RegExp('Edge\/[0-9]+', 'i').test(navigator.userAgent);
  59. };
  60. handler = function ($el, event, callback, skipNS) {
  61. var ev = skipNS ? event : event.split(' ').join(NAMESPACE + ' ') + NAMESPACE;
  62. $el.off(ev).on(ev, callback);
  63. };
  64. previewCache = {
  65. data: {},
  66. init: function (obj) {
  67. var content = obj.initialPreview, id = obj.id;
  68. if (content.length > 0 && !isArray(content)) {
  69. content = content.split(obj.initialPreviewDelimiter);
  70. }
  71. previewCache.data[id] = {
  72. content: content,
  73. config: obj.initialPreviewConfig,
  74. tags: obj.initialPreviewThumbTags,
  75. delimiter: obj.initialPreviewDelimiter,
  76. template: obj.previewGenericTemplate,
  77. msg: function (n) {
  78. return obj.getMsgSelected(n);
  79. },
  80. initId: obj.previewInitId,
  81. footer: obj.getLayoutTemplate('footer').replace(/\{progress}/g, obj.renderThumbProgress()),
  82. isDelete: obj.initialPreviewShowDelete,
  83. caption: obj.initialCaption,
  84. actions: function (showUpload, showDelete, disabled, url, key) {
  85. return obj.renderFileActions(showUpload, showDelete, disabled, url, key);
  86. }
  87. };
  88. },
  89. fetch: function (id) {
  90. return previewCache.data[id].content.filter(function (n) {
  91. return n !== null;
  92. });
  93. },
  94. count: function (id, all) {
  95. return !!previewCache.data[id] && !!previewCache.data[id].content ?
  96. (all ? previewCache.data[id].content.length : previewCache.fetch(id).length) : 0;
  97. },
  98. get: function (id, i, isDisabled) {
  99. var ind = 'init_' + i, data = previewCache.data[id], config = data.config[i],
  100. previewId = data.initId + '-' + ind, out, $tmp, frameClass = ' file-preview-initial';
  101. /** @namespace config.frameClass */
  102. /** @namespace config.frameAttr */
  103. isDisabled = isDisabled === undefined ? true : isDisabled;
  104. if (data.content[i] === null) {
  105. return '';
  106. }
  107. if (!isEmpty(config) && !isEmpty(config.frameClass)) {
  108. frameClass += ' ' + config.frameClass;
  109. }
  110. out = data.template
  111. .replace(/\{previewId}/g, previewId)
  112. .replace(/\{frameClass}/g, frameClass)
  113. .replace(/\{fileindex}/g, ind)
  114. .replace(/\{content}/g, data.content[i])
  115. .replace(/\{footer}/g, previewCache.footer(id, i, isDisabled));
  116. if (data.tags.length && data.tags[i]) {
  117. out = replaceTags(out, data.tags[i]);
  118. }
  119. if (!isEmpty(config) && !isEmpty(config.frameAttr)) {
  120. $tmp = $(document.createElement('div')).html(out);
  121. $tmp.find('.file-preview-initial').attr(config.frameAttr);
  122. out = $tmp.html();
  123. $tmp.remove();
  124. }
  125. return out;
  126. },
  127. add: function (id, content, config, tags, append) {
  128. var data = $.extend(true, {}, previewCache.data[id]), index;
  129. if (!isArray(content)) {
  130. content = content.split(data.delimiter);
  131. }
  132. if (append) {
  133. index = data.content.push(content) - 1;
  134. data.config[index] = config;
  135. data.tags[index] = tags;
  136. } else {
  137. index = content.length;
  138. data.content = content;
  139. data.config = config;
  140. data.tags = tags;
  141. }
  142. previewCache.data[id] = data;
  143. return index;
  144. },
  145. set: function (id, content, config, tags, append) {
  146. var data = $.extend(true, {}, previewCache.data[id]), i, chk;
  147. if (!content || !content.length) {
  148. return;
  149. }
  150. if (!isArray(content)) {
  151. content = content.split(data.delimiter);
  152. }
  153. chk = content.filter(function (n) {
  154. return n !== null;
  155. });
  156. if (!chk.length) {
  157. return;
  158. }
  159. if (data.content === undefined) {
  160. data.content = [];
  161. }
  162. if (data.config === undefined) {
  163. data.config = [];
  164. }
  165. if (data.tags === undefined) {
  166. data.tags = [];
  167. }
  168. if (append) {
  169. for (i = 0; i < content.length; i++) {
  170. if (content[i]) {
  171. data.content.push(content[i]);
  172. }
  173. }
  174. for (i = 0; i < config.length; i++) {
  175. if (config[i]) {
  176. data.config.push(config[i]);
  177. }
  178. }
  179. for (i = 0; i < tags.length; i++) {
  180. if (tags[i]) {
  181. data.tags.push(tags[i]);
  182. }
  183. }
  184. } else {
  185. data.content = content;
  186. data.config = config;
  187. data.tags = tags;
  188. }
  189. previewCache.data[id] = data;
  190. },
  191. unset: function (id, index) {
  192. var chk = previewCache.count(id);
  193. if (!chk) {
  194. return;
  195. }
  196. if (chk === 1) {
  197. previewCache.data[id].content = [];
  198. previewCache.data[id].config = [];
  199. return;
  200. }
  201. previewCache.data[id].content[index] = null;
  202. previewCache.data[id].config[index] = null;
  203. },
  204. out: function (id) {
  205. var html = '', data = previewCache.data[id], caption, len = previewCache.count(id, true);
  206. if (len === 0) {
  207. return {content: '', caption: ''};
  208. }
  209. for (var i = 0; i < len; i++) {
  210. html += previewCache.get(id, i);
  211. }
  212. caption = data.msg(previewCache.count(id));
  213. return {content: html, caption: caption};
  214. },
  215. footer: function (id, i, isDisabled) {
  216. var data = previewCache.data[id];
  217. isDisabled = isDisabled === undefined ? true : isDisabled;
  218. if (data.config.length === 0 || isEmpty(data.config[i])) {
  219. return '';
  220. }
  221. var config = data.config[i],
  222. caption = isSet('caption', config) ? config.caption : '',
  223. width = isSet('width', config) ? config.width : 'auto',
  224. url = isSet('url', config) ? config.url : false,
  225. key = isSet('key', config) ? config.key : null,
  226. disabled = (url === false) && isDisabled,
  227. actions = data.isDelete ? data.actions(false, true, disabled, url, key) : '',
  228. footer = data.footer.replace(/\{actions}/g, actions);
  229. return footer.replace(/\{caption}/g, caption)
  230. .replace(/\{width}/g, width)
  231. .replace(/\{indicator}/g, '')
  232. .replace(/\{indicatorTitle}/g, '');
  233. }
  234. };
  235. getNum = function (num, def) {
  236. def = def || 0;
  237. if (typeof num === "number") {
  238. return num;
  239. }
  240. if (typeof num === "string") {
  241. num = parseFloat(num);
  242. }
  243. return isNaN(num) ? def : num;
  244. };
  245. hasFileAPISupport = function () {
  246. return !!(window.File && window.FileReader);
  247. };
  248. hasDragDropSupport = function () {
  249. var div = document.createElement('div');
  250. /** @namespace div.draggable */
  251. /** @namespace div.ondragstart */
  252. /** @namespace div.ondrop */
  253. return !isIE(9) && !isEdge() && // Fix for MS Edge drag & drop support bug
  254. (div.draggable !== undefined || (div.ondragstart !== undefined && div.ondrop !== undefined));
  255. };
  256. hasFileUploadSupport = function () {
  257. return hasFileAPISupport() && window.FormData;
  258. };
  259. addCss = function ($el, css) {
  260. $el.removeClass(css).addClass(css);
  261. };
  262. STYLE_SETTING = 'style="width:{width};height:{height};"';
  263. OBJECT_PARAMS = ' <param name="controller" value="true" />\n' +
  264. ' <param name="allowFullScreen" value="true" />\n' +
  265. ' <param name="allowScriptAccess" value="always" />\n' +
  266. ' <param name="autoPlay" value="false" />\n' +
  267. ' <param name="autoStart" value="false" />\n' +
  268. ' <param name="quality" value="high" />\n';
  269. DEFAULT_PREVIEW = '<div class="file-preview-other">\n' +
  270. ' <span class="{previewFileIconClass}">{previewFileIcon}</span>\n' +
  271. '</div>';
  272. defaultFileActionSettings = {
  273. removeIcon: '<i class="glyphicon glyphicon-trash text-danger"></i>',
  274. removeClass: 'btn btn-xs btn-default',
  275. removeTitle: 'Remove file',
  276. uploadIcon: '<i class="glyphicon glyphicon-upload text-info"></i>',
  277. uploadClass: 'btn btn-xs btn-default',
  278. uploadTitle: 'Upload file',
  279. indicatorNew: '<i class="glyphicon glyphicon-hand-down text-warning"></i>',
  280. indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign text-success"></i>',
  281. indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>',
  282. indicatorLoading: '<i class="glyphicon glyphicon-hand-up text-muted"></i>',
  283. indicatorNewTitle: 'Not uploaded yet',
  284. indicatorSuccessTitle: 'Uploaded',
  285. indicatorErrorTitle: 'Upload Error',
  286. indicatorLoadingTitle: 'Uploading ...'
  287. };
  288. tMain1 = '{preview}\n' +
  289. '<div class="kv-upload-progress hide"></div>\n' +
  290. '<div class="input-group {class}">\n' +
  291. ' {caption}\n' +
  292. ' <div class="input-group-btn">\n' +
  293. ' {remove}\n' +
  294. ' {cancel}\n' +
  295. ' {upload}\n' +
  296. ' {browse}\n' +
  297. ' </div>\n' +
  298. '</div>';
  299. tMain2 = '{preview}\n<div class="kv-upload-progress hide"></div>\n{remove}\n{cancel}\n{upload}\n{browse}\n';
  300. tPreview = '<div class="file-preview {class}">\n' +
  301. ' {close}' +
  302. ' <div class="{dropClass}">\n' +
  303. ' <div class="file-preview-thumbnails">\n' +
  304. ' </div>\n' +
  305. ' <div class="clearfix"></div>' +
  306. ' <div class="file-preview-status text-center text-success"></div>\n' +
  307. ' <div class="kv-fileinput-error"></div>\n' +
  308. ' </div>\n' +
  309. '</div>';
  310. tClose = '<div class="close fileinput-remove">&times;</div>\n';
  311. tIcon = '<span class="glyphicon glyphicon-file kv-caption-icon"></span>';
  312. tCaption = '<div tabindex="500" class="form-control file-caption {class}">\n' +
  313. ' <div class="file-caption-name"></div>\n' +
  314. '</div>\n';
  315. //noinspection HtmlUnknownAttribute
  316. tBtnDefault = '<button type="{type}" tabindex="500" title="{title}" class="{css}" {status}>{icon}{label}</button>';
  317. tBtnLink = '<a href="{href}" tabindex="500" title="{title}" class="{css}" {status}>{icon}{label}</a>';
  318. tBtnBrowse = '<div tabindex="500" class="{css}" {status}>{icon}{label}</div>';
  319. tModal = '<div id="{id}" class="file-preview-detail-modal modal fade" tabindex="-1">\n' +
  320. ' <div class="modal-dialog modal-lg">\n' +
  321. ' <div class="modal-content">\n' +
  322. ' <div class="modal-header">\n' +
  323. ' <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>\n' +
  324. ' <h3 class="modal-title">{heading} <small>{title}</small></h3>\n' +
  325. ' </div>\n' +
  326. ' <div class="modal-body">\n' +
  327. ' <pre>{body}</pre>\n' +
  328. ' </div>\n' +
  329. ' </div>\n' +
  330. ' </div>\n' +
  331. '</div>';
  332. tProgress = '<div class="progress">\n' +
  333. ' <div class="{class}" role="progressbar"' +
  334. ' aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' +
  335. ' {percent}%\n' +
  336. ' </div>\n' +
  337. '</div>';
  338. tFooter = '<div class="file-thumbnail-footer">\n' +
  339. ' <div class="file-footer-caption" title="{caption}">{caption}</div>\n' +
  340. ' {progress} {actions}\n' +
  341. '</div>';
  342. tActions = '<div class="file-actions">\n' +
  343. ' <div class="file-footer-buttons">\n' +
  344. ' {upload}{delete}{other}' +
  345. ' </div>\n' +
  346. ' <div class="file-upload-indicator" title="{indicatorTitle}">{indicator}</div>\n' +
  347. ' <div class="clearfix"></div>\n' +
  348. '</div>';
  349. tActionDelete = '<button type="button" class="kv-file-remove {removeClass}" ' +
  350. 'title="{removeTitle}" {dataUrl}{dataKey}>{removeIcon}</button>\n';
  351. tActionUpload = '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">' +
  352. ' {uploadIcon}\n</button>\n';
  353. tZoom = '<button type="button" class="btn btn-default btn-xs btn-block" title="{zoomTitle}: {caption}" onclick="{dialog}">\n' +
  354. ' {zoomInd}\n' +
  355. '</button>\n';
  356. tGeneric = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  357. ' {content}\n' +
  358. ' {footer}\n' +
  359. '</div>\n';
  360. tHtml = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  361. ' <object class="file-object" data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  362. ' ' + DEFAULT_PREVIEW + '\n' +
  363. ' </object>\n' +
  364. ' {footer}\n' +
  365. '</div>';
  366. tImage = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  367. ' <img src="{data}" class="file-preview-image" title="{caption}" alt="{caption}" ' + STYLE_SETTING + '>\n' +
  368. ' {footer}\n' +
  369. '</div>\n';
  370. tText = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  371. ' <pre class="file-preview-text" title="{caption}" ' + STYLE_SETTING + '>{data}</pre>\n' +
  372. ' {zoom}\n' +
  373. ' {footer}\n' +
  374. '</div>';
  375. tVideo = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  376. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  377. ' <video width="{width}" height="{height}" controls>\n' +
  378. ' <source src="{data}" type="{type}">\n' +
  379. ' ' + DEFAULT_PREVIEW + '\n' +
  380. ' </video>\n' +
  381. ' {footer}\n' +
  382. '</div>\n';
  383. tAudio = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  384. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  385. ' <audio controls>\n' +
  386. ' <source src="' + '{data}' + '" type="{type}">\n' +
  387. ' ' + DEFAULT_PREVIEW + '\n' +
  388. ' </audio>\n' +
  389. ' {footer}\n' +
  390. '</div>';
  391. tFlash = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  392. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  393. ' <object class="file-object" type="application/x-shockwave-flash" width="{width}" height="{height}" data="{data}">\n' +
  394. OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' +
  395. ' </object>\n' +
  396. ' {footer}\n' +
  397. '</div>\n';
  398. tObject = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  399. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  400. ' <object class="file-object" data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  401. ' <param name="movie" value="{caption}" />\n' +
  402. OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' +
  403. ' </object>\n' +
  404. ' {footer}\n' +
  405. '</div>';
  406. tOther = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  407. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  408. ' <div class="file-preview-other-frame">\n' +
  409. ' ' + DEFAULT_PREVIEW + '\n' +
  410. ' </div>\n' +
  411. ' <div class="file-preview-other-footer">{footer}</div>\n' +
  412. '</div>';
  413. defaultLayoutTemplates = {
  414. main1: tMain1,
  415. main2: tMain2,
  416. preview: tPreview,
  417. close: tClose,
  418. zoom: tZoom,
  419. icon: tIcon,
  420. caption: tCaption,
  421. modal: tModal,
  422. progress: tProgress,
  423. footer: tFooter,
  424. actions: tActions,
  425. actionDelete: tActionDelete,
  426. actionUpload: tActionUpload,
  427. btnDefault: tBtnDefault,
  428. btnLink: tBtnLink,
  429. btnBrowse: tBtnBrowse
  430. };
  431. defaultPreviewTemplates = {
  432. generic: tGeneric,
  433. html: tHtml,
  434. image: tImage,
  435. text: tText,
  436. video: tVideo,
  437. audio: tAudio,
  438. flash: tFlash,
  439. object: tObject,
  440. other: tOther
  441. };
  442. defaultPreviewTypes = ['image', 'html', 'text', 'video', 'audio', 'flash', 'object'];
  443. defaultPreviewSettings = {
  444. image: {width: "auto", height: "160px"},
  445. html: {width: "213px", height: "160px"},
  446. text: {width: "160px", height: "136px"},
  447. video: {width: "213px", height: "160px"},
  448. audio: {width: "213px", height: "80px"},
  449. flash: {width: "213px", height: "160px"},
  450. object: {width: "160px", height: "160px"},
  451. other: {width: "160px", height: "160px"}
  452. };
  453. defaultFileTypeSettings = {
  454. image: function (vType, vName) {
  455. return (vType !== undefined) ? vType.match('image.*') : vName.match(/\.(gif|png|jpe?g)$/i);
  456. },
  457. html: function (vType, vName) {
  458. return (vType !== undefined) ? vType === 'text/html' : vName.match(/\.(htm|html)$/i);
  459. },
  460. text: function (vType, vName) {
  461. return (vType !== undefined && vType.match('text.*')) || vName.match(
  462. /\.(txt|md|csv|nfo|ini|json|php|js|css)$/i);
  463. },
  464. video: function (vType, vName) {
  465. return (vType !== undefined && vType.match(/\.video\/(ogg|mp4|webm|3gp)$/i)) || vName.match(
  466. /\.(og?|mp4|webm|3gp)$/i);
  467. },
  468. audio: function (vType, vName) {
  469. return (vType !== undefined && vType.match(/\.audio\/(ogg|mp3|wav)$/i)) || vName.match(/\.(ogg|mp3|wav)$/i);
  470. },
  471. flash: function (vType, vName) {
  472. return (vType !== undefined && vType === 'application/x-shockwave-flash') || vName.match(/\.(swf)$/i);
  473. },
  474. object: function () {
  475. return true;
  476. },
  477. other: function () {
  478. return true;
  479. }
  480. };
  481. isEmpty = function (value, trim) {
  482. return value === undefined || value === null || value.length === 0 || (trim && $.trim(value) === '');
  483. };
  484. isArray = function (a) {
  485. return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]';
  486. };
  487. isSet = function (needle, haystack) {
  488. return (typeof haystack === 'object' && needle in haystack);
  489. };
  490. getElement = function (options, param, value) {
  491. return (isEmpty(options) || isEmpty(options[param])) ? value : $(options[param]);
  492. };
  493. uniqId = function () {
  494. return Math.round(new Date().getTime() + (Math.random() * 100));
  495. };
  496. htmlEncode = function (str) {
  497. return str.replace(/&/g, '&amp;')
  498. .replace(/</g, '&lt;')
  499. .replace(/>/g, '&gt;')
  500. .replace(/"/g, '&quot;')
  501. .replace(/'/g, '&apos;');
  502. };
  503. replaceTags = function (str, tags) {
  504. var out = str;
  505. if (!tags) {
  506. return out;
  507. }
  508. $.each(tags, function (key, value) {
  509. if (typeof value === "function") {
  510. value = value();
  511. }
  512. out = out.split(key).join(value);
  513. });
  514. return out;
  515. };
  516. //noinspection JSUnresolvedVariable
  517. objUrl = window.URL || window.webkitURL;
  518. FileInput = function (element, options) {
  519. var self = this;
  520. self.$element = $(element);
  521. if (!self.validate()) {
  522. return;
  523. }
  524. self.isPreviewable = hasFileAPISupport();
  525. self.isIE9 = isIE(9);
  526. self.isIE10 = isIE(10);
  527. if (self.isPreviewable || self.isIE9) {
  528. self.init(options);
  529. self.listen();
  530. } else {
  531. self.$element.removeClass('file-loading');
  532. }
  533. };
  534. FileInput.prototype = {
  535. constructor: FileInput,
  536. validate: function () {
  537. var self = this, $exception;
  538. if (self.$element.attr('type') === 'file') {
  539. return true;
  540. }
  541. $exception = '<div class="help-block alert alert-warning">' +
  542. '<h4>Invalid Input Type</h4>' +
  543. 'You must set an input <code>type = file</code> for <b>bootstrap-fileinput</b> plugin to initialize.' +
  544. '</div>';
  545. self.$element.after($exception);
  546. return false;
  547. },
  548. init: function (options) {
  549. var self = this, $el = self.$element, t;
  550. $.each(options, function (key, value) {
  551. switch (key) {
  552. case 'minFileCount':
  553. case 'maxFileCount':
  554. case 'maxFileSize':
  555. self[key] = getNum(value);
  556. break;
  557. default:
  558. self[key] = value;
  559. break;
  560. }
  561. });
  562. self.fileInputCleared = false;
  563. self.fileBatchCompleted = true;
  564. if (!self.isPreviewable) {
  565. self.showPreview = false;
  566. }
  567. self.uploadFileAttr = !isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data';
  568. self.reader = null;
  569. self.formdata = {};
  570. self.clearStack();
  571. self.uploadCount = 0;
  572. self.uploadStatus = {};
  573. self.uploadLog = [];
  574. self.uploadAsyncCount = 0;
  575. self.loadedImages = [];
  576. self.totalImagesCount = 0;
  577. self.ajaxRequests = [];
  578. self.isError = false;
  579. self.ajaxAborted = false;
  580. self.cancelling = false;
  581. t = self.getLayoutTemplate('progress');
  582. self.progressTemplate = t.replace('{class}', self.progressClass);
  583. self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass);
  584. self.dropZoneEnabled = hasDragDropSupport() && self.dropZoneEnabled;
  585. self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly');
  586. self.isUploadable = hasFileUploadSupport() && !isEmpty(self.uploadUrl);
  587. self.slug = typeof options.slugCallback === "function" ? options.slugCallback : self.slugDefault;
  588. self.mainTemplate = self.showCaption ? self.getLayoutTemplate('main1') : self.getLayoutTemplate('main2');
  589. self.captionTemplate = self.getLayoutTemplate('caption');
  590. self.previewGenericTemplate = self.getPreviewTemplate('generic');
  591. if (self.resizeImage && (self.maxImageWidth || self.maxImageHeight)) {
  592. self.imageCanvas = document.createElement('canvas');
  593. self.imageCanvasContext = self.imageCanvas.getContext('2d');
  594. }
  595. if (isEmpty(self.$element.attr('id'))) {
  596. self.$element.attr('id', uniqId());
  597. }
  598. if (self.$container === undefined) {
  599. self.$container = self.createContainer();
  600. } else {
  601. self.refreshContainer();
  602. }
  603. self.$dropZone = self.$container.find('.file-drop-zone');
  604. self.$progress = self.$container.find('.kv-upload-progress');
  605. self.$btnUpload = self.$container.find('.fileinput-upload');
  606. self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption'));
  607. self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name'));
  608. self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview'));
  609. self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails'));
  610. self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status'));
  611. self.$errorContainer = getElement(options, 'elErrorContainer',
  612. self.$previewContainer.find('.kv-fileinput-error'));
  613. if (!isEmpty(self.msgErrorClass)) {
  614. addCss(self.$errorContainer, self.msgErrorClass);
  615. }
  616. self.$errorContainer.hide();
  617. self.fileActionSettings = $.extend(true, defaultFileActionSettings, options.fileActionSettings);
  618. self.previewInitId = "preview-" + uniqId();
  619. self.id = self.$element.attr('id');
  620. previewCache.init(self);
  621. self.initPreview(true);
  622. self.initPreviewDeletes();
  623. self.options = options;
  624. self.setFileDropZoneTitle();
  625. self.$element.removeClass('file-loading');
  626. if (self.$element.attr('disabled')) {
  627. self.disable();
  628. }
  629. },
  630. parseError: function (jqXHR, errorThrown, fileName) {
  631. /** @namespace jqXHR.responseJSON */
  632. var self = this, errMsg = $.trim(errorThrown + ''),
  633. dot = errMsg.slice(-1) === '.' ? '' : '.',
  634. text = jqXHR.responseJSON !== undefined && jqXHR.responseJSON.error !== undefined ?
  635. jqXHR.responseJSON.error : jqXHR.responseText;
  636. if (self.cancelling && self.msgUploadAborted) {
  637. errMsg = self.msgUploadAborted;
  638. }
  639. if (self.showAjaxErrorDetails && text) {
  640. text = $.trim(text.replace(/\n\s*\n/g, '\n'));
  641. text = text.length > 0 ? '<pre>' + text + '</pre>' : '';
  642. errMsg += dot + text;
  643. } else {
  644. errMsg += dot;
  645. }
  646. self.cancelling = false;
  647. return fileName ? '<b>' + fileName + ': </b>' + errMsg : errMsg;
  648. },
  649. raise: function (event, params) {
  650. var self = this, e = $.Event(event);
  651. if (params !== undefined) {
  652. self.$element.trigger(e, params);
  653. } else {
  654. self.$element.trigger(e);
  655. }
  656. if (e.isDefaultPrevented()) {
  657. return false;
  658. }
  659. if (!e.result) {
  660. return e.result;
  661. }
  662. switch (event) {
  663. // ignore these events
  664. case 'filebatchuploadcomplete':
  665. case 'filebatchuploadsuccess':
  666. case 'fileuploaded':
  667. case 'fileclear':
  668. case 'filecleared':
  669. case 'filereset':
  670. case 'fileerror':
  671. case 'filefoldererror':
  672. case 'fileuploaderror':
  673. case 'filebatchuploaderror':
  674. case 'filedeleteerror':
  675. case 'filecustomerror':
  676. case 'filesuccessremove':
  677. break;
  678. // receive data response via `filecustomerror` event`
  679. default:
  680. self.ajaxAborted = e.result;
  681. break;
  682. }
  683. return true;
  684. },
  685. getLayoutTemplate: function (t) {
  686. var self = this,
  687. template = isSet(t, self.layoutTemplates) ? self.layoutTemplates[t] : defaultLayoutTemplates[t];
  688. if (isEmpty(self.customLayoutTags)) {
  689. return template;
  690. }
  691. return replaceTags(template, self.customLayoutTags);
  692. },
  693. getPreviewTemplate: function (t) {
  694. var self = this,
  695. template = isSet(t, self.previewTemplates) ? self.previewTemplates[t] : defaultPreviewTemplates[t];
  696. if (isEmpty(self.customPreviewTags)) {
  697. return template;
  698. }
  699. return replaceTags(template, self.customPreviewTags);
  700. },
  701. parseFilePreviewIcon: function (content, fname) {
  702. var self = this, ext, icn = self.previewFileIcon;
  703. if (fname && fname.indexOf('.') > -1) {
  704. ext = fname.split('.').pop();
  705. if (self.previewFileIconSettings && self.previewFileIconSettings[ext]) {
  706. icn = self.previewFileIconSettings[ext];
  707. }
  708. if (self.previewFileExtSettings) {
  709. $.each(self.previewFileExtSettings, function (key, func) {
  710. if (self.previewFileIconSettings[key] && func(ext)) {
  711. icn = self.previewFileIconSettings[key];
  712. }
  713. });
  714. }
  715. }
  716. if (content.indexOf('{previewFileIcon}') > -1) {
  717. return content.replace(/\{previewFileIconClass}/g, self.previewFileIconClass).replace(
  718. /\{previewFileIcon}/g, icn);
  719. }
  720. return content;
  721. },
  722. getOutData: function (jqXHR, responseData, filesData) {
  723. var self = this;
  724. jqXHR = jqXHR || {};
  725. responseData = responseData || {};
  726. filesData = filesData || self.filestack.slice(0) || {};
  727. return {
  728. form: self.formdata,
  729. files: filesData,
  730. filenames: self.filenames,
  731. extra: self.getExtraData(),
  732. response: responseData,
  733. reader: self.reader,
  734. jqXHR: jqXHR
  735. };
  736. },
  737. listen: function () {
  738. var self = this, $el = self.$element, $form = $el.closest('form'), $cont = self.$container;
  739. handler($el, 'change', $.proxy(self.change, self));
  740. handler(self.$btnFile, 'click', $.proxy(self.browse, self));
  741. handler($form, 'reset', $.proxy(self.reset, self));
  742. handler($cont.find('.fileinput-remove:not([disabled])'), 'click', $.proxy(self.clear, self));
  743. handler($cont.find('.fileinput-cancel'), 'click', $.proxy(self.cancel, self));
  744. self.initDragDrop();
  745. if (!self.isUploadable) {
  746. handler($form, 'submit', $.proxy(self.submitForm, self));
  747. }
  748. handler(self.$container.find('.fileinput-upload'), 'click', $.proxy(self.uploadClick, self));
  749. },
  750. zoneDragDropInit: function (e) {
  751. e.stopPropagation();
  752. e.preventDefault();
  753. },
  754. zoneDragEnter: function (e) {
  755. var self = this, hasFiles = $.inArray('Files', e.originalEvent.dataTransfer.types) > -1;
  756. self.zoneDragDropInit(e);
  757. if (self.isDisabled || !hasFiles) {
  758. e.originalEvent.dataTransfer.effectAllowed = 'none';
  759. e.originalEvent.dataTransfer.dropEffect = 'none';
  760. return;
  761. }
  762. addCss(self.$dropZone, 'file-highlighted');
  763. },
  764. zoneDragLeave: function (e) {
  765. var self = this;
  766. self.zoneDragDropInit(e);
  767. if (self.isDisabled) {
  768. return;
  769. }
  770. self.$dropZone.removeClass('file-highlighted');
  771. },
  772. zoneDrop: function (e) {
  773. var self = this;
  774. e.preventDefault();
  775. /** @namespace e.originalEvent.dataTransfer */
  776. if (self.isDisabled || isEmpty(e.originalEvent.dataTransfer.files)) {
  777. return;
  778. }
  779. self.change(e, 'dragdrop');
  780. self.$dropZone.removeClass('file-highlighted');
  781. },
  782. initDragDrop: function () {
  783. var self = this, $zone = self.$dropZone;
  784. if (self.isUploadable && self.dropZoneEnabled && self.showPreview) {
  785. handler($zone, 'dragenter dragover', $.proxy(self.zoneDragEnter, self));
  786. handler($zone, 'dragleave', $.proxy(self.zoneDragLeave, self));
  787. handler($zone, 'drop', $.proxy(self.zoneDrop, self));
  788. handler($(document), 'dragenter dragover drop', self.zoneDragDropInit);
  789. }
  790. },
  791. browse: function (e) {
  792. var self = this;
  793. self.raise('filebrowse');
  794. if (e && e.isDefaultPrevented()) {
  795. return;
  796. }
  797. if (self.isError && !self.isUploadable) {
  798. self.clear();
  799. }
  800. self.$captionContainer.focus();
  801. },
  802. uploadClick: function (e) {
  803. var self = this, $btn = self.$container.find('.fileinput-upload'), $form,
  804. isEnabled = !$btn.hasClass('disabled') && isEmpty($btn.attr('disabled'));
  805. if (e && e.isDefaultPrevented()) {
  806. return;
  807. }
  808. if (!self.isUploadable) {
  809. if (isEnabled && $btn.attr('type') !== 'submit') {
  810. $form = $btn.closest('form');
  811. // downgrade to normal form submit if possible
  812. if ($form.length) {
  813. $form.trigger('submit');
  814. }
  815. e.preventDefault();
  816. }
  817. return;
  818. }
  819. e.preventDefault();
  820. if (isEnabled) {
  821. self.upload();
  822. }
  823. },
  824. submitForm: function () {
  825. var self = this, $el = self.$element, files = $el.get(0).files;
  826. if (files && self.minFileCount > 0 && self.getFileCount(files.length) < self.minFileCount) {
  827. self.noFilesError({});
  828. return false;
  829. }
  830. return !self.abort({});
  831. },
  832. abort: function (params) {
  833. var self = this, data;
  834. if (self.ajaxAborted && typeof self.ajaxAborted === "object" && self.ajaxAborted.message !== undefined) {
  835. data = $.extend(true, {}, self.getOutData(), params);
  836. data.abortData = self.ajaxAborted.data || {};
  837. data.abortMessage = self.ajaxAborted.message;
  838. self.cancel();
  839. self.setProgress(100);
  840. self.showUploadError(self.ajaxAborted.message, data, 'filecustomerror');
  841. return true;
  842. }
  843. return false;
  844. },
  845. noFilesError: function (params) {
  846. var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle,
  847. msg = self.msgFilesTooLess.replace('{n}', self.minFileCount).replace('{files}', label),
  848. $error = self.$errorContainer;
  849. self.addError(msg);
  850. self.isError = true;
  851. self.updateFileDetails(0);
  852. $error.fadeIn(800);
  853. self.raise('fileerror', [params]);
  854. self.clearFileInput();
  855. addCss(self.$container, 'has-error');
  856. },
  857. setProgress: function (p, $el) {
  858. var self = this, pct = Math.min(p, 100),
  859. template = pct < 100 ? self.progressTemplate : self.progressCompleteTemplate;
  860. $el = $el || self.$progress;
  861. if (!isEmpty(template)) {
  862. $el.html(template.replace(/\{percent}/g, pct));
  863. }
  864. },
  865. lock: function () {
  866. var self = this;
  867. self.resetErrors();
  868. self.disable();
  869. if (self.showRemove) {
  870. addCss(self.$container.find('.fileinput-remove'), 'hide');
  871. }
  872. if (self.showCancel) {
  873. self.$container.find('.fileinput-cancel').removeClass('hide');
  874. }
  875. self.raise('filelock', [self.filestack, self.getExtraData()]);
  876. },
  877. unlock: function (reset) {
  878. var self = this;
  879. if (reset === undefined) {
  880. reset = true;
  881. }
  882. self.enable();
  883. if (self.showCancel) {
  884. addCss(self.$container.find('.fileinput-cancel'), 'hide');
  885. }
  886. if (self.showRemove) {
  887. self.$container.find('.fileinput-remove').removeClass('hide');
  888. }
  889. if (reset) {
  890. self.resetFileStack();
  891. }
  892. self.raise('fileunlock', [self.filestack, self.getExtraData()]);
  893. },
  894. resetFileStack: function () {
  895. var self = this, i = 0, newstack = [], newnames = [];
  896. self.getThumbs().each(function () {
  897. var $thumb = $(this), ind = $thumb.attr('data-fileindex'),
  898. file = self.filestack[ind];
  899. if (ind === -1) {
  900. return;
  901. }
  902. if (file !== undefined) {
  903. newstack[i] = file;
  904. newnames[i] = self.getFileName(file);
  905. $thumb.attr({
  906. 'id': self.previewInitId + '-' + i,
  907. 'data-fileindex': i
  908. });
  909. i++;
  910. } else {
  911. $thumb.attr({
  912. 'id': 'uploaded-' + uniqId(),
  913. 'data-fileindex': '-1'
  914. });
  915. }
  916. });
  917. self.filestack = newstack;
  918. self.filenames = newnames;
  919. },
  920. destroy: function () {
  921. var self = this, $cont = self.$container;
  922. $cont.find('.file-drop-zone').off();
  923. self.$element.insertBefore($cont).off(NAMESPACE).removeData();
  924. $cont.off().remove();
  925. },
  926. refresh: function (options) {
  927. var self = this, $el = self.$element;
  928. options = options ? $.extend(true, {}, self.options, options) : self.options;
  929. self.destroy();
  930. $el.fileinput(options);
  931. if ($el.val()) {
  932. $el.trigger('change.fileinput');
  933. }
  934. },
  935. setFileDropZoneTitle: function () {
  936. var self = this, $zone = self.$container.find('.file-drop-zone');
  937. $zone.find('.' + self.dropZoneTitleClass).remove();
  938. if (!self.isUploadable || !self.showPreview || $zone.length === 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled) {
  939. return;
  940. }
  941. if ($zone.find('.file-preview-frame').length === 0 && isEmpty(self.defaultPreviewContent)) {
  942. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + self.dropZoneTitle + '</div>');
  943. }
  944. self.$container.removeClass('file-input-new');
  945. addCss(self.$container, 'file-input-ajax-new');
  946. },
  947. errorsExist: function () {
  948. var self = this, $err;
  949. if (self.$errorContainer.find('li').length) {
  950. return true;
  951. }
  952. $err = $(document.createElement('div')).html(self.$errorContainer.html());
  953. $err.find('span.kv-error-close').remove();
  954. $err.find('ul').remove();
  955. return $.trim($err.text()).length ? true : false;
  956. },
  957. getMsgSelected: function (n) {
  958. var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural;
  959. return self.msgSelected.replace('{n}', n).replace('{files}', strFiles);
  960. },
  961. renderThumbProgress: function () {
  962. return '<div class="file-thumb-progress hide">' + this.progressTemplate.replace(/\{percent}/g,
  963. '0') + '</div>';
  964. },
  965. renderFileFooter: function (caption, width) {
  966. var self = this, config = self.fileActionSettings, footer, out, template = self.getLayoutTemplate('footer');
  967. if (self.isUploadable) {
  968. footer = template.replace(/\{actions}/g, self.renderFileActions(true, true, false, false, false));
  969. out = footer.replace(/\{caption}/g, caption)
  970. .replace(/\{width}/g, width)
  971. .replace(/\{progress}/g, self.renderThumbProgress())
  972. .replace(/\{indicator}/g, config.indicatorNew)
  973. .replace(/\{indicatorTitle}/g, config.indicatorNewTitle);
  974. } else {
  975. out = template.replace(/\{actions}/g, '')
  976. .replace(/\{caption}/g, caption)
  977. .replace(/\{progress}/g, '')
  978. .replace(/\{width}/g, width)
  979. .replace(/\{indicator}/g, '')
  980. .replace(/\{indicatorTitle}/g, '');
  981. }
  982. out = replaceTags(out, self.previewThumbTags);
  983. return out;
  984. },
  985. renderFileActions: function (showUpload, showDelete, disabled, url, key) {
  986. if (!showUpload && !showDelete) {
  987. return '';
  988. }
  989. var self = this,
  990. vUrl = url === false ? '' : ' data-url="' + url + '"',
  991. vKey = key === false ? '' : ' data-key="' + key + '"',
  992. btnDelete = self.getLayoutTemplate('actionDelete'),
  993. btnUpload = '',
  994. template = self.getLayoutTemplate('actions'),
  995. otherButtons = self.otherActionButtons.replace(/\{dataKey}/g, vKey),
  996. config = self.fileActionSettings,
  997. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  998. btnDelete = btnDelete
  999. .replace(/\{removeClass}/g, removeClass)
  1000. .replace(/\{removeIcon}/g, config.removeIcon)
  1001. .replace(/\{removeTitle}/g, config.removeTitle)
  1002. .replace(/\{dataUrl}/g, vUrl)
  1003. .replace(/\{dataKey}/g, vKey);
  1004. if (showUpload) {
  1005. btnUpload = self.getLayoutTemplate('actionUpload')
  1006. .replace(/\{uploadClass}/g, config.uploadClass)
  1007. .replace(/\{uploadIcon}/g, config.uploadIcon)
  1008. .replace(/\{uploadTitle}/g, config.uploadTitle);
  1009. }
  1010. return template
  1011. .replace(/\{delete}/g, btnDelete)
  1012. .replace(/\{upload}/g, btnUpload)
  1013. .replace(/\{other}/g, otherButtons);
  1014. },
  1015. setThumbStatus: function ($thumb, status) {
  1016. var self = this;
  1017. if (!self.showPreview) {
  1018. return;
  1019. }
  1020. var icon = 'indicator' + status, msg = icon + 'Title',
  1021. css = 'file-preview-' + status.toLowerCase(),
  1022. $indicator = $thumb.find('.file-upload-indicator'),
  1023. config = self.fileActionSettings;
  1024. $thumb.removeClass('file-preview-success file-preview-error file-preview-loading');
  1025. if (status === 'Error') {
  1026. $thumb.find('.kv-file-upload').attr('disabled', true);
  1027. }
  1028. $indicator.html(config[icon]);
  1029. $indicator.attr('title', config[msg]);
  1030. $thumb.addClass(css);
  1031. },
  1032. clearPreview: function () {
  1033. var self = this, $thumbs = !self.showUploadedThumbs ? self.$preview.find('.file-preview-frame') :
  1034. self.$preview.find('.file-preview-frame:not(.file-preview-success)');
  1035. $thumbs.remove();
  1036. if (!self.$preview.find('.file-preview-frame').length || !self.showPreview) {
  1037. self.resetUpload();
  1038. }
  1039. self.validateDefaultPreview();
  1040. },
  1041. initPreview: function (isInit) {
  1042. var self = this, cap = self.initialCaption || '', out;
  1043. if (!previewCache.count(self.id)) {
  1044. self.clearPreview();
  1045. if (isInit) {
  1046. self.setCaption(cap);
  1047. } else {
  1048. self.initCaption();
  1049. }
  1050. return;
  1051. }
  1052. out = previewCache.out(self.id);
  1053. cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
  1054. self.$preview.html(out.content);
  1055. self.setCaption(cap);
  1056. if (!isEmpty(out.content)) {
  1057. self.$container.removeClass('file-input-new');
  1058. }
  1059. },
  1060. initPreviewDeletes: function () {
  1061. var self = this, deleteExtraData = self.deleteExtraData || {},
  1062. resetProgress = function () {
  1063. var hasFiles = self.isUploadable ? previewCache.count(self.id) : self.$element.get(0).files.length;
  1064. if (self.$preview.find('.kv-file-remove').length === 0 && !hasFiles) {
  1065. self.reset();
  1066. self.initialCaption = '';
  1067. }
  1068. };
  1069. self.$preview.find('.kv-file-remove').each(function () {
  1070. var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key');
  1071. if (isEmpty(vUrl) || vKey === undefined) {
  1072. return;
  1073. }
  1074. var $frame = $el.closest('.file-preview-frame'), cache = previewCache.data[self.id],
  1075. settings, params, index = $frame.data('fileindex'), config, extraData;
  1076. index = parseInt(index.replace('init_', ''));
  1077. config = isEmpty(cache.config) && isEmpty(cache.config[index]) ? null : cache.config[index];
  1078. extraData = isEmpty(config) || isEmpty(config.extra) ? deleteExtraData : config.extra;
  1079. if (typeof extraData === "function") {
  1080. extraData = extraData();
  1081. }
  1082. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  1083. settings = $.extend(true, {}, {
  1084. url: vUrl,
  1085. type: 'POST',
  1086. dataType: 'json',
  1087. data: $.extend(true, {}, {key: vKey}, extraData),
  1088. beforeSend: function (jqXHR) {
  1089. self.ajaxAborted = false;
  1090. self.raise('filepredelete', [vKey, jqXHR, extraData]);
  1091. if (self.ajaxAborted) {
  1092. jqXHR.abort();
  1093. } else {
  1094. addCss($frame, 'file-uploading');
  1095. addCss($el, 'disabled');
  1096. }
  1097. },
  1098. success: function (data, textStatus, jqXHR) {
  1099. var n, cap;
  1100. if (isEmpty(data) || isEmpty(data.error)) {
  1101. previewCache.unset(self.id, index);
  1102. n = previewCache.count(self.id);
  1103. cap = n > 0 ? self.getMsgSelected(n) : '';
  1104. self.raise('filedeleted', [vKey, jqXHR, extraData]);
  1105. self.setCaption(cap);
  1106. } else {
  1107. params.jqXHR = jqXHR;
  1108. params.response = data;
  1109. self.showError(data.error, params, 'filedeleteerror');
  1110. $frame.removeClass('file-uploading');
  1111. $el.removeClass('disabled');
  1112. resetProgress();
  1113. return;
  1114. }
  1115. $frame.removeClass('file-uploading').addClass('file-deleted');
  1116. $frame.fadeOut('slow', function () {
  1117. self.clearObjects($frame);
  1118. $frame.remove();
  1119. resetProgress();
  1120. if (!n && self.getFileStack().length === 0) {
  1121. self.setCaption('');
  1122. self.reset();
  1123. }
  1124. });
  1125. },
  1126. error: function (jqXHR, textStatus, errorThrown) {
  1127. var errMsg = self.parseError(jqXHR, errorThrown);
  1128. params.jqXHR = jqXHR;
  1129. params.response = {};
  1130. self.showError(errMsg, params, 'filedeleteerror');
  1131. $frame.removeClass('file-uploading');
  1132. resetProgress();
  1133. }
  1134. }, self.ajaxDeleteSettings);
  1135. handler($el, 'click', function () {
  1136. if (!self.validateMinCount()) {
  1137. return false;
  1138. }
  1139. $.ajax(settings);
  1140. });
  1141. });
  1142. },
  1143. clearObjects: function ($el) {
  1144. $el.find('video audio').each(function () {
  1145. this.pause();
  1146. $(this).remove();
  1147. });
  1148. $el.find('img object div').each(function () {
  1149. $(this).remove();
  1150. });
  1151. },
  1152. clearFileInput: function () {
  1153. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  1154. if (isEmpty($el.val())) {
  1155. return;
  1156. }
  1157. // Fix for IE ver < 11, that does not clear file inputs
  1158. // Requires a sequence of steps to prevent IE crashing but
  1159. // still allow clearing of the file input.
  1160. if (self.isIE9 || self.isIE10) {
  1161. $srcFrm = $el.closest('form');
  1162. $tmpFrm = $(document.createElement('form'));
  1163. $tmpEl = $(document.createElement('div'));
  1164. $el.before($tmpEl);
  1165. if ($srcFrm.length) {
  1166. $srcFrm.after($tmpFrm);
  1167. } else {
  1168. $tmpEl.after($tmpFrm);
  1169. }
  1170. $tmpFrm.append($el).trigger('reset');
  1171. $tmpEl.before($el).remove();
  1172. $tmpFrm.remove();
  1173. } else { // normal input clear behavior for other sane browsers
  1174. $el.val('');
  1175. }
  1176. self.fileInputCleared = true;
  1177. },
  1178. resetUpload: function () {
  1179. var self = this;
  1180. self.uploadCache = {content: [], config: [], tags: [], append: true};
  1181. self.uploadCount = 0;
  1182. self.uploadStatus = {};
  1183. self.uploadLog = [];
  1184. self.uploadAsyncCount = 0;
  1185. self.loadedImages = [];
  1186. self.totalImagesCount = 0;
  1187. self.$btnUpload.removeAttr('disabled');
  1188. self.setProgress(0);
  1189. addCss(self.$progress, 'hide');
  1190. self.resetErrors(false);
  1191. self.ajaxAborted = false;
  1192. self.ajaxRequests = [];
  1193. self.resetCanvas();
  1194. },
  1195. resetCanvas: function () {
  1196. var self = this;
  1197. if (self.canvas && self.imageCanvasContext) {
  1198. self.imageCanvasContext.clearRect(0, 0, self.canvas.width, self.canvas.height);
  1199. }
  1200. },
  1201. cancel: function () {
  1202. var self = this, xhr = self.ajaxRequests, len = xhr.length, i;
  1203. if (len > 0) {
  1204. for (i = 0; i < len; i += 1) {
  1205. self.cancelling = true;
  1206. xhr[i].abort();
  1207. }
  1208. }
  1209. self.getThumbs().each(function () {
  1210. var $thumb = $(this), ind = $thumb.attr('data-fileindex');
  1211. $thumb.removeClass('file-uploading');
  1212. if (self.filestack[ind] !== undefined) {
  1213. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  1214. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  1215. }
  1216. self.unlock();
  1217. });
  1218. },
  1219. cleanMemory: function ($thumb) {
  1220. var data = $thumb.is('img') ? $thumb.attr('src') : $thumb.find('source').attr('src');
  1221. /** @namespace objUrl.revokeObjectURL */
  1222. objUrl.revokeObjectURL(data);
  1223. },
  1224. hasInitialPreview: function () {
  1225. var self = this;
  1226. return !self.overwriteInitial && previewCache.count(self.id);
  1227. },
  1228. clear: function () {
  1229. var self = this, cap;
  1230. self.$btnUpload.removeAttr('disabled');
  1231. self.getThumbs().find('video,audio,img').each(function () {
  1232. self.cleanMemory($(this));
  1233. });
  1234. self.resetUpload();
  1235. self.clearStack();
  1236. self.clearFileInput();
  1237. self.resetErrors(true);
  1238. self.raise('fileclear');
  1239. if (self.hasInitialPreview()) {
  1240. self.showFileIcon();
  1241. self.resetPreview();
  1242. self.initPreviewDeletes();
  1243. self.$container.removeClass('file-input-new');
  1244. } else {
  1245. self.getThumbs().each(function () {
  1246. self.clearObjects($(this));
  1247. });
  1248. if (self.isUploadable) {
  1249. previewCache.data[self.id] = {};
  1250. }
  1251. self.$preview.html('');
  1252. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  1253. self.setCaption(cap);
  1254. self.$caption.attr('title', '');
  1255. addCss(self.$container, 'file-input-new');
  1256. self.validateDefaultPreview();
  1257. }
  1258. if (self.$container.find('.file-preview-frame').length === 0) {
  1259. if (!self.initCaption()) {
  1260. self.$captionContainer.find('.kv-caption-icon').hide();
  1261. }
  1262. }
  1263. self.hideFileIcon();
  1264. self.raise('filecleared');
  1265. self.$captionContainer.focus();
  1266. self.setFileDropZoneTitle();
  1267. },
  1268. resetPreview: function () {
  1269. var self = this, out, cap;
  1270. if (previewCache.count(self.id)) {
  1271. out = previewCache.out(self.id);
  1272. self.$preview.html(out.content);
  1273. cap = self.initialCaption ? self.initialCaption : out.caption;
  1274. self.setCaption(cap);
  1275. } else {
  1276. self.clearPreview();
  1277. self.initCaption();
  1278. }
  1279. },
  1280. clearDefaultPreview: function () {
  1281. var self = this;
  1282. self.$preview.find('.file-default-preview').remove();
  1283. },
  1284. validateDefaultPreview: function () {
  1285. var self = this;
  1286. if (!self.showPreview || isEmpty(self.defaultPreviewContent)) {
  1287. return;
  1288. }
  1289. self.$preview.html('<div class="file-default-preview">' + self.defaultPreviewContent + '</div>');
  1290. self.$container.removeClass('file-input-new');
  1291. },
  1292. resetPreviewThumbs: function (isAjax) {
  1293. var self = this, out;
  1294. if (isAjax) {
  1295. self.clearPreview();
  1296. self.clearStack();
  1297. return;
  1298. }
  1299. if (self.hasInitialPreview()) {
  1300. out = previewCache.out(self.id);
  1301. self.$preview.html(out.content);
  1302. self.setCaption(out.caption);
  1303. self.initPreviewDeletes();
  1304. } else {
  1305. self.clearPreview();
  1306. }
  1307. },
  1308. reset: function () {
  1309. var self = this;
  1310. self.resetPreview();
  1311. self.$container.find('.fileinput-filename').text('');
  1312. self.raise('filereset');
  1313. addCss(self.$container, 'file-input-new');
  1314. if (self.$preview.find('.file-preview-frame').length || self.isUploadable && self.dropZoneEnabled) {
  1315. self.$container.removeClass('file-input-new');
  1316. }
  1317. self.setFileDropZoneTitle();
  1318. self.clearStack();
  1319. self.formdata = {};
  1320. },
  1321. disable: function () {
  1322. var self = this;
  1323. self.isDisabled = true;
  1324. self.raise('filedisabled');
  1325. self.$element.attr('disabled', 'disabled');
  1326. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  1327. self.$container.find(".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").attr(
  1328. "disabled",
  1329. true);
  1330. self.initDragDrop();
  1331. },
  1332. enable: function () {
  1333. var self = this;
  1334. self.isDisabled = false;
  1335. self.raise('fileenabled');
  1336. self.$element.removeAttr('disabled');
  1337. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  1338. self.$container.find(
  1339. ".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").removeAttr("disabled");
  1340. self.initDragDrop();
  1341. },
  1342. getThumbs: function (css) {
  1343. css = css || '';
  1344. return this.$preview.find('.file-preview-frame:not(.file-preview-initial)' + css);
  1345. },
  1346. getExtraData: function (previewId, index) {
  1347. var self = this, data = self.uploadExtraData;
  1348. if (typeof self.uploadExtraData === "function") {
  1349. data = self.uploadExtraData(previewId, index);
  1350. }
  1351. return data;
  1352. },
  1353. uploadExtra: function (previewId, index) {
  1354. var self = this, data = self.getExtraData(previewId, index);
  1355. if (data.length === 0) {
  1356. return;
  1357. }
  1358. $.each(data, function (key, value) {
  1359. self.formdata.append(key, value);
  1360. });
  1361. },
  1362. setAsyncUploadStatus: function (previewId, pct, total) {
  1363. var self = this, sum = 0;
  1364. self.setProgress(pct, $('#' + previewId).find('.file-thumb-progress'));
  1365. self.uploadStatus[previewId] = pct;
  1366. $.each(self.uploadStatus, function (key, value) {
  1367. sum += value;
  1368. });
  1369. self.setProgress(Math.ceil(sum / total));
  1370. },
  1371. initXhr: function (xhrobj, previewId, fileCount) {
  1372. var self = this;
  1373. if (xhrobj.upload) {
  1374. xhrobj.upload.addEventListener('progress', function (event) {
  1375. var pct = 0, position = event.loaded || event.position, total = event.total;
  1376. /** @namespace event.lengthComputable */
  1377. if (event.lengthComputable) {
  1378. pct = Math.ceil(position / total * 100);
  1379. }
  1380. if (previewId) {
  1381. self.setAsyncUploadStatus(previewId, pct, fileCount);
  1382. } else {
  1383. self.setProgress(Math.ceil(pct));
  1384. }
  1385. }, false);
  1386. }
  1387. return xhrobj;
  1388. },
  1389. ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, previewId, index) {
  1390. var self = this, settings;
  1391. self.raise('filepreajax', [previewId, index]);
  1392. self.uploadExtra(previewId, index);
  1393. settings = $.extend(true, {}, {
  1394. xhr: function () {
  1395. var xhrobj = $.ajaxSettings.xhr();
  1396. return self.initXhr(xhrobj, previewId, self.getFileStack().length);
  1397. },
  1398. url: self.uploadUrl,
  1399. type: 'POST',
  1400. dataType: 'json',
  1401. data: self.formdata,
  1402. cache: false,
  1403. processData: false,
  1404. contentType: false,
  1405. beforeSend: fnBefore,
  1406. success: fnSuccess,
  1407. complete: fnComplete,
  1408. error: fnError
  1409. }, self.ajaxSettings);
  1410. self.ajaxRequests.push($.ajax(settings));
  1411. },
  1412. initUploadSuccess: function (out, $thumb, allFiles) {
  1413. var self = this, append, data, index, $newThumb, content, config, tags, i;
  1414. if (!self.showPreview || typeof out !== 'object' || $.isEmptyObject(out)) {
  1415. return;
  1416. }
  1417. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  1418. self.hasInitData = true;
  1419. content = out.initialPreview || [];
  1420. config = out.initialPreviewConfig || [];
  1421. tags = out.initialPreviewThumbTags || [];
  1422. append = out.append === undefined || out.append ? true : false;
  1423. self.overwriteInitial = false;
  1424. if ($thumb !== undefined) {
  1425. if (!allFiles) {
  1426. index = previewCache.add(self.id, content, config[0], tags[0], append);
  1427. data = previewCache.get(self.id, index, false);
  1428. $newThumb = $(data).hide();
  1429. $thumb.after($newThumb).fadeOut('slow', function () {
  1430. $newThumb.fadeIn('slow').css('display:inline-block');
  1431. self.initPreviewDeletes();
  1432. self.clearFileInput();
  1433. $thumb.remove();
  1434. });
  1435. } else {
  1436. i = $thumb.attr('data-fileindex');
  1437. self.uploadCache.content[i] = content[0];
  1438. self.uploadCache.config[i] = config[0];
  1439. self.uploadCache.tags[i] = tags[0];
  1440. self.uploadCache.append = append;
  1441. }
  1442. } else {
  1443. previewCache.set(self.id, content, config, tags, append);
  1444. self.initPreview();
  1445. self.initPreviewDeletes();
  1446. }
  1447. }
  1448. },
  1449. initSuccessThumbs: function () {
  1450. var self = this;
  1451. if (!self.showPreview) {
  1452. return;
  1453. }
  1454. self.getThumbs('.file-preview-success').each(function () {
  1455. var $thumb = $(this), $remove = $thumb.find('.kv-file-remove');
  1456. $remove.removeAttr('disabled');
  1457. handler($remove, 'click', function () {
  1458. var out = self.raise('filesuccessremove', [$thumb.attr('id'), $thumb.data('fileindex')]);
  1459. self.cleanMemory($thumb);
  1460. if (out === false) {
  1461. return;
  1462. }
  1463. $thumb.fadeOut('slow', function () {
  1464. $thumb.remove();
  1465. if (!self.$preview.find('.file-preview-frame').length) {
  1466. self.reset();
  1467. }
  1468. });
  1469. });
  1470. });
  1471. },
  1472. checkAsyncComplete: function () {
  1473. var self = this, previewId, i;
  1474. for (i = 0; i < self.filestack.length; i++) {
  1475. if (self.filestack[i]) {
  1476. previewId = self.previewInitId + "-" + i;
  1477. if ($.inArray(previewId, self.uploadLog) === -1) {
  1478. return false;
  1479. }
  1480. }
  1481. }
  1482. return (self.uploadAsyncCount === self.uploadLog.length);
  1483. },
  1484. uploadSingle: function (i, files, allFiles) {
  1485. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  1486. previewId = self.previewInitId + "-" + i, $thumb, chkComplete, $btnUpload, $btnDelete,
  1487. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1488. fnBefore, fnSuccess, fnComplete, fnError, updateUploadLog, params = {id: previewId, index: i};
  1489. self.formdata = formdata;
  1490. if (self.showPreview) {
  1491. $thumb = $('#' + previewId + ':not(.file-preview-initial)');
  1492. $btnUpload = $thumb.find('.kv-file-upload');
  1493. $btnDelete = $thumb.find('.kv-file-remove');
  1494. $('#' + previewId).find('.file-thumb-progress').removeClass('hide');
  1495. }
  1496. if (total === 0 || !hasPostData || ($btnUpload && $btnUpload.hasClass('disabled')) || self.abort(params)) {
  1497. return;
  1498. }
  1499. updateUploadLog = function (i, previewId) {
  1500. self.updateStack(i, undefined);
  1501. self.uploadLog.push(previewId);
  1502. if (self.checkAsyncComplete()) {
  1503. self.fileBatchCompleted = true;
  1504. }
  1505. };
  1506. chkComplete = function () {
  1507. if (!self.fileBatchCompleted) {
  1508. return;
  1509. }
  1510. setTimeout(function () {
  1511. if (self.showPreview) {
  1512. previewCache.set(
  1513. self.id,
  1514. self.uploadCache.content,
  1515. self.uploadCache.config,
  1516. self.uploadCache.tags,
  1517. self.uploadCache.append
  1518. );
  1519. if (self.hasInitData) {
  1520. self.initPreview();
  1521. self.initPreviewDeletes();
  1522. }
  1523. }
  1524. self.unlock();
  1525. self.clearFileInput();
  1526. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1527. self.uploadCount = 0;
  1528. self.uploadStatus = {};
  1529. self.uploadLog = [];
  1530. self.setProgress(100);
  1531. }, 100);
  1532. };
  1533. fnBefore = function (jqXHR) {
  1534. outData = self.getOutData(jqXHR);
  1535. self.fileBatchCompleted = false;
  1536. if (self.showPreview) {
  1537. if (!$thumb.hasClass('file-preview-success')) {
  1538. self.setThumbStatus($thumb, 'Loading');
  1539. addCss($thumb, 'file-uploading');
  1540. }
  1541. $btnUpload.attr('disabled', true);
  1542. $btnDelete.attr('disabled', true);
  1543. }
  1544. if (!allFiles) {
  1545. self.lock();
  1546. }
  1547. self.raise('filepreupload', [outData, previewId, i]);
  1548. $.extend(true, params, outData);
  1549. if (self.abort(params)) {
  1550. jqXHR.abort();
  1551. self.setProgress(100);
  1552. }
  1553. };
  1554. fnSuccess = function (data, textStatus, jqXHR) {
  1555. outData = self.getOutData(jqXHR, data);
  1556. $.extend(true, params, outData);
  1557. setTimeout(function () {
  1558. if (isEmpty(data) || isEmpty(data.error)) {
  1559. if (self.showPreview) {
  1560. self.setThumbStatus($thumb, 'Success');
  1561. $btnUpload.hide();
  1562. self.initUploadSuccess(data, $thumb, allFiles);
  1563. }
  1564. self.raise('fileuploaded', [outData, previewId, i]);
  1565. if (!allFiles) {
  1566. self.updateStack(i, undefined);
  1567. } else {
  1568. updateUploadLog(i, previewId);
  1569. }
  1570. } else {
  1571. self.showUploadError(data.error, params);
  1572. self.setPreviewError($thumb, i);
  1573. if (allFiles) {
  1574. updateUploadLog(i, previewId);
  1575. }
  1576. }
  1577. }, 100);
  1578. };
  1579. fnComplete = function () {
  1580. setTimeout(function () {
  1581. if (self.showPreview) {
  1582. $btnUpload.removeAttr('disabled');
  1583. $btnDelete.removeAttr('disabled');
  1584. $thumb.removeClass('file-uploading');
  1585. }
  1586. if (!allFiles) {
  1587. self.unlock(false);
  1588. self.clearFileInput();
  1589. } else {
  1590. chkComplete();
  1591. }
  1592. self.initSuccessThumbs();
  1593. }, 100);
  1594. };
  1595. fnError = function (jqXHR, textStatus, errorThrown) {
  1596. var errMsg = self.parseError(jqXHR, errorThrown, (allFiles ? files[i].name : null));
  1597. setTimeout(function () {
  1598. if (allFiles) {
  1599. updateUploadLog(i, previewId);
  1600. }
  1601. self.uploadStatus[previewId] = 100;
  1602. self.setPreviewError($thumb, i);
  1603. $.extend(true, params, self.getOutData(jqXHR));
  1604. self.showUploadError(errMsg, params);
  1605. }, 100);
  1606. };
  1607. formdata.append(self.uploadFileAttr, files[i], self.filenames[i]);
  1608. formdata.append('file_id', i);
  1609. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, previewId, i);
  1610. },
  1611. uploadBatch: function () {
  1612. var self = this, files = self.filestack, total = files.length, params = {}, fnBefore, fnSuccess, fnError,
  1613. fnComplete, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1614. setAllUploaded;
  1615. self.formdata = new FormData();
  1616. if (total === 0 || !hasPostData || self.abort(params)) {
  1617. return;
  1618. }
  1619. setAllUploaded = function () {
  1620. $.each(files, function (key) {
  1621. self.updateStack(key, undefined);
  1622. });
  1623. self.clearFileInput();
  1624. };
  1625. fnBefore = function (jqXHR) {
  1626. self.lock();
  1627. var outData = self.getOutData(jqXHR);
  1628. if (self.showPreview) {
  1629. self.getThumbs().each(function () {
  1630. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  1631. $btnDelete = $thumb.find('.kv-file-remove');
  1632. if (!$thumb.hasClass('file-preview-success')) {
  1633. self.setThumbStatus($thumb, 'Loading');
  1634. addCss($thumb, 'file-uploading');
  1635. }
  1636. $btnUpload.attr('disabled', true);
  1637. $btnDelete.attr('disabled', true);
  1638. });
  1639. }
  1640. self.raise('filebatchpreupload', [outData]);
  1641. if (self.abort(outData)) {
  1642. jqXHR.abort();
  1643. self.setProgress(100);
  1644. }
  1645. };
  1646. fnSuccess = function (data, textStatus, jqXHR) {
  1647. /** @namespace data.errorkeys */
  1648. var outData = self.getOutData(jqXHR, data), $thumbs = self.getThumbs(), key = 0,
  1649. keys = isEmpty(data) || isEmpty(data.errorkeys) ? [] : data.errorkeys;
  1650. if (isEmpty(data) || isEmpty(data.error)) {
  1651. self.raise('filebatchuploadsuccess', [outData]);
  1652. setAllUploaded();
  1653. if (self.showPreview) {
  1654. $thumbs.each(function () {
  1655. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload');
  1656. $thumb.find('.kv-file-upload').hide();
  1657. self.setThumbStatus($thumb, 'Success');
  1658. $thumb.removeClass('file-uploading');
  1659. $btnUpload.removeAttr('disabled');
  1660. });
  1661. self.initUploadSuccess(data);
  1662. } else {
  1663. self.reset();
  1664. }
  1665. } else {
  1666. if (self.showPreview) {
  1667. $thumbs.each(function () {
  1668. var $thumb = $(this), $btnDelete = $thumb.find('.kv-file-remove'),
  1669. $btnUpload = $thumb.find('.kv-file-upload');
  1670. $thumb.removeClass('file-uploading');
  1671. $btnUpload.removeAttr('disabled');
  1672. $btnDelete.removeAttr('disabled');
  1673. if (keys.length === 0) {
  1674. self.setPreviewError($thumb);
  1675. return;
  1676. }
  1677. if ($.inArray(key, keys) !== -1) {
  1678. self.setPreviewError($thumb);
  1679. } else {
  1680. $thumb.find('.kv-file-upload').hide();
  1681. self.setThumbStatus($thumb, 'Success');
  1682. self.updateStack(key, undefined);
  1683. }
  1684. key++;
  1685. });
  1686. self.initUploadSuccess(data);
  1687. }
  1688. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1689. }
  1690. };
  1691. fnComplete = function () {
  1692. self.setProgress(100);
  1693. self.unlock();
  1694. self.initSuccessThumbs();
  1695. self.clearFileInput();
  1696. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1697. };
  1698. fnError = function (jqXHR, textStatus, errorThrown) {
  1699. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1700. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1701. self.uploadFileCount = total - 1;
  1702. if (!self.showPreview) {
  1703. return;
  1704. }
  1705. self.getThumbs().each(function () {
  1706. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1707. $thumb.removeClass('file-uploading');
  1708. if (self.filestack[key] !== undefined) {
  1709. self.setPreviewError($thumb);
  1710. }
  1711. });
  1712. self.getThumbs().removeClass('file-uploading');
  1713. self.getThumbs(' .kv-file-upload').removeAttr('disabled');
  1714. self.getThumbs(' .kv-file-delete').removeAttr('disabled');
  1715. };
  1716. $.each(files, function (key, data) {
  1717. if (!isEmpty(files[key])) {
  1718. self.formdata.append(self.uploadFileAttr, data, self.filenames[key]);
  1719. }
  1720. });
  1721. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1722. },
  1723. uploadExtraOnly: function () {
  1724. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  1725. self.formdata = new FormData();
  1726. if (self.abort(params)) {
  1727. return;
  1728. }
  1729. fnBefore = function (jqXHR) {
  1730. self.lock();
  1731. var outData = self.getOutData(jqXHR);
  1732. self.raise('filebatchpreupload', [outData]);
  1733. self.setProgress(50);
  1734. params.data = outData;
  1735. params.xhr = jqXHR;
  1736. if (self.abort(params)) {
  1737. jqXHR.abort();
  1738. self.setProgress(100);
  1739. }
  1740. };
  1741. fnSuccess = function (data, textStatus, jqXHR) {
  1742. var outData = self.getOutData(jqXHR, data);
  1743. if (isEmpty(data) || isEmpty(data.error)) {
  1744. self.raise('filebatchuploadsuccess', [outData]);
  1745. self.clearFileInput();
  1746. self.initUploadSuccess(data);
  1747. } else {
  1748. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1749. }
  1750. };
  1751. fnComplete = function () {
  1752. self.setProgress(100);
  1753. self.unlock();
  1754. self.clearFileInput();
  1755. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1756. };
  1757. fnError = function (jqXHR, textStatus, errorThrown) {
  1758. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1759. params.data = outData;
  1760. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1761. };
  1762. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1763. },
  1764. upload: function () {
  1765. var self = this, totLen = self.getFileStack().length, params = {},
  1766. i, outData, len, hasExtraData = !$.isEmptyObject(self.getExtraData());
  1767. if (self.minFileCount > 0 && self.getFileCount(totLen) < self.minFileCount) {
  1768. self.noFilesError(params);
  1769. return;
  1770. }
  1771. if (!self.isUploadable || self.isDisabled || (totLen === 0 && !hasExtraData)) {
  1772. return;
  1773. }
  1774. self.resetUpload();
  1775. self.$progress.removeClass('hide');
  1776. self.uploadCount = 0;
  1777. self.uploadStatus = {};
  1778. self.uploadLog = [];
  1779. self.lock();
  1780. self.setProgress(2);
  1781. if (totLen === 0 && hasExtraData) {
  1782. self.uploadExtraOnly();
  1783. return;
  1784. }
  1785. len = self.filestack.length;
  1786. self.hasInitData = false;
  1787. if (self.uploadAsync) {
  1788. outData = self.getOutData();
  1789. self.raise('filebatchpreupload', [outData]);
  1790. self.fileBatchCompleted = false;
  1791. self.uploadCache = {content: [], config: [], tags: [], append: true};
  1792. self.uploadAsyncCount = self.getFileStack().length;
  1793. for (i = 0; i < len; i++) {
  1794. self.uploadCache.content[i] = null;
  1795. self.uploadCache.config[i] = null;
  1796. self.uploadCache.tags[i] = null;
  1797. }
  1798. for (i = 0; i < len; i++) {
  1799. if (self.filestack[i] !== undefined) {
  1800. self.uploadSingle(i, self.filestack, true);
  1801. }
  1802. }
  1803. return;
  1804. }
  1805. self.uploadBatch();
  1806. },
  1807. initFileActions: function () {
  1808. var self = this;
  1809. if (!self.showPreview) {
  1810. return;
  1811. }
  1812. self.$preview.find('.kv-file-remove').each(function () {
  1813. var $el = $(this), $frame = $el.closest('.file-preview-frame'), hasError,
  1814. id = $frame.attr('id'), ind = $frame.attr('data-fileindex'), n, cap, status;
  1815. handler($el, 'click', function () {
  1816. status = self.raise('filepreremove', [id, ind]);
  1817. if (status === false || !self.validateMinCount()) {
  1818. return false;
  1819. }
  1820. hasError = $frame.hasClass('file-preview-error');
  1821. self.cleanMemory($frame);
  1822. $frame.fadeOut('slow', function () {
  1823. self.updateStack(ind, undefined);
  1824. self.clearObjects($frame);
  1825. $frame.remove();
  1826. if (id && hasError) {
  1827. self.$errorContainer.find('li[data-file-id="' + id + '"]').fadeOut('fast', function () {
  1828. $(this).remove();
  1829. if (!self.errorsExist()) {
  1830. self.resetErrors();
  1831. }
  1832. });
  1833. }
  1834. var filestack = self.getFileStack(true), len = filestack.length, chk = previewCache.count(
  1835. self.id),
  1836. hasThumb = self.showPreview && self.$preview.find('.file-preview-frame').length;
  1837. self.clearFileInput();
  1838. if (len === 0 && chk === 0 && !hasThumb) {
  1839. self.reset();
  1840. } else {
  1841. n = chk + len;
  1842. cap = n > 1 ? self.getMsgSelected(n) : (filestack[0] ? self.getFileNames()[0] : '');
  1843. self.setCaption(cap);
  1844. }
  1845. self.raise('fileremoved', [id, ind]);
  1846. });
  1847. });
  1848. });
  1849. self.$preview.find('.kv-file-upload').each(function () {
  1850. var $el = $(this);
  1851. handler($el, 'click', function () {
  1852. var $frame = $el.closest('.file-preview-frame'),
  1853. ind = $frame.attr('data-fileindex');
  1854. if (!$frame.hasClass('file-preview-error')) {
  1855. self.uploadSingle(ind, self.filestack, false);
  1856. }
  1857. });
  1858. });
  1859. },
  1860. hideFileIcon: function () {
  1861. if (this.overwriteInitial) {
  1862. this.$captionContainer.find('.kv-caption-icon').hide();
  1863. }
  1864. },
  1865. showFileIcon: function () {
  1866. this.$captionContainer.find('.kv-caption-icon').show();
  1867. },
  1868. addError: function (msg) {
  1869. var self = this, $error = self.$errorContainer;
  1870. if (msg && $error.length) {
  1871. $error.html(self.errorCloseButton + msg);
  1872. handler($error.find('.kv-error-close'), 'click', function () {
  1873. $error.fadeOut('slow');
  1874. });
  1875. }
  1876. },
  1877. resetErrors: function (fade) {
  1878. var self = this, $error = self.$errorContainer;
  1879. self.isError = false;
  1880. self.$container.removeClass('has-error');
  1881. $error.html('');
  1882. if (fade) {
  1883. $error.fadeOut('slow');
  1884. } else {
  1885. $error.hide();
  1886. }
  1887. },
  1888. showFolderError: function (folders) {
  1889. var self = this, $error = self.$errorContainer;
  1890. if (!folders) {
  1891. return;
  1892. }
  1893. self.addError(self.msgFoldersNotAllowed.replace(/\{n}/g, folders));
  1894. $error.fadeIn(800);
  1895. addCss(self.$container, 'has-error');
  1896. self.raise('filefoldererror', [folders]);
  1897. },
  1898. showUploadError: function (msg, params, event) {
  1899. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror',
  1900. e = params && params.id ? '<li data-file-id="' + params.id + '">' + msg + '</li>' : '<li>' + msg + '</li>';
  1901. if ($error.find('ul').length === 0) {
  1902. self.addError('<ul>' + e + '</ul>');
  1903. } else {
  1904. $error.find('ul').append(e);
  1905. }
  1906. $error.fadeIn(800);
  1907. self.raise(ev, [params]);
  1908. self.$container.removeClass('file-input-new');
  1909. addCss(self.$container, 'has-error');
  1910. return true;
  1911. },
  1912. showError: function (msg, params, event) {
  1913. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  1914. params = params || {};
  1915. params.reader = self.reader;
  1916. self.addError(msg);
  1917. $error.fadeIn(800);
  1918. self.raise(ev, [params]);
  1919. if (!self.isUploadable) {
  1920. self.clearFileInput();
  1921. }
  1922. self.$container.removeClass('file-input-new');
  1923. addCss(self.$container, 'has-error');
  1924. self.$btnUpload.attr('disabled', true);
  1925. return true;
  1926. },
  1927. errorHandler: function (evt, caption) {
  1928. var self = this, err = evt.target.error;
  1929. /** @namespace err.NOT_FOUND_ERR */
  1930. /** @namespace err.SECURITY_ERR */
  1931. /** @namespace err.NOT_READABLE_ERR */
  1932. if (err.code === err.NOT_FOUND_ERR) {
  1933. self.showError(self.msgFileNotFound.replace('{name}', caption));
  1934. } else if (err.code === err.SECURITY_ERR) {
  1935. self.showError(self.msgFileSecured.replace('{name}', caption));
  1936. } else if (err.code === err.NOT_READABLE_ERR) {
  1937. self.showError(self.msgFileNotReadable.replace('{name}', caption));
  1938. } else if (err.code === err.ABORT_ERR) {
  1939. self.showError(self.msgFilePreviewAborted.replace('{name}', caption));
  1940. } else {
  1941. self.showError(self.msgFilePreviewError.replace('{name}', caption));
  1942. }
  1943. },
  1944. parseFileType: function (file) {
  1945. var self = this, isValid, vType, cat, i;
  1946. for (i = 0; i < defaultPreviewTypes.length; i += 1) {
  1947. cat = defaultPreviewTypes[i];
  1948. isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  1949. vType = isValid(file.type, file.name) ? cat : '';
  1950. if (!isEmpty(vType)) {
  1951. return vType;
  1952. }
  1953. }
  1954. return 'other';
  1955. },
  1956. previewDefault: function (file, previewId, isDisabled) {
  1957. if (!this.showPreview) {
  1958. return;
  1959. }
  1960. var self = this, frameClass = '', fname = file ? file.name : '',
  1961. /** @namespace objUrl.createObjectURL */
  1962. data = objUrl.createObjectURL(file), ind = previewId.slice(previewId.lastIndexOf('-') + 1),
  1963. config = self.previewSettings.other || defaultPreviewSettings.other,
  1964. footer = self.renderFileFooter(file.name, config.width),
  1965. previewOtherTemplate = self.parseFilePreviewIcon(self.getPreviewTemplate('other'), fname);
  1966. if (isDisabled === true) {
  1967. if (!self.isUploadable) {
  1968. footer += '<div class="file-other-error" title="' + self.fileActionSettings.indicatorErrorTitle +
  1969. '">' + self.fileActionSettings.indicatorError + '</div>';
  1970. }
  1971. }
  1972. self.clearDefaultPreview();
  1973. self.$preview.append("\n" + previewOtherTemplate
  1974. .replace(/\{previewId}/g, previewId)
  1975. .replace(/\{frameClass}/g, frameClass)
  1976. .replace(/\{fileindex}/g, ind)
  1977. .replace(/\{caption}/g, self.slug(file.name))
  1978. .replace(/\{width}/g, config.width)
  1979. .replace(/\{height}/g, config.height)
  1980. .replace(/\{type}/g, file.type)
  1981. .replace(/\{data}/g, data)
  1982. .replace(/\{footer}/g, footer));
  1983. if (isDisabled === true && self.isUploadable) {
  1984. self.setThumbStatus($('#' + previewId), 'Error');
  1985. }
  1986. },
  1987. previewFile: function (i, file, theFile, previewId, data) {
  1988. if (!this.showPreview) {
  1989. return;
  1990. }
  1991. var self = this, cat = self.parseFileType(file), fname = file ? file.name : '', caption = self.slug(fname),
  1992. content, strText, types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes,
  1993. tmplt = self.getPreviewTemplate(cat), chkTypes = types && types.indexOf(cat) >= 0, id,
  1994. config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat],
  1995. chkMimes = mimes && mimes.indexOf(file.type) !== -1,
  1996. footer = self.renderFileFooter(caption, config.width), modal = '',
  1997. ind = previewId.slice(previewId.lastIndexOf('-') + 1);
  1998. if (chkTypes || chkMimes) {
  1999. tmplt = self.parseFilePreviewIcon(tmplt, fname.split('.').pop());
  2000. if (cat === 'text') {
  2001. strText = htmlEncode(theFile.target.result);
  2002. id = 'text-' + uniqId();
  2003. content = tmplt.replace(/\{zoom}/g, self.getLayoutTemplate('zoom'));
  2004. modal = self.getLayoutTemplate('modal').replace('{id}', id)
  2005. .replace(/\{title}/g, caption)
  2006. .replace(/\{body}/g, strText).replace(/\{heading}/g, self.msgZoomModalHeading);
  2007. content = content.replace(/\{previewId}/g, previewId).replace(/\{caption}/g, caption)
  2008. .replace(/\{width}/g, config.width).replace(/\{height}/g, config.height)
  2009. .replace(/\{frameClass}/g, '').replace(/\{zoomInd}/g, self.zoomIndicator)
  2010. .replace(/\{footer}/g, footer).replace(/\{fileindex}/g, ind)
  2011. .replace(/\{type}/g, file.type).replace(/\{zoomTitle}/g, self.msgZoomTitle)
  2012. .replace(/\{dialog}/g, "$('#" + id + "').modal('show')")
  2013. .replace(/\{data}/g, strText) + modal;
  2014. } else {
  2015. content = tmplt.replace(/\{previewId}/g, previewId).replace(/\{caption}/g, caption)
  2016. .replace(/\{frameClass}/g, '').replace(/\{type}/g, file.type).replace(/\{fileindex}/g, ind)
  2017. .replace(/\{width}/g, config.width).replace(/\{height}/g, config.height)
  2018. .replace(/\{footer}/g, footer).replace(/\{data}/g, data);
  2019. }
  2020. self.clearDefaultPreview();
  2021. self.$preview.append("\n" + content);
  2022. self.validateImage(i, previewId, caption, file.type);
  2023. } else {
  2024. self.previewDefault(file, previewId);
  2025. }
  2026. },
  2027. slugDefault: function (text) {
  2028. return isEmpty(text) ? '' : String(text).replace(/[\-\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_');
  2029. },
  2030. readFiles: function (files) {
  2031. this.reader = new FileReader();
  2032. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  2033. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  2034. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  2035. settings = self.fileTypeSettings, ctr = self.filestack.length, readFile,
  2036. throwError = function (msg, file, previewId, index) {
  2037. var p1 = $.extend(true, {}, self.getOutData({}, {}, files), {id: previewId, index: index}),
  2038. p2 = {id: previewId, index: index, file: file, files: files};
  2039. self.previewDefault(file, previewId, true);
  2040. if (self.isUploadable) {
  2041. self.addToStack(undefined);
  2042. }
  2043. setTimeout(readFile(index + 1), 100);
  2044. self.initFileActions();
  2045. if (self.removeFromPreviewOnError) {
  2046. $('#' + previewId).remove();
  2047. }
  2048. return self.isUploadable ? self.showUploadError(msg, p1) : self.showError(msg, p2);
  2049. };
  2050. self.loadedImages = [];
  2051. self.totalImagesCount = 0;
  2052. $.each(files, function (key, file) {
  2053. var func = self.fileTypeSettings.image || defaultFileTypeSettings.image;
  2054. if (func && func(file.type)) {
  2055. self.totalImagesCount++;
  2056. }
  2057. });
  2058. readFile = function (i) {
  2059. if (isEmpty($el.attr('multiple'))) {
  2060. numFiles = 1;
  2061. }
  2062. if (i >= numFiles) {
  2063. if (self.isUploadable && self.filestack.length > 0) {
  2064. self.raise('filebatchselected', [self.getFileStack()]);
  2065. } else {
  2066. self.raise('filebatchselected', [files]);
  2067. }
  2068. $container.removeClass('file-thumb-loading');
  2069. $status.html('');
  2070. return;
  2071. }
  2072. var node = ctr + i, previewId = previewInitId + "-" + node, isText, file = files[i],
  2073. caption = self.slug(file.name), fileSize = (file.size || 0) / 1000, checkFile, fileExtExpr = '',
  2074. previewData = objUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk,
  2075. fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '),
  2076. fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', ');
  2077. if (!isEmpty(fileExt)) {
  2078. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  2079. }
  2080. fileSize = fileSize.toFixed(2);
  2081. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  2082. msg = self.msgSizeTooLarge.replace('{name}', caption)
  2083. .replace('{size}', fileSize)
  2084. .replace('{maxSize}', self.maxFileSize);
  2085. self.isError = throwError(msg, file, previewId, i);
  2086. return;
  2087. }
  2088. if (!isEmpty(fileTypes) && isArray(fileTypes)) {
  2089. for (j = 0; j < fileTypes.length; j += 1) {
  2090. typ = fileTypes[j];
  2091. checkFile = settings[typ];
  2092. chk = (checkFile !== undefined && checkFile(file.type, caption));
  2093. fileCount += isEmpty(chk) ? 0 : chk.length;
  2094. }
  2095. if (fileCount === 0) {
  2096. msg = self.msgInvalidFileType.replace('{name}', caption).replace('{types}', strTypes);
  2097. self.isError = throwError(msg, file, previewId, i);
  2098. return;
  2099. }
  2100. }
  2101. if (fileCount === 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) {
  2102. chk = caption.match(fileExtExpr);
  2103. fileCount += isEmpty(chk) ? 0 : chk.length;
  2104. if (fileCount === 0) {
  2105. msg = self.msgInvalidFileExtension.replace('{name}', caption).replace('{extensions}',
  2106. strExt);
  2107. self.isError = throwError(msg, file, previewId, i);
  2108. return;
  2109. }
  2110. }
  2111. if (!self.showPreview) {
  2112. self.addToStack(file);
  2113. setTimeout(readFile(i + 1), 100);
  2114. self.raise('fileloaded', [file, previewId, i, reader]);
  2115. return;
  2116. }
  2117. if ($preview.length > 0 && FileReader !== undefined) {
  2118. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  2119. $container.addClass('file-thumb-loading');
  2120. reader.onerror = function (evt) {
  2121. self.errorHandler(evt, caption);
  2122. };
  2123. reader.onload = function (theFile) {
  2124. self.previewFile(i, file, theFile, previewId, previewData);
  2125. self.initFileActions();
  2126. };
  2127. reader.onloadend = function () {
  2128. msg = msgProgress
  2129. .replace('{index}', i + 1).replace('{files}', numFiles)
  2130. .replace('{percent}', 50).replace('{name}', caption);
  2131. setTimeout(function () {
  2132. $status.html(msg);
  2133. self.updateFileDetails(numFiles);
  2134. readFile(i + 1);
  2135. }, 100);
  2136. self.raise('fileloaded', [file, previewId, i, reader]);
  2137. };
  2138. reader.onprogress = function (data) {
  2139. if (data.lengthComputable) {
  2140. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  2141. msg = msgProgress.replace('{index}', i + 1).replace('{files}', numFiles)
  2142. .replace('{percent}', progress).replace('{name}', caption);
  2143. setTimeout(function () {
  2144. $status.html(msg);
  2145. }, 100);
  2146. }
  2147. };
  2148. isText = isSet('text', settings) ? settings.text : defaultFileTypeSettings.text;
  2149. if (isText(file.type, caption)) {
  2150. reader.readAsText(file, self.textEncoding);
  2151. } else {
  2152. reader.readAsArrayBuffer(file);
  2153. }
  2154. } else {
  2155. self.previewDefault(file, previewId);
  2156. setTimeout(function () {
  2157. readFile(i + 1);
  2158. self.updateFileDetails(numFiles);
  2159. }, 100);
  2160. self.raise('fileloaded', [file, previewId, i, reader]);
  2161. }
  2162. self.addToStack(file);
  2163. };
  2164. readFile(0);
  2165. self.updateFileDetails(numFiles, false);
  2166. },
  2167. updateFileDetails: function (numFiles) {
  2168. var self = this, $el = self.$element, fileStack = self.getFileStack(),
  2169. name = ($el[0].files[0] && $el[0].files[0].name) || (fileStack.length && fileStack[0].name) || '',
  2170. label = self.slug(name), n = self.isUploadable ? fileStack.length : numFiles,
  2171. nFiles = previewCache.count(self.id) + n, log = n > 1 ? self.getMsgSelected(nFiles) : label;
  2172. if (self.isError) {
  2173. self.$previewContainer.removeClass('file-thumb-loading');
  2174. self.$previewStatus.html('');
  2175. self.$captionContainer.find('.kv-caption-icon').hide();
  2176. } else {
  2177. self.showFileIcon();
  2178. }
  2179. self.setCaption(log, self.isError);
  2180. self.$container.removeClass('file-input-new file-input-ajax-new');
  2181. if (arguments.length === 1) {
  2182. self.raise('fileselect', [numFiles, label]);
  2183. }
  2184. if (previewCache.count(self.id)) {
  2185. self.initPreviewDeletes();
  2186. }
  2187. },
  2188. validateMinCount: function () {
  2189. var self = this, len = self.isUploadable ? self.getFileStack().length : self.$element.get(0).files.length;
  2190. if (self.validateInitialCount && self.minFileCount > 0 && self.getFileCount(len - 1) < self.minFileCount) {
  2191. self.noFilesError({});
  2192. return false;
  2193. }
  2194. return true;
  2195. },
  2196. getFileCount: function (fileCount) {
  2197. var self = this, addCount = 0;
  2198. if (self.validateInitialCount && !self.overwriteInitial) {
  2199. addCount = previewCache.count(self.id);
  2200. fileCount += addCount;
  2201. }
  2202. return fileCount;
  2203. },
  2204. change: function (e) {
  2205. var self = this, $el = self.$element;
  2206. if (!self.isUploadable && isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix
  2207. self.fileInputCleared = false;
  2208. return;
  2209. }
  2210. self.fileInputCleared = false;
  2211. var tfiles, msg, total, isDragDrop = arguments.length > 1, isAjaxUpload = self.isUploadable, i = 0, f, n, len,
  2212. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files, ctr = self.filestack.length,
  2213. isSingleUpload = isEmpty($el.attr('multiple')), flagSingle = (isSingleUpload && ctr > 0), folders = 0,
  2214. throwError = function (mesg, file, previewId, index) {
  2215. var p1 = $.extend(true, {}, self.getOutData({}, {}, files), {id: previewId, index: index}),
  2216. p2 = {id: previewId, index: index, file: file, files: files};
  2217. return self.isUploadable ? self.showUploadError(mesg, p1) : self.showError(mesg, p2);
  2218. };
  2219. self.reader = null;
  2220. self.resetUpload();
  2221. self.hideFileIcon();
  2222. if (self.isUploadable) {
  2223. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  2224. }
  2225. if (isDragDrop) {
  2226. tfiles = [];
  2227. while (files[i]) {
  2228. f = files[i];
  2229. if (!f.type && f.size % 4096 === 0) {
  2230. folders++;
  2231. } else {
  2232. tfiles.push(f);
  2233. }
  2234. i++;
  2235. }
  2236. } else {
  2237. if (e.target.files === undefined) {
  2238. tfiles = e.target && e.target.value ? [
  2239. {name: e.target.value.replace(/^.+\\/, '')}
  2240. ] : [];
  2241. } else {
  2242. tfiles = e.target.files;
  2243. }
  2244. }
  2245. if (isEmpty(tfiles) || tfiles.length === 0) {
  2246. if (!isAjaxUpload) {
  2247. self.clear();
  2248. }
  2249. self.showFolderError(folders);
  2250. self.raise('fileselectnone');
  2251. return;
  2252. }
  2253. self.resetErrors();
  2254. len = tfiles.length;
  2255. total = self.isUploadable ? self.getFileStack().length + len : len;
  2256. total = self.getFileCount(total);
  2257. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  2258. if (!self.autoReplace || len > self.maxFileCount) {
  2259. n = (self.autoReplace && len > self.maxFileCount) ? len : total;
  2260. msg = self.msgFilesTooMany.replace('{m}', self.maxFileCount).replace('{n}', n);
  2261. self.isError = throwError(msg, null, null, null);
  2262. self.$captionContainer.find('.kv-caption-icon').hide();
  2263. self.setCaption('', true);
  2264. self.$container.removeClass('file-input-new file-input-ajax-new');
  2265. return;
  2266. }
  2267. if (total > self.maxFileCount) {
  2268. self.resetPreviewThumbs(isAjaxUpload);
  2269. }
  2270. } else {
  2271. if (!isAjaxUpload || flagSingle) {
  2272. self.resetPreviewThumbs(false);
  2273. if (flagSingle) {
  2274. self.clearStack();
  2275. }
  2276. } else {
  2277. if (isAjaxUpload && ctr === 0 && (!previewCache.count(self.id) || self.overwriteInitial)) {
  2278. self.resetPreviewThumbs(true);
  2279. }
  2280. }
  2281. }
  2282. if (self.isPreviewable) {
  2283. self.readFiles(tfiles);
  2284. } else {
  2285. self.updateFileDetails(1);
  2286. }
  2287. self.showFolderError(folders);
  2288. },
  2289. getFileName: function (file) {
  2290. return file && file.name ? this.slug(file.name) : undefined;
  2291. },
  2292. getFileNames: function (skipNull) {
  2293. var self = this;
  2294. return self.filenames.filter(function (n) {
  2295. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  2296. });
  2297. },
  2298. getFileStack: function (skipNull) {
  2299. var self = this;
  2300. return self.filestack.filter(function (n) {
  2301. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  2302. });
  2303. },
  2304. clearStack: function () {
  2305. var self = this;
  2306. self.filestack = [];
  2307. self.filenames = [];
  2308. },
  2309. updateStack: function (i, file) {
  2310. var self = this;
  2311. self.filestack[i] = file;
  2312. self.filenames[i] = self.getFileName(file);
  2313. },
  2314. addToStack: function (file) {
  2315. var self = this;
  2316. self.filestack.push(file);
  2317. self.filenames.push(self.getFileName(file));
  2318. },
  2319. setPreviewError: function ($thumb, i, val) {
  2320. var self = this;
  2321. if (i) {
  2322. self.updateStack(i, val);
  2323. }
  2324. if (self.removeFromPreviewOnError) {
  2325. $thumb.remove();
  2326. } else {
  2327. self.setThumbStatus($thumb, 'Error');
  2328. }
  2329. },
  2330. checkDimensions: function (i, chk, $img, $thumb, fname, type, params) {
  2331. var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max',
  2332. limit = self[tag + 'Image' + type], $imgEl, isValid;
  2333. if (isEmpty(limit) || !$img.length) {
  2334. return;
  2335. }
  2336. $imgEl = $img[0];
  2337. dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height;
  2338. isValid = chk === 'Small' ? dim >= limit : dim <= limit;
  2339. if (isValid) {
  2340. return;
  2341. }
  2342. msg = self['msgImage' + type + chk].replace('{name}', fname).replace('{size}', limit);
  2343. self.showUploadError(msg, params);
  2344. self.setPreviewError($thumb, i, null);
  2345. },
  2346. validateImage: function (i, previewId, fname, ftype) {
  2347. var self = this, $preview = self.$preview, params, w1, w2,
  2348. $thumb = $preview.find("#" + previewId), $img = $thumb.find('img');
  2349. fname = fname || 'Untitled';
  2350. if (!$img.length) {
  2351. return;
  2352. }
  2353. handler($img, 'load', function () {
  2354. w1 = $thumb.width();
  2355. w2 = $preview.width();
  2356. if (w1 > w2) {
  2357. $img.css('width', '100%');
  2358. $thumb.css('width', '97%');
  2359. }
  2360. params = {ind: i, id: previewId};
  2361. self.checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
  2362. self.checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
  2363. if (!self.resizeImage) {
  2364. self.checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
  2365. self.checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
  2366. }
  2367. self.raise('fileimageloaded', [previewId]);
  2368. self.loadedImages.push({ind: i, img: $img, thumb: $thumb, pid: previewId, typ: ftype});
  2369. self.validateAllImages();
  2370. objUrl.revokeObjectURL($img.attr('src'));
  2371. });
  2372. },
  2373. validateAllImages: function () {
  2374. var self = this, i, config, $img, $thumb, pid, ind, params = {}, errFunc;
  2375. if (self.loadedImages.length !== self.totalImagesCount) {
  2376. return;
  2377. }
  2378. self.raise('fileimagesloaded');
  2379. if (!self.resizeImage) {
  2380. return;
  2381. }
  2382. errFunc = self.isUploadable ? self.showUploadError : self.showError;
  2383. for (i = 0; i < self.loadedImages.length; i++) {
  2384. config = self.loadedImages[i];
  2385. $img = config.img;
  2386. $thumb = config.thumb;
  2387. pid = config.pid;
  2388. ind = config.ind;
  2389. params = {id: pid, 'index': ind};
  2390. if (!self.getResizedImage($img[0], config.typ, pid, ind)) {
  2391. errFunc(self.msgImageResizeError, params, 'fileimageresizeerror');
  2392. self.setPreviewError($thumb, ind);
  2393. }
  2394. }
  2395. self.raise('fileimagesresized');
  2396. },
  2397. getResizedImage: function (image, type, pid, ind) {
  2398. var self = this, width = image.naturalWidth, height = image.naturalHeight, ratio = 1,
  2399. maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height,
  2400. isValidImage = (width && height), chkWidth, chkHeight,
  2401. canvas = self.imageCanvas, context = self.imageCanvasContext;
  2402. if (!isValidImage) {
  2403. return false;
  2404. }
  2405. if (width === maxWidth && height === maxHeight) {
  2406. return true;
  2407. }
  2408. type = type || self.resizeDefaultImageType;
  2409. chkWidth = width > maxWidth;
  2410. chkHeight = height > maxHeight;
  2411. if (self.resizePreference === 'width') {
  2412. ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1);
  2413. } else {
  2414. ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1);
  2415. }
  2416. self.resetCanvas();
  2417. width *= ratio;
  2418. height *= ratio;
  2419. canvas.width = width;
  2420. canvas.height = height;
  2421. try {
  2422. context.drawImage(image, 0, 0, width, height);
  2423. canvas.toBlob(function (blob) {
  2424. self.raise('fileimageresized', [pid, ind]);
  2425. self.filestack[ind] = blob;
  2426. }, type, self.resizeQuality);
  2427. return true;
  2428. }
  2429. catch (err) {
  2430. return false;
  2431. }
  2432. },
  2433. initCaption: function () {
  2434. var self = this, cap = self.initialCaption || '';
  2435. if (self.overwriteInitial || isEmpty(cap)) {
  2436. self.$caption.html('');
  2437. return false;
  2438. }
  2439. self.setCaption(cap);
  2440. return true;
  2441. },
  2442. setCaption: function (content, isError) {
  2443. var self = this, title, out;
  2444. if (isError) {
  2445. title = $('<div>' + self.msgValidationError + '</div>').text();
  2446. out = '<span class="' + self.msgValidationErrorClass + '">' +
  2447. self.msgValidationErrorIcon + title + '</span>';
  2448. } else {
  2449. if (isEmpty(content) || self.$caption.length === 0) {
  2450. return;
  2451. }
  2452. title = $('<div>' + content + '</div>').text();
  2453. out = self.getLayoutTemplate('icon') + title;
  2454. }
  2455. self.$caption.html(out);
  2456. self.$caption.attr('title', title);
  2457. self.$captionContainer.find('.file-caption-ellipsis').attr('title', title);
  2458. },
  2459. initBrowse: function ($container) {
  2460. var self = this;
  2461. self.$btnFile = $container.find('.btn-file');
  2462. self.$btnFile.append(self.$element);
  2463. },
  2464. createContainer: function () {
  2465. var self = this,
  2466. $container = $(document.createElement("div"))
  2467. .attr({"class": 'file-input file-input-new'})
  2468. .html(self.renderMain());
  2469. self.$element.before($container);
  2470. self.initBrowse($container);
  2471. return $container;
  2472. },
  2473. refreshContainer: function () {
  2474. var self = this, $container = self.$container;
  2475. $container.before(self.$element);
  2476. $container.html(self.renderMain());
  2477. self.initBrowse($container);
  2478. },
  2479. renderMain: function () {
  2480. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : 'file-drop-disabled',
  2481. close = !self.showClose ? '' : self.getLayoutTemplate('close'),
  2482. preview = !self.showPreview ? '' : self.getLayoutTemplate('preview')
  2483. .replace(/\{class}/g, self.previewClass)
  2484. .replace(/\{dropClass}/g, dropCss),
  2485. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  2486. caption = self.captionTemplate.replace(/\{class}/g, css + ' kv-fileinput-caption');
  2487. return self.mainTemplate.replace(/\{class}/g, self.mainClass)
  2488. .replace(/\{preview}/g, preview)
  2489. .replace(/\{close}/g, close)
  2490. .replace(/\{caption}/g, caption)
  2491. .replace(/\{upload}/g, self.renderButton('upload'))
  2492. .replace(/\{remove}/g, self.renderButton('remove'))
  2493. .replace(/\{cancel}/g, self.renderButton('cancel'))
  2494. .replace(/\{browse}/g, self.renderButton('browse'));
  2495. },
  2496. renderButton: function (type) {
  2497. var self = this, tmplt = self.getLayoutTemplate('btnDefault'), css = self[type + 'Class'],
  2498. title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'],
  2499. status = self.isDisabled ? ' disabled' : '', btnType = 'button';
  2500. switch (type) {
  2501. case 'remove':
  2502. if (!self.showRemove) {
  2503. return '';
  2504. }
  2505. break;
  2506. case 'cancel':
  2507. if (!self.showCancel) {
  2508. return '';
  2509. }
  2510. css += ' hide';
  2511. break;
  2512. case 'upload':
  2513. if (!self.showUpload) {
  2514. return '';
  2515. }
  2516. if (self.isUploadable && !self.isDisabled) {
  2517. tmplt = self.getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl);
  2518. } else {
  2519. btnType = 'submit';
  2520. }
  2521. break;
  2522. case 'browse':
  2523. tmplt = self.getLayoutTemplate('btnBrowse');
  2524. break;
  2525. default:
  2526. return '';
  2527. }
  2528. css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button';
  2529. if (!isEmpty(label)) {
  2530. label = ' <span class="' + self.buttonLabelClass + '">' + label + '</span>';
  2531. }
  2532. return tmplt.replace('{type}', btnType)
  2533. .replace('{css}', css)
  2534. .replace('{title}', title)
  2535. .replace('{status}', status)
  2536. .replace('{icon}', icon)
  2537. .replace('{label}', label);
  2538. }
  2539. };
  2540. $.fn.fileinput = function (option) {
  2541. if (!hasFileAPISupport() && !isIE(9)) {
  2542. return;
  2543. }
  2544. var args = Array.apply(null, arguments), retvals = [];
  2545. args.shift();
  2546. this.each(function () {
  2547. var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option,
  2548. lang = options.language || self.data('language') || 'en', loc = {}, opts;
  2549. if (!data) {
  2550. if (lang !== 'en' && !isEmpty($.fn.fileinputLocales[lang])) {
  2551. loc = $.fn.fileinputLocales[lang];
  2552. }
  2553. opts = $.extend(true, {}, $.fn.fileinput.defaults, $.fn.fileinputLocales.en, loc, options, self.data());
  2554. data = new FileInput(this, opts);
  2555. self.data('fileinput', data);
  2556. }
  2557. if (typeof option === 'string') {
  2558. retvals.push(data[option].apply(data, args));
  2559. }
  2560. });
  2561. switch (retvals.length) {
  2562. case 0:
  2563. return this;
  2564. case 1:
  2565. return retvals[0];
  2566. default:
  2567. return retvals;
  2568. }
  2569. };
  2570. $.fn.fileinput.defaults = {
  2571. language: 'en',
  2572. showCaption: true,
  2573. showPreview: true,
  2574. showRemove: true,
  2575. showUpload: true,
  2576. showCancel: true,
  2577. showClose: true,
  2578. showUploadedThumbs: true,
  2579. autoReplace: false,
  2580. mainClass: '',
  2581. previewClass: '',
  2582. captionClass: '',
  2583. mainTemplate: null,
  2584. initialCaption: '',
  2585. initialPreview: [],
  2586. initialPreviewDelimiter: '*$$*',
  2587. initialPreviewConfig: [],
  2588. initialPreviewThumbTags: [],
  2589. previewThumbTags: {},
  2590. initialPreviewShowDelete: true,
  2591. removeFromPreviewOnError: true,
  2592. deleteUrl: '',
  2593. deleteExtraData: {},
  2594. overwriteInitial: true,
  2595. layoutTemplates: defaultLayoutTemplates,
  2596. previewTemplates: defaultPreviewTemplates,
  2597. allowedPreviewTypes: defaultPreviewTypes,
  2598. allowedPreviewMimeTypes: null,
  2599. allowedFileTypes: null,
  2600. allowedFileExtensions: null,
  2601. defaultPreviewContent: null,
  2602. customLayoutTags: {},
  2603. customPreviewTags: {},
  2604. previewSettings: defaultPreviewSettings,
  2605. fileTypeSettings: defaultFileTypeSettings,
  2606. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  2607. previewFileIconClass: 'file-icon-4x',
  2608. previewFileIconSettings: {},
  2609. previewFileExtSettings: {},
  2610. buttonLabelClass: 'hidden-xs',
  2611. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i>',
  2612. browseClass: 'btn btn-primary',
  2613. removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
  2614. removeClass: 'btn btn-default',
  2615. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i>',
  2616. cancelClass: 'btn btn-default',
  2617. uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
  2618. uploadClass: 'btn btn-default',
  2619. uploadUrl: null,
  2620. uploadAsync: true,
  2621. uploadExtraData: {},
  2622. minImageWidth: null,
  2623. minImageHeight: null,
  2624. maxImageWidth: null,
  2625. maxImageHeight: null,
  2626. resizeImage: false,
  2627. resizePreference: 'width',
  2628. resizeQuality: 0.92,
  2629. resizeDefaultImageType: 'image/jpeg',
  2630. maxFileSize: 0,
  2631. minFileCount: 0,
  2632. maxFileCount: 0,
  2633. validateInitialCount: false,
  2634. msgValidationErrorClass: 'text-danger',
  2635. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  2636. msgErrorClass: 'file-error-message',
  2637. progressThumbClass: "progress-bar progress-bar-success progress-bar-striped active",
  2638. progressClass: "progress-bar progress-bar-success progress-bar-striped active",
  2639. progressCompleteClass: "progress-bar progress-bar-success",
  2640. previewFileType: 'image',
  2641. zoomIndicator: '<i class="glyphicon glyphicon-zoom-in"></i>',
  2642. elCaptionContainer: null,
  2643. elCaptionText: null,
  2644. elPreviewContainer: null,
  2645. elPreviewImage: null,
  2646. elPreviewStatus: null,
  2647. elErrorContainer: null,
  2648. errorCloseButton: '<span class="close kv-error-close">&times;</span>',
  2649. slugCallback: null,
  2650. dropZoneEnabled: true,
  2651. dropZoneTitleClass: 'file-drop-zone-title',
  2652. fileActionSettings: {},
  2653. otherActionButtons: '',
  2654. textEncoding: 'UTF-8',
  2655. ajaxSettings: {},
  2656. ajaxDeleteSettings: {},
  2657. showAjaxErrorDetails: true
  2658. };
  2659. $.fn.fileinputLocales.en = {
  2660. fileSingle: 'file',
  2661. filePlural: 'files',
  2662. browseLabel: 'Browse &hellip;',
  2663. removeLabel: 'Remove',
  2664. removeTitle: 'Clear selected files',
  2665. cancelLabel: 'Cancel',
  2666. cancelTitle: 'Abort ongoing upload',
  2667. uploadLabel: 'Upload',
  2668. uploadTitle: 'Upload selected files',
  2669. msgZoomTitle: 'View details',
  2670. msgZoomModalHeading: 'Detailed Preview',
  2671. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
  2672. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
  2673. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
  2674. msgFileNotFound: 'File "{name}" not found!',
  2675. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  2676. msgFileNotReadable: 'File "{name}" is not readable.',
  2677. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  2678. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  2679. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  2680. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  2681. msgUploadAborted: 'The file upload was aborted',
  2682. msgValidationError: 'File Upload Error',
  2683. msgLoading: 'Loading file {index} of {files} &hellip;',
  2684. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  2685. msgSelected: '{n} {files} selected',
  2686. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  2687. msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
  2688. msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
  2689. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
  2690. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
  2691. msgImageResizeError: 'Could not get the image dimensions to resize.',
  2692. msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>',
  2693. dropZoneTitle: 'Drag & drop files here &hellip;'
  2694. };
  2695. $.fn.fileinput.Constructor = FileInput;
  2696. /**
  2697. * Convert automatically file inputs with class 'file' into a bootstrap fileinput control.
  2698. */
  2699. $(document).ready(function () {
  2700. var $input = $('input.file[type=file]');
  2701. if ($input.length) {
  2702. $input.fileinput();
  2703. }
  2704. });
  2705. }));