fileinput.js 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669
  1. /*!
  2. * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2015
  3. * @version 4.1.5
  4. *
  5. * File input styled for Bootstrap 3.0 that utilizes HTML5 File Input's advanced
  6. * features including the FileReader API.
  7. *
  8. * The plugin drastically enhances the HTML file input to preview multiple files on the client before
  9. * upload. In addition it provides the ability to preview content of images, text, videos, audio, html,
  10. * flash and other objects. It also offers the ability to upload and delete files using AJAX, and add
  11. * files in batches (i.e. preview, append, or remove before upload).
  12. *
  13. * Author: Kartik Visweswaran
  14. * Copyright: 2015, Kartik Visweswaran, Krajee.com
  15. * For more JQuery plugins visit http://plugins.krajee.com
  16. * For more Yii related demos visit http://demos.krajee.com
  17. */
  18. (function ($) {
  19. var isIE = function(ver) {
  20. var div = document.createElement("div"), status;
  21. div.innerHTML = "<!--[if IE " + ver + "]><i></i><![endif]-->";
  22. status = (div.getElementsByTagName("i").length == 1);
  23. document.body.appendChild(div);
  24. div.parentNode.removeChild(div);
  25. return status;
  26. },
  27. hasFileAPISupport = function () {
  28. return window.File && window.FileReader;
  29. },
  30. hasDragDropSupport = function() {
  31. var $div = document.createElement('div');
  32. return !isIE(9) && (('draggable' in $div) || ('ondragstart' in $div && 'ondrop' in $div));
  33. },
  34. hasFileUploadSupport = function () {
  35. return hasFileAPISupport && window.FormData;
  36. },
  37. addCss = function($el, css) {
  38. $el.removeClass(css).addClass(css);
  39. },
  40. STYLE_SETTING = 'style="width:{width};height:{height};"',
  41. OBJECT_PARAMS = ' <param name="controller" value="true" />\n' +
  42. ' <param name="allowFullScreen" value="true" />\n' +
  43. ' <param name="allowScriptAccess" value="always" />\n' +
  44. ' <param name="autoPlay" value="false" />\n' +
  45. ' <param name="autoStart" value="false" />\n'+
  46. ' <param name="quality" value="high" />\n',
  47. DEFAULT_PREVIEW = '<div class="file-preview-other">\n' +
  48. ' <i class="glyphicon glyphicon-file"></i>\n' +
  49. ' </div>';
  50. var defaultFileActionSettings = {
  51. removeIcon: '<i class="glyphicon glyphicon-trash text-danger"></i>',
  52. removeClass: 'btn btn-xs btn-default',
  53. removeTitle: 'Remove file',
  54. uploadIcon: '<i class="glyphicon glyphicon-upload text-info"></i>',
  55. uploadClass: 'btn btn-xs btn-default',
  56. uploadTitle: 'Upload file',
  57. indicatorNew: '<i class="glyphicon glyphicon-hand-down text-warning"></i>',
  58. indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign file-icon-large text-success"></i>',
  59. indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>',
  60. indicatorLoading: '<i class="glyphicon glyphicon-hand-up text-muted"></i>',
  61. indicatorNewTitle: 'Not uploaded yet',
  62. indicatorSuccessTitle: 'Uploaded',
  63. indicatorErrorTitle: 'Upload Error',
  64. indicatorLoadingTitle: 'Uploading ...'
  65. };
  66. var defaultLayoutTemplates = {
  67. main1: '{preview}\n' +
  68. '<div class="kv-upload-progress hide"></div>\n' +
  69. '<div class="input-group {class}">\n' +
  70. ' {caption}\n' +
  71. ' <div class="input-group-btn">\n' +
  72. ' {remove}\n' +
  73. ' {cancel}\n' +
  74. ' {upload}\n' +
  75. ' {browse}\n' +
  76. ' </div>\n' +
  77. '</div>',
  78. main2: '{preview}\n<div class="kv-upload-progress hide"></div>\n{remove}\n{cancel}\n{upload}\n{browse}\n',
  79. preview: '<div class="file-preview {class}">\n' +
  80. ' <div class="close fileinput-remove">&times;</div>\n' +
  81. ' <div class="{dropClass}">\n' +
  82. ' <div class="file-preview-thumbnails">\n' +
  83. ' </div>\n' +
  84. ' <div class="clearfix"></div>' +
  85. ' <div class="file-preview-status text-center text-success"></div>\n' +
  86. ' <div class="kv-fileinput-error"></div>\n' +
  87. ' </div>\n' +
  88. '</div>',
  89. icon: '<span class="glyphicon glyphicon-file kv-caption-icon"></span>',
  90. caption: '<div tabindex="-1" class="form-control file-caption {class}">\n' +
  91. ' <div class="file-caption-name"></div>\n' +
  92. '</div>',
  93. modal: '<div id="{id}" class="modal fade">\n' +
  94. ' <div class="modal-dialog modal-lg">\n' +
  95. ' <div class="modal-content">\n' +
  96. ' <div class="modal-header">\n' +
  97. ' <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>\n' +
  98. ' <h3 class="modal-title">Detailed Preview <small>{title}</small></h3>\n' +
  99. ' </div>\n' +
  100. ' <div class="modal-body">\n' +
  101. ' <textarea class="form-control" style="font-family:Monaco,Consolas,monospace; height: {height}px;" readonly>{body}</textarea>\n' +
  102. ' </div>\n' +
  103. ' </div>\n' +
  104. ' </div>\n' +
  105. '</div>',
  106. progress: '<div class="progress">\n' +
  107. ' <div class="progress-bar progress-bar-success progress-bar-striped text-center" role="progressbar" aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' +
  108. ' {percent}%\n' +
  109. ' </div>\n' +
  110. '</div>',
  111. footer: '<div class="file-thumbnail-footer">\n' +
  112. ' <div class="file-caption-name" style="width:{width}">{caption}</div>\n' +
  113. ' {actions}\n' +
  114. '</div>',
  115. actions: '<div class="file-actions">\n' +
  116. ' <div class="file-footer-buttons">\n' +
  117. ' {upload}{delete}{other}' +
  118. ' </div>\n' +
  119. ' <div class="file-upload-indicator" tabindex="-1" title="{indicatorTitle}">{indicator}</div>\n' +
  120. ' <div class="clearfix"></div>\n' +
  121. '</div>',
  122. actionDelete: '<button type="button" class="kv-file-remove {removeClass}" title="{removeTitle}"{dataUrl}{dataKey}>{removeIcon}</button>\n',
  123. actionUpload: '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">{uploadIcon}</button>\n'
  124. };
  125. var defaultPreviewTypes = ['image', 'html', 'text', 'video', 'audio', 'flash', 'object'];
  126. var defaultPreviewTemplates = {
  127. generic: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  128. ' {content}\n' +
  129. ' {footer}\n' +
  130. '</div>\n',
  131. html: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  132. ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  133. ' ' + DEFAULT_PREVIEW + '\n' +
  134. ' </object>\n' +
  135. ' {footer}\n' +
  136. '</div>',
  137. image: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  138. ' <img src="{data}" class="file-preview-image" title="{caption}" alt="{caption}" ' + STYLE_SETTING + '>\n' +
  139. ' {footer}\n' +
  140. '</div>\n',
  141. text: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  142. ' <div class="file-preview-text" title="{caption}" ' + STYLE_SETTING + '>\n' +
  143. ' {data}\n' +
  144. ' </div>\n' +
  145. ' {footer}\n' +
  146. '</div>\n',
  147. video: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}" title="{caption}" ' + STYLE_SETTING + '>\n' +
  148. ' <video width="{width}" height="{height}" controls>\n' +
  149. ' <source src="{data}" type="{type}">\n' +
  150. ' ' + DEFAULT_PREVIEW + '\n' +
  151. ' </video>\n' +
  152. ' {footer}\n' +
  153. '</div>\n',
  154. audio: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}" title="{caption}" ' + STYLE_SETTING + '>\n' +
  155. ' <audio controls>\n' +
  156. ' <source src="{data}" type="{type}">\n' +
  157. ' ' + DEFAULT_PREVIEW + '\n' +
  158. ' </audio>\n' +
  159. ' {footer}\n' +
  160. '</div>\n',
  161. flash: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}" title="{caption}" ' + STYLE_SETTING + '>\n' +
  162. ' <object type="application/x-shockwave-flash" width="{width}" height="{height}" data="{data}">\n' +
  163. OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' +
  164. ' </object>\n' +
  165. ' {footer}\n' +
  166. '</div>\n',
  167. object: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}" title="{caption}" ' + STYLE_SETTING + '>\n' +
  168. ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  169. ' <param name="movie" value="{caption}" />\n' +
  170. OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' +
  171. ' </object>\n' +
  172. ' {footer}\n' +
  173. '</div>',
  174. other: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}" title="{caption}" ' + STYLE_SETTING + '>\n' +
  175. ' ' + DEFAULT_PREVIEW + '\n' +
  176. ' {footer}\n' +
  177. '</div>',
  178. };
  179. var defaultPreviewSettings = {
  180. image: {width: "auto", height: "160px"},
  181. html: {width: "213px", height: "160px"},
  182. text: {width: "160px", height: "160px"},
  183. video: {width: "213px", height: "160px"},
  184. audio: {width: "213px", height: "80px"},
  185. flash: {width: "213px", height: "160px"},
  186. object: {width: "160px", height: "160px"},
  187. other: {width: "160px", height: "160px"}
  188. };
  189. var defaultFileTypeSettings = {
  190. image: function(vType, vName) {
  191. return (typeof vType !== "undefined") ? vType.match('image.*') : vName.match(/\.(gif|png|jpe?g)$/i);
  192. },
  193. html: function(vType, vName) {
  194. return (typeof vType !== "undefined") ? vType == 'text/html' : vName.match(/\.(htm|html)$/i);
  195. },
  196. text: function(vType, vName) {
  197. return typeof vType !== "undefined" && vType.match('text.*') || vName.match(/\.(txt|md|csv|nfo|php|ini)$/i);
  198. },
  199. video: function (vType, vName) {
  200. return typeof vType !== "undefined" && vType.match(/\.video\/(ogg|mp4|webm)$/i) || vName.match(/\.(og?|mp4|webm)$/i);
  201. },
  202. audio: function (vType, vName) {
  203. return typeof vType !== "undefined" && vType.match(/\.audio\/(ogg|mp3|wav)$/i) || vName.match(/\.(ogg|mp3|wav)$/i);
  204. },
  205. flash: function (vType, vName) {
  206. return typeof vType !== "undefined" && vType == 'application/x-shockwave-flash' || vName.match(/\.(swf)$/i);
  207. },
  208. object: function (vType, vName) {
  209. return true;
  210. },
  211. other: function (vType, vName) {
  212. return true;
  213. },
  214. };
  215. var isEmpty = function (value, trim) {
  216. return value === null || value === undefined || value == []
  217. || value === '' || trim && $.trim(value) === '';
  218. },
  219. isArray = function (a) {
  220. return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]';
  221. },
  222. isSet = function (needle, haystack) {
  223. return (typeof haystack == 'object' && needle in haystack);
  224. },
  225. getValue = function (options, param, value) {
  226. return (isEmpty(options) || isEmpty(options[param])) ? value : options[param];
  227. },
  228. getElement = function (options, param, value) {
  229. return (isEmpty(options) || isEmpty(options[param])) ? value : $(options[param]);
  230. },
  231. uniqId = function () {
  232. return Math.round(new Date().getTime() + (Math.random() * 100));
  233. },
  234. htmlEncode = function(str) {
  235. return String(str)
  236. .replace(/&/g, '&amp;')
  237. .replace(/"/g, '&quot;')
  238. .replace(/'/g, '&#39;')
  239. .replace(/</g, '&lt;')
  240. .replace(/>/g, '&gt;');
  241. },
  242. vUrl = window.URL || window.webkitURL;
  243. var FileInput = function (element, options) {
  244. this.$element = $(element);
  245. if (hasFileAPISupport() || isIE(9)) {
  246. this.init(options);
  247. this.listen();
  248. } else {
  249. this.$element.removeClass('file-loading');
  250. }
  251. };
  252. FileInput.prototype = {
  253. constructor: FileInput,
  254. init: function (options) {
  255. var self = this, $el = self.$element;
  256. for (key in options) {
  257. self[key] = options[key];
  258. }
  259. if (isEmpty(self.allowedPreviewTypes)) {
  260. self.allowedPreviewTypes = defaultPreviewTypes;
  261. }
  262. self.uploadFileAttr = !isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data';
  263. self.reader = null;
  264. self.formdata = {};
  265. self.isIE9 = isIE(9);
  266. self.isIE10 = isIE(10);
  267. self.filestack = [];
  268. self.ajaxRequests = [];
  269. self.isError = false;
  270. self.dropZoneEnabled = hasDragDropSupport() && self.dropZoneEnabled;
  271. self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly');
  272. self.isUploadable = hasFileUploadSupport && !isEmpty(self.uploadUrl);
  273. self.slug = typeof options.slugCallback == "function" ? options.slugCallback : self.slugDefault;
  274. self.mainTemplate = self.showCaption ? self.getLayoutTemplate('main1') : self.getLayoutTemplate('main2');
  275. self.captionTemplate = self.getLayoutTemplate('caption');
  276. self.previewGenericTemplate = self.getPreviewTemplate('generic');
  277. if (isEmpty(self.$element.attr('id'))) {
  278. self.$element.attr('id', uniqId());
  279. }
  280. if (typeof self.$container == 'undefined') {
  281. self.$container = self.createContainer();
  282. } else {
  283. self.refreshContainer();
  284. }
  285. self.$progress = self.$container.find('.kv-upload-progress');
  286. self.$btnUpload = self.$container.find('.kv-fileinput-upload')
  287. self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption'));
  288. self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name'));
  289. self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview'));
  290. self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails'));
  291. self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status'));
  292. self.$errorContainer = getElement(options, 'elErrorContainer', self.$previewContainer.find('.kv-fileinput-error'));
  293. if (!isEmpty(self.msgErrorClass)) {
  294. addCss(self.$errorContainer, self.msgErrorClass);
  295. }
  296. self.$errorContainer.hide();
  297. self.initialPreviewContent = '';
  298. var content = self.initialPreview;
  299. self.initialPreviewCount = isArray(content) ? content.length : (content.length > 0 ? content.split(self.initialPreviewDelimiter).length : 0);
  300. self.fileActionSettings = $.extend(defaultFileActionSettings, options.fileActionSettings);
  301. self.previewInitId = "preview-" + uniqId();
  302. self.initPreview();
  303. self.initPreviewDeletes();
  304. self.original = {
  305. preview: self.$preview.html(),
  306. caption: self.$caption.html()
  307. };
  308. self.autoSizeCaption();
  309. self.options = options;
  310. self.setFileDropZoneTitle();
  311. self.uploadCount = 0;
  312. self.uploadPercent = 0;
  313. self.$element.removeClass('file-loading');
  314. },
  315. raise: function(event) {
  316. var self = this;
  317. if (arguments.length > 1) {
  318. self.$element.trigger(event, arguments[1]);
  319. } else {
  320. self.$element.trigger(event);
  321. }
  322. },
  323. getLayoutTemplate: function(t) {
  324. var self = this;
  325. return isSet(t, self.layoutTemplates) ? self.layoutTemplates[t] : defaultLayoutTemplates[t];
  326. },
  327. getPreviewTemplate: function(t) {
  328. var self = this;
  329. return isSet(t, self.previewTemplates) ? self.previewTemplates[t] : defaultPreviewTemplates[t];
  330. },
  331. getOutData: function () {
  332. var self = this, jqXHR = arguments.length > 0 ? arguments[0] : {},
  333. responsedata = arguments.length > 1 ? arguments[1] : {},
  334. filesdata = arguments.length > 2 ? arguments[2] : self.filestack;
  335. return {
  336. form: self.formdata,
  337. files: filesdata,
  338. extra: self.getExtraData(),
  339. response: responsedata,
  340. reader: self.reader,
  341. jqXHR: jqXHR
  342. };
  343. },
  344. listen: function () {
  345. var self = this, $el = self.$element, $cap = self.$captionContainer, $btnFile = self.$btnFile;
  346. $el.on('change', $.proxy(self.change, self));
  347. $(window).off('resize').on('resize', function() {
  348. setTimeout(function() {
  349. self.autoSizeCaption();
  350. }, 50);
  351. });
  352. $btnFile.off('click').on('click', function (ev) {
  353. self.raise('filebrowse');
  354. if (self.isError && !self.isUploadable) {
  355. self.clear(false);
  356. }
  357. $cap.focus();
  358. });
  359. $el.closest('form').off('reset').on('reset', $.proxy(self.reset, self));
  360. self.$container.off('click')
  361. .on('click', '.fileinput-remove:not([disabled])', $.proxy(self.clear, self))
  362. .on('click', '.fileinput-cancel', $.proxy(self.cancel, self));
  363. if (self.isUploadable && self.dropZoneEnabled && self.showPreview) {
  364. self.initDragDrop();
  365. }
  366. if (!self.isUploadable) {
  367. return;
  368. }
  369. self.$container.find('.kv-fileinput-upload').off('click').on('click', function(e) {
  370. if (!self.isUploadable) {
  371. return;
  372. }
  373. e.preventDefault();
  374. var totLen = self.getFileStack().length;
  375. if (self.isDisabled || $(this).hasClass('disabled') || !isEmpty($(this).attr('disabled')) || totLen == 0) {
  376. return;
  377. }
  378. self.resetUpload();
  379. self.$progress.removeClass('hide');
  380. self.uploadCount = 0;
  381. self.uploadPercent = 0;
  382. var i, len = self.filestack.length, template = self.getLayoutTemplate('progress');
  383. self.lock();
  384. self.setProgress(0);
  385. if ((self.uploadAsync || totLen == 1) && self.showPreview) {
  386. var outData = self.getOutData();
  387. self.raise('filebatchpreupload', [outData]);
  388. for (i = 0; i < len; i++) {
  389. if (self.filestack[i] !== undefined) {
  390. self.upload(i, self.getFileStack(), true);
  391. }
  392. }
  393. setTimeout(function() {
  394. $(document).ajaxStop(function() {
  395. self.setProgress(100);
  396. self.$preview.find('file-preview-frame').removeClass('file-loading');
  397. self.unlock();
  398. self.clearFileInput();
  399. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  400. });
  401. }, 100);
  402. return;
  403. }
  404. self.uploadBatch();
  405. });
  406. },
  407. setProgress: function(percent) {
  408. var self = this, template = self.getLayoutTemplate('progress'), pct = Math.min(percent, 100);
  409. self.$progress.html(template.replace(/\{percent\}/g, pct));
  410. },
  411. lock: function() {
  412. var self = this;
  413. self.resetErrors();
  414. self.disable();
  415. if (self.showRemove) {
  416. addCss(self.$container.find('.fileinput-remove'), 'hide');
  417. }
  418. if (self.showCancel) {
  419. self.$container.find('.fileinput-cancel').removeClass('hide');
  420. }
  421. self.raise('filelock', [self.filestack, self.getExtraData()]);
  422. },
  423. unlock: function() {
  424. var self = this;
  425. self.enable();
  426. if (self.showCancel) {
  427. addCss(self.$container.find('.fileinput-cancel'), 'hide');
  428. }
  429. if (self.showRemove) {
  430. self.$container.find('.fileinput-remove').removeClass('hide');
  431. }
  432. self.raise('fileunlock', [self.filestack, self.getExtraData()]);
  433. },
  434. refresh: function (options) {
  435. var self = this, $el = self.$element,
  436. params = (arguments.length) ? $.extend(self.options, options) : self.options;
  437. $el.off();
  438. self.init(params);
  439. var $zone = self.$container.find('.file-drop-zone');
  440. $zone.off('dragenter dragover drop');
  441. $(document).off('dragenter dragover drop');
  442. self.listen();
  443. self.setFileDropZoneTitle();
  444. },
  445. initDragDrop: function() {
  446. var self = this, $zone = self.$container.find('.file-drop-zone');
  447. $zone.off('dragenter dragover drop');
  448. $(document).off('dragenter dragover drop');
  449. $zone.on('dragenter dragover', function (e) {
  450. e.stopPropagation();
  451. e.preventDefault();
  452. if (self.isDisabled) {
  453. return;
  454. }
  455. addCss($(this), 'highlighted');
  456. });
  457. $zone.on('dragleave', function (e) {
  458. e.stopPropagation();
  459. e.preventDefault();
  460. if (self.isDisabled) {
  461. return;
  462. }
  463. $(this).removeClass('highlighted');
  464. });
  465. $zone.on('drop', function (e) {
  466. e.preventDefault();
  467. if (self.isDisabled) {
  468. return;
  469. }
  470. self.change(e, 'dragdrop');
  471. $(this).removeClass('highlighted');
  472. });
  473. $(document).on('dragenter dragover drop', function (e) {
  474. e.stopPropagation();
  475. e.preventDefault();
  476. });
  477. },
  478. setFileDropZoneTitle: function() {
  479. var self = this, $zone = self.$container.find('.file-drop-zone');
  480. $zone.find('.' + self.dropZoneTitleClass).remove();
  481. if (!self.isUploadable || !self.showPreview ||
  482. $zone.length == 0 || self.getFileStack().length > 0 ||
  483. !self.dropZoneEnabled) {
  484. return;
  485. }
  486. if ($zone.find('.file-preview-frame').length == 0) {
  487. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + self.dropZoneTitle + '</div>');
  488. }
  489. self.$container.removeClass('file-input-new');
  490. },
  491. initFileActions: function() {
  492. var self = this;
  493. self.$preview.find('.kv-file-remove').each(function() {
  494. var $el = $(this), $frame = $el.closest('.file-preview-frame'),
  495. ind = $frame.attr('data-fileindex');
  496. $el.off('click').on('click', function() {
  497. $frame.fadeOut('slow', function() {
  498. self.filestack[ind] = undefined;
  499. self.clearObjects($frame);
  500. $frame.remove();
  501. var filestack = self.getFileStack(), len = filestack.length,
  502. chk = self.$container.find('.file-preview-initial').length;
  503. if (len == 0 && chk == 0) {
  504. self.original.preview = '';
  505. self.reset();
  506. } else {
  507. var n = self.initialPreviewCount + len,
  508. cap = n > 1 ? self.msgSelected.replace(/\{n\}/g, n) : filestack[0].name;
  509. self.setCaption(cap);
  510. }
  511. });
  512. });
  513. });
  514. self.$preview.find('.kv-file-upload').each(function() {
  515. var $el = $(this);
  516. $el.off('click').on('click', function() {
  517. var $frame = $el.closest('.file-preview-frame'),
  518. ind = $frame.attr('data-fileindex');
  519. self.upload(ind, self.filestack);
  520. });
  521. });
  522. },
  523. renderInitFileFooter: function(i) {
  524. var self = this, hasConfig = self.initialPreviewConfig.length > 0,
  525. template = self.getLayoutTemplate('footer');
  526. if (hasConfig && !isEmpty(self.initialPreviewConfig[i])) {
  527. var config = self.initialPreviewConfig[i],
  528. caption = ('caption' in config) ? config.caption : '',
  529. width = ('width' in config) ? config.width : 'auto',
  530. url = ('url' in config) ? config.url : false,
  531. key = ('key' in config) ? config.key : null,
  532. disabled = url === false ? true : false,
  533. actions = self.initialPreviewShowDelete ? self.renderFileActions(false, true, disabled, url, key) : '',
  534. footer = template.replace(/\{actions\}/g, actions);
  535. return footer.replace(/\{caption\}/g, caption).replace(/\{width\}/g, width)
  536. .replace(/\{indicator\}/g, '').replace(/\{indicatorTitle\}/g, '');
  537. }
  538. return '';
  539. },
  540. renderFileFooter: function(caption, width) {
  541. var self = this, config = self.fileActionSettings,
  542. template = self.getLayoutTemplate('footer');
  543. if (self.isUploadable) {
  544. var footer = template.replace(/\{actions\}/g, self.renderFileActions(true, true, false, false, false));
  545. return footer.replace(/\{caption\}/g, caption).replace(/\{width\}/g, width)
  546. .replace(/\{indicator\}/g, config.indicatorNew).replace(/\{indicatorTitle\}/g, config.indicatorNewTitle);
  547. } else {
  548. return template.replace(/\{actions\}/g, '').replace(/\{caption\}/g, caption).replace(/\{width\}/g, width)
  549. .replace(/\{indicator\}/g, '').replace(/\{indicatorTitle\}/g, '');
  550. }
  551. return '';
  552. },
  553. renderFileActions: function(showUpload, showDelete, disabled, url, key) {
  554. if (!showUpload && !showDelete) {
  555. return '';
  556. }
  557. var self = this,
  558. vUrl = url == false ? '' : ' data-url="' + url + '"',
  559. vKey = key == false ? '' : ' data-key="' + key + '"',
  560. btnDelete = self.getLayoutTemplate('actionDelete'),
  561. btnUpload = '',
  562. template = self.getLayoutTemplate('actions'),
  563. otherActionButtons = self.otherActionButtons.replace(/\{dataKey\}/g, vKey),
  564. config = self.fileActionSettings,
  565. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  566. btnDelete = btnDelete
  567. .replace(/\{removeClass\}/g, removeClass)
  568. .replace(/\{removeIcon\}/g, config.removeIcon)
  569. .replace(/\{removeTitle\}/g, config.removeTitle)
  570. .replace(/\{dataUrl\}/g, vUrl)
  571. .replace(/\{dataKey\}/g, vKey);
  572. if (showUpload) {
  573. btnUpload = self.getLayoutTemplate('actionUpload')
  574. .replace(/\{uploadClass\}/g, config.uploadClass)
  575. .replace(/\{uploadIcon\}/g, config.uploadIcon)
  576. .replace(/\{uploadTitle\}/g, config.uploadTitle);
  577. }
  578. return template
  579. .replace(/\{delete\}/g, btnDelete)
  580. .replace(/\{upload\}/g, btnUpload)
  581. .replace(/\{other\}/g, otherActionButtons);
  582. },
  583. getInitialPreview: function(template, content, i) {
  584. var self = this, ind = 'init_' + i,
  585. previewId = self.previewInitId + '-' + ind;
  586. footer = self.renderInitFileFooter(i, false);
  587. return template
  588. .replace(/\{previewId\}/g, previewId)
  589. .replace(/\{frameClass\}/g, ' file-preview-initial')
  590. .replace(/\{fileindex\}/g, ind)
  591. .replace(/\{content\}/g, content)
  592. .replace(/\{footer\}/g, footer);
  593. },
  594. initPreview: function () {
  595. var self = this, html = '', content = self.initialPreview, len = self.initialPreviewCount,
  596. cap = self.initialCaption.length, previewId = self.previewInitId + '-init_' + i;
  597. caption = (cap > 0) ? self.initialCaption : self.msgSelected.replace(/\{n\}/g, len);
  598. if (isArray(content) && len > 0) {
  599. for (var i = 0; i < len; i++) {
  600. html += self.getInitialPreview(self.previewGenericTemplate, content[i], i);
  601. }
  602. if (len > 1 && cap == 0) {
  603. caption = self.msgSelected.replace(/\{n\}/g, len);
  604. }
  605. } else {
  606. if (len > 0) {
  607. var fileList = content.split(self.initialPreviewDelimiter);
  608. for (var i = 0; i < len; i++) {
  609. html += self.getInitialPreview(self.previewGenericTemplate, content[i], i);
  610. }
  611. if (len > 1 && cap == 0) {
  612. caption = self.msgSelected.replace(/\{n\}/g, len);
  613. }
  614. } else {
  615. if (cap > 0) {
  616. self.setCaption(caption);
  617. return;
  618. } else {
  619. return;
  620. }
  621. }
  622. }
  623. self.initialPreviewContent = html;
  624. self.$preview.html(html);
  625. self.setCaption(caption);
  626. self.$container.removeClass('file-input-new');
  627. },
  628. initPreviewDeletes: function() {
  629. var self = this,
  630. resetProgress = function() {
  631. if (self.$preview.find('.kv-file-remove').length == 0) {
  632. self.reset();
  633. }
  634. };
  635. self.$preview.find('.kv-file-remove').each(function() {
  636. var $el = $(this), $frame = $el.closest('.file-preview-frame'),
  637. vUrl = $el.attr('data-url'), vKey = $el.attr('data-key'),
  638. $content = $(self.initialPreviewContent);
  639. if (vUrl === undefined || vKey === undefined) {
  640. return;
  641. }
  642. $el.off('click').on('click', function() {
  643. $.ajax({
  644. url: vUrl,
  645. type: 'POST',
  646. dataType: 'json',
  647. data: {key: vKey},
  648. beforeSend: function(jqXHR) {
  649. addCss($frame, 'file-uploading');
  650. addCss($el, 'disabled');
  651. self.raise('filepredelete', [vKey, jqXHR]);
  652. },
  653. success: function(data, textStatus, jqXHR) {
  654. if(typeof data.error === 'undefined') {
  655. self.raise('filedeleted', [vKey, jqXHR]);
  656. } else {
  657. self.showError(data.error, null, $el.attr('id'), key, 'filedeleteerror', jqXHR);
  658. resetProgress();
  659. }
  660. $frame.removeClass('file-uploading').addClass('file-deleted');
  661. $frame.fadeOut('slow', function() {
  662. self.clearObjects($frame);
  663. $frame.remove();
  664. var $content = $(document.createElement('div')).html(self.original.preview);
  665. $content.find('.file-preview-frame').each(function() {
  666. var $el = $(this);
  667. if ($el.find('.kv-file-remove').attr('data-key') == vKey) {
  668. $el.remove();
  669. }
  670. });
  671. self.initialPreviewContent = $content.html();
  672. if (self.initialPreviewCount > 0) {
  673. self.initialPreviewCount--;
  674. }
  675. var caption = (self.initialCaption.length > 0) ?
  676. self.initialCaption :
  677. self.msgSelected.replace(/\{n\}/g, self.initialPreviewCount);
  678. self.original.preview = $content.html();
  679. self.setCaption(caption);
  680. self.original.caption = self.$caption.html();
  681. $content.remove();
  682. resetProgress();
  683. });
  684. },
  685. error: function(jqXHR, textStatus, errorThrown) {
  686. self.showError(errorThrown, null, $el.attr('id'), key, 'filedeleteerror', jqXHR);
  687. $frame.removeClass('file-uploading');
  688. resetProgress();
  689. }
  690. });
  691. });
  692. });
  693. },
  694. clearObjects: function($el) {
  695. $el.find('video audio').each(function() {
  696. this.pause();
  697. delete(this);
  698. $(this).remove();
  699. });
  700. $el.find('img object div').each(function() {
  701. delete(this);
  702. $(this).remove();
  703. });
  704. },
  705. clearFileInput: function() {
  706. var self = this, $el = self.$element;
  707. if (isEmpty($el.val())) {
  708. return;
  709. }
  710. // Fix for IE ver < 11, that does not clear file inputs
  711. // Requires a sequence of steps to prevent IE crashing but
  712. // still allow clearing of the file input.
  713. if (self.isIE9 || self.isIE10) {
  714. var $srcFrm = $el.closest('form'),
  715. $tmpFrm = $(document.createElement('form')),
  716. $tmpEl = $(document.createElement('div'));
  717. $el.before($tmpEl);
  718. if ($srcFrm.length) {
  719. $srcFrm.after($tmpFrm);
  720. } else {
  721. $tmpEl.after($tmpFrm);
  722. }
  723. $tmpFrm.append($el).trigger('reset');
  724. $tmpEl.before($el).remove();
  725. $tmpFrm.remove();
  726. } else { // normal input clear behavior for other sane browsers
  727. $el.val('');
  728. }
  729. },
  730. resetUpload: function() {
  731. var self = this;
  732. self.uploadCount = 0;
  733. self.uploadPercent = 0;
  734. self.$btnUpload.removeAttr('disabled');
  735. self.setProgress(0);
  736. addCss(self.$progress, 'hide');
  737. self.resetErrors(false);
  738. self.ajaxRequests = [];
  739. },
  740. cancel: function() {
  741. var self = this, xhr = self.ajaxRequests, len = xhr.length;
  742. if (len > 0) {
  743. for (i = 0; i < len; i++) {
  744. xhr[i].abort();
  745. }
  746. self.$preview.find('file-preview-frame').each(function() {
  747. $thumb = $(this), ind = $thumb.attr('data-fileindex');
  748. $thumb.removeClass('file-uploading');
  749. if (self.filestack[ind] !== undefined) {
  750. $thumb.find('.kv-file-upload').removeClass('disabled');
  751. $thumb.find('.kv-file-upload').removeClass('disabled');
  752. }
  753. });
  754. self.unlock();
  755. }
  756. },
  757. clear: function () {
  758. var self = this, e = arguments.length > 0 && arguments[0];
  759. if (!self.isIE9 && self.reader instanceof FileReader) {
  760. self.reader.abort();
  761. }
  762. self.$btnUpload.removeAttr('disabled');
  763. self.resetUpload();
  764. self.filestack = [];
  765. self.autoSizeCaption();
  766. self.clearFileInput();
  767. self.resetErrors(true);
  768. if (e !== false) {
  769. self.raise('change');
  770. self.raise('fileclear');
  771. }
  772. if (self.overwriteInitial) {
  773. self.initialPreviewCount = 0;
  774. self.initialPreviewContent = '';
  775. }
  776. if (!self.overwriteInitial && self.initialPreviewContent.length > 0) {
  777. self.showFileIcon();
  778. self.$preview.html(self.original.preview);
  779. self.$caption.html(self.original.caption);
  780. self.initPreviewDeletes();
  781. self.$container.removeClass('file-input-new');
  782. } else {
  783. self.$preview.find('.file-preview-frame').each(function() {
  784. self.clearObjects($(this));
  785. });
  786. self.$preview.html('');
  787. var cap = (!self.overwriteInitial && self.initialCaption.length > 0) ?
  788. self.original.caption : '';
  789. self.$caption.html(cap);
  790. self.$caption.attr('title', '');
  791. addCss(self.$container, 'file-input-new');
  792. }
  793. if (self.$container.find('.file-preview-frame').length == 0) {
  794. self.initialCaption = '';
  795. self.original.caption = '';
  796. self.$caption.html('');
  797. self.$captionContainer.find('.kv-caption-icon').hide();
  798. }
  799. self.hideFileIcon();
  800. self.raise('filecleared');
  801. self.$captionContainer.focus();
  802. self.setFileDropZoneTitle();
  803. },
  804. reset: function () {
  805. var self = this;
  806. self.clear(false);
  807. self.$preview.html(self.original.preview);
  808. self.$caption.html(self.original.caption);
  809. self.$container.find('.fileinput-filename').text('');
  810. self.raise('filereset');
  811. if (self.initialPreview.length > 0) {
  812. self.$container.removeClass('file-input-new');
  813. }
  814. self.setFileDropZoneTitle();
  815. if (self.isUploadable) {
  816. self.resetUpload();
  817. }
  818. self.filestack = [];
  819. self.formdata = {};
  820. },
  821. disable: function (e) {
  822. var self = this;
  823. self.isDisabled = true;
  824. self.$element.attr('disabled', 'disabled');
  825. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  826. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").attr("disabled", true);
  827. self.initDragDrop();
  828. },
  829. enable: function (e) {
  830. var self = this;
  831. self.isDisabled = false;
  832. self.$element.removeAttr('disabled');
  833. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  834. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").removeAttr("disabled");
  835. self.initDragDrop();
  836. },
  837. getExtraData: function() {
  838. var self = this, data = self.uploadExtraData;
  839. if (typeof(self.uploadExtraData) == "function") {
  840. data = self.uploadExtraData();
  841. }
  842. return data;
  843. },
  844. uploadExtra: function(fd) {
  845. var self = this, data = self.getExtraData();
  846. if (data.length == 0) {
  847. return;
  848. }
  849. $.each(data, function(key, value) {
  850. if (!isEmpty(key) && !isEmpty(value)) {
  851. fd.append(key, value);
  852. }
  853. });
  854. },
  855. initXhr: function(xhrobj, factor) {
  856. var self = this;
  857. if (xhrobj.upload) {
  858. xhrobj.upload.addEventListener('progress', function(event) {
  859. var pct = 0, position = event.loaded || event.position, total = event.total;
  860. if (event.lengthComputable) {
  861. pct = Math.ceil(position / total * factor);
  862. }
  863. self.uploadPercent = Math.max(pct, self.uploadPercent);
  864. self.setProgress(self.uploadPercent);
  865. }, false);
  866. }
  867. return xhrobj;
  868. },
  869. upload: function(i, files) {
  870. var self = this, total = files.length, formdata = new FormData(),
  871. previewId = self.previewInitId + "-" + i, $thumb = $('#' + previewId),
  872. $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove'),
  873. $indicator = $thumb.find('.file-upload-indicator'), config = self.fileActionSettings;
  874. self.formdata = formdata;
  875. if (total == 0) {
  876. return;
  877. }
  878. if ($btnUpload.hasClass('disabled')) {
  879. return;
  880. }
  881. var percent,
  882. allFiles = arguments.length > 2,
  883. setIndicator = function (icon, msg) {
  884. $indicator.html(config[icon]);
  885. $indicator.attr('title', config[msg]);
  886. },
  887. updateProgress = function() {
  888. if (!allFiles || total == 0 || self.uploadPercent >= 100) {
  889. return;
  890. }
  891. self.uploadCount++;
  892. var pct = 80 + Math.ceil(self.uploadCount * 20/total);
  893. self.uploadPercent = Math.max(pct, self.uploadPercent);
  894. self.setProgress(self.uploadPercent);
  895. self.initPreviewDeletes();
  896. },
  897. resetActions = function() {
  898. $btnUpload.removeAttr('disabled');
  899. $btnDelete.removeAttr('disabled');
  900. $thumb.removeClass('file-uploading');
  901. };
  902. formdata.append(self.uploadFileAttr, files[i]);
  903. formdata.append('file_id', i);
  904. self.uploadExtra(formdata);
  905. self.ajaxRequests.push($.ajax({
  906. xhr: function() {
  907. var xhrobj = $.ajaxSettings.xhr();
  908. return self.initXhr(xhrobj, 80);
  909. },
  910. url: self.uploadUrl,
  911. type: 'POST',
  912. dataType: 'json',
  913. data: formdata,
  914. cache: false,
  915. processData: false,
  916. contentType: false,
  917. beforeSend: function(jqXHR) {
  918. var outData = self.getOutData(jqXHR);
  919. setIndicator('indicatorLoading', 'indicatorLoadingTitle');
  920. addCss($thumb, 'file-uploading');
  921. $btnUpload.attr('disabled', true);
  922. $btnDelete.attr('disabled', true);
  923. if (!allFiles) {
  924. self.lock();
  925. }
  926. self.raise('filepreupload', [outData, previewId, i])
  927. },
  928. success: function(data, textStatus, jqXHR) {
  929. var outData = self.getOutData(jqXHR, data);
  930. setTimeout(function() {
  931. if(typeof data.error === 'undefined') {
  932. setIndicator('indicatorSuccess', 'indicatorSuccessTitle');
  933. $btnUpload.hide();
  934. $btnDelete.hide();
  935. self.filestack[i] = undefined;
  936. self.raise('fileuploaded', [outData, previewId, i]);
  937. } else {
  938. setIndicator('indicatorError', 'indicatorErrorTitle');
  939. self.showUploadError(data.error, outData, previewId, i);
  940. }
  941. }, 100);
  942. },
  943. complete: function() {
  944. setTimeout(function() {
  945. updateProgress();
  946. resetActions();
  947. }, 100);
  948. if (!allFiles) {
  949. self.unlock();
  950. }
  951. },
  952. error: function(jqXHR, textStatus, errorThrown) {
  953. setIndicator('indicatorError', 'indicatorErrorTitle');
  954. var outData = self.getOutData(jqXHR);
  955. if (allFiles) {
  956. var cap = files[i].name;
  957. self.showUploadError('<b>' + cap + '</b>: ' + errorThrown, outData, previewId, i);
  958. } else {
  959. self.showUploadError(errorThrown, outData, previewId, i);
  960. }
  961. }
  962. }));
  963. },
  964. uploadBatch: function() {
  965. var self = this, files = self.filestack, total = files.length, formdata = new FormData();
  966. self.formdata = formdata;
  967. if (total == 0) {
  968. return;
  969. }
  970. var config = self.fileActionSettings,
  971. setIndicator = function (i, icon, msg) {
  972. var $indicator = $('#' + self.previewInitId + "-" + i).find('.file-upload-indicator');
  973. $indicator.html(config[icon]);
  974. $indicator.attr('title', config[msg]);
  975. },
  976. enableActions = function (i, disabled) {
  977. var $thumb = $('#' + self.previewInitId + "-" + i),
  978. $btnUpload = $thumb.find('.kv-file-upload'),
  979. $btnDelete = $thumb.find('.kv-file-delete');
  980. $thumb.removeClass('file-uploading');
  981. $btnUpload.removeAttr('disabled');
  982. $btnDelete.removeAttr('disabled');
  983. },
  984. setAllUploaded = function() {
  985. $.each(files, function(key, data) {
  986. self.filestack[key] = undefined;
  987. });
  988. self.clearFileInput();
  989. };
  990. $.each(files, function(key, data) {
  991. if (files[key] !== undefined) {
  992. formdata.append(self.uploadFileAttr, files[key]);
  993. }
  994. });
  995. self.uploadExtra(formdata);
  996. self.ajaxRequests.push($.ajax({
  997. xhr: function() {
  998. var xhrobj = $.ajaxSettings.xhr();
  999. return self.initXhr(xhrobj, 98);
  1000. },
  1001. url: self.uploadUrl,
  1002. type: 'POST',
  1003. dataType: 'json',
  1004. data: formdata,
  1005. cache: false,
  1006. processData: false,
  1007. contentType: false,
  1008. beforeSend: function(jqXHR) {
  1009. self.lock();
  1010. var outData = self.getOutData(jqXHR);
  1011. if (!self.showPreview) {
  1012. return;
  1013. }
  1014. self.$preview.find('.file-preview-frame').each(function() {
  1015. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove');
  1016. addCss($thumb, 'file-uploading');
  1017. $btnUpload.attr('disabled', true);
  1018. $btnDelete.attr('disabled', true);
  1019. });
  1020. self.raise('filebatchpreupload', [outData]);
  1021. },
  1022. success: function(data, textStatus, jqXHR) {
  1023. var outData = self.getOutData(jqXHR, data);
  1024. var keys = isEmpty(data.errorkeys) ? [] : data.errorkeys;
  1025. if(typeof data.error === 'undefined' || isEmpty(data.error)) {
  1026. self.raise('filebatchuploadsuccess', [outData]);
  1027. setAllUploaded();
  1028. if (self.showPreview) {
  1029. self.$preview.find('.kv-file-upload').hide();
  1030. self.$preview.find('.kv-file-remove').hide();
  1031. self.$preview.find('.file-preview-frame').each(function() {
  1032. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1033. setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle');
  1034. enableActions(key);
  1035. });
  1036. } else {
  1037. self.reset();
  1038. }
  1039. } else {
  1040. self.$preview.find('.file-preview-frame').each(function() {
  1041. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1042. enableActions(key);
  1043. if (keys.length == 0) {
  1044. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1045. return;
  1046. }
  1047. if ($.inArray(key, keys)) {
  1048. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1049. } else {
  1050. $thumb.find('.kv-file-upload').hide();
  1051. $thumb.find('.kv-file-remove').hide();
  1052. setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle');
  1053. self.filestack[key] = undefined;
  1054. }
  1055. });
  1056. self.showUploadError(data.error, outData, null, null, 'filebatchuploaderror');
  1057. }
  1058. },
  1059. complete: function () {
  1060. self.setProgress(100);
  1061. self.unlock();
  1062. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1063. self.clearFileInput();
  1064. },
  1065. error: function(jqXHR, textStatus, errorThrown) {
  1066. var outData = self.getOutData(jqXHR);
  1067. self.showUploadError(errorThrown, outData, null, null, 'filebatchuploaderror');
  1068. self.uploadFileCount = total - 1;
  1069. self.$preview.find('.file-preview-frame').removeClass('file-uploading');
  1070. self.$preview.find('.file-preview-frame kv-file-upload').removeAttr('disabled');
  1071. self.$preview.find('.file-preview-frame kv-file-delete').removeAttr('disabled');
  1072. }
  1073. }));
  1074. },
  1075. hideFileIcon: function () {
  1076. if (this.overwriteInitial) {
  1077. this.$captionContainer.find('.kv-caption-icon').hide();
  1078. }
  1079. },
  1080. showFileIcon: function () {
  1081. this.$captionContainer.find('.kv-caption-icon').show();
  1082. },
  1083. resetErrors: function (fade) {
  1084. var self = this, $error = self.$errorContainer;
  1085. self.isError = false;
  1086. self.$container.removeClass('has-error');
  1087. $error.html('');
  1088. if (fade) {
  1089. $error.fadeOut('slow');
  1090. } else {
  1091. $error.hide();
  1092. }
  1093. },
  1094. showUploadError: function (msg, data, previewId, index) {
  1095. var self = this, $error = self.$errorContainer,
  1096. ev = arguments.length > 4 ? arguments[4] : 'fileuploaderror';
  1097. if ($error.find('ul').length == 0) {
  1098. $error.html('<ul class="text-left"><li>' + msg + '</li></ul>');
  1099. } else {
  1100. $error.find('ul').append('<li>' + msg + '</li>');
  1101. }
  1102. $error.fadeIn(800);
  1103. self.raise(ev, [data, previewId, index, self.reader]);
  1104. addCss(self.$container, 'has-error');
  1105. return true;
  1106. },
  1107. showError: function (msg, file, previewId, index) {
  1108. var self = this, $error = self.$errorContainer,
  1109. ev = arguments.length > 4 ? arguments[4] : 'fileerror',
  1110. jqXHR = arguments.length > 5 ? arguments[5] : {};
  1111. $error.html(msg);
  1112. $error.fadeIn(800);
  1113. self.raise(ev, [file, previewId, index, self.reader, jqXHR]);
  1114. if (!self.isUploadable) {
  1115. self.clearFileInput();
  1116. }
  1117. addCss(self.$container, 'has-error');
  1118. self.$btnUpload.attr('disabled', true);
  1119. return true;
  1120. },
  1121. errorHandler: function (evt, caption) {
  1122. var self = this;
  1123. switch (evt.target.error.code) {
  1124. case evt.target.error.NOT_FOUND_ERR:
  1125. self.addError(self.msgFileNotFound.replace(/\{name\}/g, caption));
  1126. break;
  1127. case evt.target.error.NOT_READABLE_ERR:
  1128. self.addError(self.msgFileNotReadable.replace(/\{name\}/g, caption));
  1129. break;
  1130. case evt.target.error.ABORT_ERR:
  1131. self.addError(self.msgFilePreviewAborted.replace(/\{name\}/g, caption));
  1132. break;
  1133. default:
  1134. self.addError(self.msgFilePreviewError.replace(/\{name\}/g, caption));
  1135. }
  1136. },
  1137. parseFileType: function(file) {
  1138. var isValid, vType;
  1139. for (var i = 0; i < defaultPreviewTypes.length; i++) {
  1140. cat = defaultPreviewTypes[i];
  1141. isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  1142. vType = isValid(file.type, file.name) ? cat : '';
  1143. if (vType != '') {
  1144. return vType;
  1145. }
  1146. }
  1147. return 'other';
  1148. },
  1149. previewDefault: function(file, previewId) {
  1150. var self = this;
  1151. if (!self.showPreview) {
  1152. return;
  1153. }
  1154. var data = vUrl.createObjectURL(file), $obj = $('#' + previewId),
  1155. config = self.previewSettings.other,
  1156. footer = self.isUploadable ?
  1157. self.renderFileFooter(file.name, config.width) :
  1158. self.renderFileFooter(file.name, config.width, false),
  1159. previewOtherTemplate = self.getPreviewTemplate('other'),
  1160. ind = previewId.slice(previewId.lastIndexOf('-') + 1),
  1161. frameClass = '';
  1162. if (arguments.length > 2) {
  1163. var $err = $(self.msgValidationError);
  1164. frameClass = ' btn disabled';
  1165. footer += '<div class="file-other-error text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i></div>';
  1166. }
  1167. self.$preview.append("\n" + previewOtherTemplate
  1168. .replace(/\{previewId\}/g, previewId)
  1169. .replace(/\{frameClass\}/g, frameClass)
  1170. .replace(/\{fileindex\}/g, ind)
  1171. .replace(/\{caption\}/g, self.slug(file.name))
  1172. .replace(/\{width\}/g, config.width)
  1173. .replace(/\{height\}/g, config.height)
  1174. .replace(/\{type\}/g, file.type)
  1175. .replace(/\{data\}/g, data)
  1176. .replace(/\{footer\}/g, footer));
  1177. $obj.on('load', function(e) {
  1178. vUrl.revokeObjectURL($obj.attr('data'));
  1179. });
  1180. },
  1181. previewFile: function(file, theFile, previewId, data) {
  1182. var self = this;
  1183. if (!self.showPreview) {
  1184. return;
  1185. }
  1186. var cat = self.parseFileType(file), caption = self.slug(file.name), data, obj, content,
  1187. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes, fType = file.type,
  1188. template = isSet(cat, self.previewTemplates) ? self.previewTemplates[cat] : defaultPreviewTemplates[cat],
  1189. config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat],
  1190. wrapLen = parseInt(self.wrapTextLength), wrapInd = self.wrapIndicator, $preview = self.$preview,
  1191. chkTypes = types.indexOf(cat) >=0, chkMimes = isEmpty(mimes) || (!isEmpty(mimes) && isSet(file.type, mimes)),
  1192. footer = self.renderFileFooter(caption, config.width),
  1193. ind = previewId.slice(previewId.lastIndexOf('-') + 1);
  1194. if (chkTypes && chkMimes) {
  1195. if (cat == 'text') {
  1196. var strText = htmlEncode(theFile.target.result);
  1197. vUrl.revokeObjectURL(data);
  1198. if (strText.length > wrapLen) {
  1199. var id = 'text-' + uniqId(), height = window.innerHeight * .75,
  1200. modal = self.getLayoutTemplate('modal')
  1201. .replace(/\{id\}/g, id)
  1202. .replace(/\{title\}/g, caption)
  1203. .replace(/\{height\}/g, height)
  1204. .replace(/\{body\}/g, strText);
  1205. wrapInd = wrapInd
  1206. .replace(/\{title\}/g, caption)
  1207. .replace(/\{dialog\}/g, "$('#" + id + "').modal('show')");
  1208. strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
  1209. }
  1210. content = template
  1211. .replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption)
  1212. .replace(/\{frameClass\}/g, '')
  1213. .replace(/\{type\}/g, file.type).replace(/\{width\}/g, config.width)
  1214. .replace(/\{height\}/g, config.height).replace(/\{data\}/g, strText)
  1215. .replace(/\{footer\}/g, footer).replace(/\{fileindex\}/g, ind) + modal;
  1216. } else {
  1217. content = template
  1218. .replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption)
  1219. .replace(/\{frameClass\}/g, '')
  1220. .replace(/\{type\}/g, file.type).replace(/\{data\}/g, data)
  1221. .replace(/\{width\}/g, config.width).replace(/\{height\}/g, config.height)
  1222. .replace(/\{footer\}/g, footer).replace(/\{fileindex\}/g, ind);
  1223. }
  1224. $preview.append("\n" + content);
  1225. self.autoSizeImage(previewId);
  1226. } else {
  1227. self.previewDefault(file, previewId);
  1228. }
  1229. },
  1230. slugDefault: function (text) {
  1231. return isEmpty(text) ? '' : text.split(/(\\|\/)/g).pop().replace(/[^\w-.\\\/ ]+/g,'');
  1232. },
  1233. getFileStack: function() {
  1234. var size = 0, self = this;
  1235. return self.filestack.filter(function(n){ return n != undefined });
  1236. },
  1237. readFiles: function (files) {
  1238. this.reader = new FileReader();
  1239. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  1240. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  1241. msgProgress = self.msgProgress, msgSelected = self.msgSelected, fileType = self.previewFileType,
  1242. wrapLen = parseInt(self.wrapTextLength), wrapInd = self.wrapIndicator,
  1243. previewInitId = self.previewInitId, numFiles = files.length, settings = self.fileTypeSettings,
  1244. isText = isSet('text', settings) ? settings['text'] : defaultFileTypeSettings['text'],
  1245. ctr = self.filestack.length,
  1246. throwError = function(msg, file, previewId, index) {
  1247. self.previewDefault(file, previewId, true);
  1248. var outData = self.getOutData({}, {}, files);
  1249. return self.isUploadable ? self.showUploadError(msg, outData, previewId, index) : self.showError(msg, file, previewId, index);
  1250. };
  1251. function readFile(i) {
  1252. if (isEmpty($el.attr('multiple'))) {
  1253. numFiles = 1;
  1254. }
  1255. if (i >= numFiles) {
  1256. $container.removeClass('loading');
  1257. $status.html('');
  1258. return;
  1259. }
  1260. var node = ctr + i, previewId = previewInitId + "-" + node, file = files[i], caption = self.slug(file.name),
  1261. fileSize = (file.size ? file.size : 0) / 1000, checkFile,
  1262. previewData = vUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk,
  1263. fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '),
  1264. fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', '),
  1265. fileExtExpr = isEmpty(fileExt) ? '' : new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  1266. fileSize = fileSize.toFixed(2);
  1267. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  1268. msg = self.msgSizeTooLarge.replace(/\{name\}/g, caption).replace(/\{size\}/g,
  1269. fileSize).replace(/\{maxSize\}/g, self.maxFileSize);
  1270. self.isError = throwError(msg, file, previewId, i);
  1271. return;
  1272. }
  1273. if (!isEmpty(fileTypes) && isArray(fileTypes)) {
  1274. for (j = 0; j < fileTypes.length; j++) {
  1275. typ = fileTypes[j];
  1276. checkFile = settings[typ];
  1277. chk = (checkFile !== undefined && checkFile(file.type, caption));
  1278. fileCount += isEmpty(chk) ? 0 : chk.length;
  1279. }
  1280. if (fileCount == 0) {
  1281. msg = self.msgInvalidFileType.replace(/\{name\}/g, caption).replace(/\{types\}/g, strTypes);
  1282. self.isError = throwError(msg, file, previewId, i);
  1283. return;
  1284. }
  1285. }
  1286. if (fileCount == 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) {
  1287. chk = caption.match(fileExtExpr);
  1288. fileCount += isEmpty(chk) ? 0 : chk.length;
  1289. if (fileCount == 0) {
  1290. msg = self.msgInvalidFileExtension.replace(/\{name\}/g, caption).replace(/\{extensions\}/g, strExt);
  1291. self.isError = throwError(msg, file, previewId, i);
  1292. return;
  1293. }
  1294. }
  1295. if (!self.showPreview) {
  1296. self.filestack.push(file);
  1297. setTimeout(readFile(i + 1), 100);
  1298. self.raise('fileloaded', [file, previewId, i, reader]);
  1299. return;
  1300. }
  1301. if ($preview.length > 0 && typeof FileReader !== "undefined") {
  1302. $status.html(msgLoading.replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles));
  1303. $container.addClass('loading');
  1304. reader.onerror = function (evt) {
  1305. self.errorHandler(evt, caption);
  1306. };
  1307. reader.onload = function (theFile) {
  1308. self.previewFile(file, theFile, previewId, previewData);
  1309. self.initFileActions();
  1310. };
  1311. reader.onloadend = function (e) {
  1312. var msg = msgProgress
  1313. .replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles)
  1314. .replace(/\{percent\}/g, 50).replace(/\{name\}/g, caption);
  1315. setTimeout(function () {
  1316. $status.html(msg);
  1317. vUrl.revokeObjectURL(previewData);
  1318. }, 100);
  1319. setTimeout(function () {
  1320. readFile(i + 1);
  1321. self.updateFileDetails(numFiles);
  1322. }, 100);
  1323. self.raise('fileloaded', [file, previewId, i, reader]);
  1324. };
  1325. reader.onprogress = function (data) {
  1326. if (data.lengthComputable) {
  1327. var progress = parseInt(((data.loaded / data.total) * 100), 10);
  1328. var msg = msgProgress
  1329. .replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles)
  1330. .replace(/\{percent\}/g, progress).replace(/\{name\}/g, caption);
  1331. setTimeout(function () {
  1332. $status.html(msg);
  1333. }, 100);
  1334. }
  1335. };
  1336. if (isText(file.type, caption)) {
  1337. reader.readAsText(file, self.textEncoding);
  1338. } else {
  1339. reader.readAsArrayBuffer(file);
  1340. }
  1341. } else {
  1342. self.previewDefault(file, previewId);
  1343. setTimeout(function() {
  1344. readFile(i + 1);
  1345. self.updateFileDetails(numFiles);
  1346. }, 100);
  1347. self.raise('fileloaded', [file, previewId, i, reader]);
  1348. }
  1349. self.filestack.push(file);
  1350. }
  1351. readFile(0);
  1352. self.updateFileDetails(numFiles, false);
  1353. },
  1354. updateFileDetails: function(numFiles) {
  1355. var self = this, msgSelected = self.msgSelected, $el = self.$element, fileStack = self.getFileStack(),
  1356. name = $el.val() || (fileStack.length && fileStack[0].name) || '', label = self.slug(name),
  1357. n = self.isUploadable ? fileStack.length : numFiles;
  1358. numFiles = self.initialPreviewCount + n,
  1359. log = n > 1 ? msgSelected.replace(/\{n\}/g, numFiles) : label;
  1360. if (self.isError) {
  1361. self.$previewContainer.removeClass('loading');
  1362. self.$previewStatus.html('');
  1363. self.$captionContainer.find('.kv-caption-icon').hide();
  1364. log = self.msgValidationError;
  1365. } else {
  1366. self.showFileIcon();
  1367. }
  1368. self.setCaption(log);
  1369. self.$container.removeClass('file-input-new');
  1370. if (arguments.length == 1) {
  1371. self.raise('fileselect', [numFiles, label]);
  1372. }
  1373. },
  1374. change: function (e) {
  1375. var self = this, $el = self.$element, label = self.slug($el.val()),
  1376. total = 0, $preview = self.$preview, isDragDrop = arguments.length > 1,
  1377. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files,
  1378. msgSelected = self.msgSelected,
  1379. numFiles = !isEmpty(files) ? (files.length + self.initialPreviewCount) : 1, tfiles,
  1380. ctr = self.filestack.length, isAjaxUpload = (self.isUploadable && ctr != 0),
  1381. isSingleUpload = isEmpty($el.attr('multiple')),
  1382. throwError = function(msg, file, previewId, index) {
  1383. var outData = self.getOutData({}, {}, files);
  1384. return self.isUploadable ? self.showUploadError(msg, outData, previewId, index) : self.showError(msg, file, previewId, index);
  1385. };
  1386. self.resetUpload();
  1387. self.hideFileIcon();
  1388. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  1389. if (isDragDrop) {
  1390. tfiles = files;
  1391. } else {
  1392. if (e.target.files === undefined) {
  1393. tfiles = e.target && e.target.value ? [
  1394. {name: e.target.value.replace(/^.+\\/, '')}
  1395. ] : [];
  1396. } else {
  1397. tfiles = e.target.files;
  1398. }
  1399. }
  1400. if (isEmpty(tfiles) || tfiles.length === 0) {
  1401. if (!isAjaxUpload) {
  1402. self.clear(false);
  1403. }
  1404. self.raise('fileselectnone');
  1405. return;
  1406. }
  1407. self.resetErrors();
  1408. if (!isAjaxUpload || (isSingleUpload && ctr > 0)) {
  1409. if (!self.overwriteInitial) {
  1410. $preview.html(self.initialPreviewContent);
  1411. } else {
  1412. $preview.html('');
  1413. }
  1414. if (isSingleUpload && ctr > 0) {
  1415. self.filestack = [];
  1416. }
  1417. }
  1418. var total = self.isUploadable ? self.getFileStack().length + tfiles.length : tfiles.length;
  1419. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  1420. var msg = self.msgFilesTooMany.replace(/\{m\}/g, self.maxFileCount).replace(/\{n\}/g, total);
  1421. self.isError = throwError(msg, null, null, null);
  1422. self.$captionContainer.find('.kv-caption-icon').hide();
  1423. self.$caption.html(self.msgValidationError);
  1424. self.$container.removeClass('file-input-new');
  1425. return;
  1426. }
  1427. if (!self.isIE9) {
  1428. self.readFiles(files);
  1429. } else {
  1430. self.updateFileDetails(1);
  1431. }
  1432. self.reader = null;
  1433. },
  1434. autoSizeImage: function(previewId) {
  1435. var self = this, $preview = self.$preview,
  1436. $thumb = $preview.find("#" + previewId),
  1437. $img = $thumb.find('img');
  1438. if (!$img.length) {
  1439. return;
  1440. }
  1441. $img.on('load', function() {
  1442. var w1 = $thumb.width(), w2 = $preview.width();
  1443. if (w1 > w2) {
  1444. $img.css('width', '100%');
  1445. $thumb.css('width', '97%');
  1446. }
  1447. var $cap = $img.closest('.file-preview-frame').find('.file-caption-name');
  1448. if ($cap.length) {
  1449. $cap.width($img.width());
  1450. $cap.attr('title', $cap.text());
  1451. }
  1452. self.raise('fileimageloaded', previewId);
  1453. });
  1454. },
  1455. autoSizeCaption: function() {
  1456. var self = this;
  1457. if (self.$caption.length == 0 || !self.autoFitCaption) {
  1458. return;
  1459. }
  1460. self.$caption.css('width', 0);
  1461. setTimeout(function() {
  1462. var w = self.$captionContainer.width();
  1463. self.$caption.css('width', 0.98 * w);
  1464. }, 50);
  1465. },
  1466. setCaption: function(content) {
  1467. var self = this, title = $('<div>' + content + '</div>').text(),
  1468. icon = self.getLayoutTemplate('icon'),
  1469. out = icon + title;
  1470. if (self.$caption.length == 0) {
  1471. return;
  1472. }
  1473. self.$caption.html(out);
  1474. self.$caption.attr('title', title);
  1475. self.autoSizeCaption();
  1476. },
  1477. initBrowse: function ($container) {
  1478. var self = this;
  1479. self.$btnFile = $container.find('.btn-file');
  1480. self.$btnFile.append(self.$element);
  1481. },
  1482. createContainer: function () {
  1483. var self = this;
  1484. var $container = $(document.createElement("span")).attr({"class": 'file-input file-input-new'}).html(self.renderMain());
  1485. self.$element.before($container);
  1486. self.initBrowse($container);
  1487. return $container;
  1488. },
  1489. refreshContainer: function () {
  1490. var self = this, $container = self.$container;
  1491. $container.before(self.$element);
  1492. $container.html(self.renderMain());
  1493. self.initBrowse($container);
  1494. },
  1495. renderMain: function () {
  1496. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : '';;
  1497. var preview = self.showPreview ? self.getLayoutTemplate('preview')
  1498. .replace(/\{class\}/g, self.previewClass)
  1499. .replace(/\{dropClass\}/g, dropCss)
  1500. : '';
  1501. var css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass;
  1502. var caption = self.captionTemplate.replace(/\{class\}/g, css + ' kv-fileinput-caption');
  1503. return self.mainTemplate.replace(/\{class\}/g, self.mainClass).
  1504. replace(/\{preview\}/g, preview).
  1505. replace(/\{caption\}/g, caption).
  1506. replace(/\{upload\}/g, self.renderUpload()).
  1507. replace(/\{remove\}/g, self.renderRemove()).
  1508. replace(/\{cancel\}/g, self.renderCancel()).
  1509. replace(/\{browse\}/g, self.renderBrowse());
  1510. },
  1511. renderBrowse: function () {
  1512. var self = this, css = self.browseClass + ' btn-file', status = '';
  1513. if (self.isDisabled) {
  1514. status = ' disabled ';
  1515. }
  1516. return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>';
  1517. },
  1518. renderRemove: function () {
  1519. var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
  1520. if (!self.showRemove) {
  1521. return '';
  1522. }
  1523. if (self.isDisabled) {
  1524. status = ' disabled ';
  1525. }
  1526. return '<button type="button" title="' + self.removeTitle + '" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
  1527. },
  1528. renderCancel: function () {
  1529. var self = this, css = self.cancelClass + ' fileinput-cancel fileinput-cancel-button', status = '';
  1530. if (!self.showCancel) {
  1531. return '';
  1532. }
  1533. return '<button type="button" title="' + self.cancelTitle + '" class="hide ' + css + '">' + self.cancelIcon + self.cancelLabel + '</button>';
  1534. },
  1535. renderUpload: function () {
  1536. var self = this, css = self.uploadClass + ' kv-fileinput-upload', content = '', status = '';
  1537. if (!self.showUpload) {
  1538. return '';
  1539. }
  1540. if (self.isDisabled) {
  1541. status = ' disabled ';
  1542. }
  1543. if (!self.isUploadable || self.isDisabled) {
  1544. content = '<button type="submit" title="' + self.uploadTitle + '"class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
  1545. } else {
  1546. content = '<a href="' + self.uploadUrl + '" title="' + self.uploadTitle + '" class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>';
  1547. }
  1548. return content;
  1549. }
  1550. }
  1551. //FileInput plugin definition
  1552. $.fn.fileinput = function (option) {
  1553. if (!hasFileAPISupport() && !isIE(9)) {
  1554. return;
  1555. }
  1556. var args = Array.apply(null, arguments);
  1557. args.shift();
  1558. return this.each(function () {
  1559. var $this = $(this),
  1560. data = $this.data('fileinput'),
  1561. options = typeof option === 'object' && option;
  1562. if (!data) {
  1563. $this.data('fileinput',
  1564. (data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data()))));
  1565. }
  1566. if (typeof option === 'string') {
  1567. data[option].apply(data, args);
  1568. }
  1569. });
  1570. };
  1571. $.fn.fileinput.defaults = {
  1572. showCaption: true,
  1573. showPreview: true,
  1574. showRemove: true,
  1575. showUpload: true,
  1576. showCancel: true,
  1577. autoFitCaption: true,
  1578. mainClass: '',
  1579. previewClass: '',
  1580. captionClass: '',
  1581. mainTemplate: null,
  1582. initialCaption: '',
  1583. initialPreview: '',
  1584. initialPreviewCount: 0,
  1585. initialPreviewDelimiter: '*$$*',
  1586. initialPreviewConfig: [],
  1587. initialPreviewShowDelete: true,
  1588. overwriteInitial: true,
  1589. layoutTemplates: defaultLayoutTemplates,
  1590. previewTemplates: defaultPreviewTemplates,
  1591. allowedPreviewTypes: defaultPreviewTypes,
  1592. allowedPreviewMimeTypes: null,
  1593. allowedFileTypes: null,
  1594. allowedFileExtensions: null,
  1595. previewSettings: defaultPreviewSettings,
  1596. fileTypeSettings: defaultFileTypeSettings,
  1597. browseLabel: 'Browse &hellip;',
  1598. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  1599. browseClass: 'btn btn-primary',
  1600. removeLabel: 'Remove',
  1601. removeTitle: 'Clear selected files',
  1602. removeIcon: '<i class="glyphicon glyphicon-trash"></i> ',
  1603. removeClass: 'btn btn-default',
  1604. cancelLabel: 'Cancel',
  1605. cancelTitle: 'Abort ongoing upload',
  1606. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  1607. cancelClass: 'btn btn-default',
  1608. uploadLabel: 'Upload',
  1609. uploadTitle: 'Upload selected files',
  1610. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  1611. uploadClass: 'btn btn-default',
  1612. uploadUrl: null,
  1613. uploadExtraData: [],
  1614. uploadAsync: true,
  1615. maxFileSize: 0,
  1616. maxFileCount: 0,
  1617. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>. Please retry your upload!',
  1618. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>. Please retry your upload!',
  1619. msgFileNotFound: 'File "{name}" not found!',
  1620. msgFileNotReadable: 'File "{name}" is not readable.',
  1621. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  1622. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  1623. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  1624. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  1625. msgValidationError: '<span class="text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i> File Upload Error</span>',
  1626. msgErrorClass: 'file-error-message',
  1627. msgLoading: 'Loading file {index} of {files} &hellip;',
  1628. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  1629. msgSelected: '{n} files selected',
  1630. previewFileType: 'image',
  1631. wrapTextLength: 250,
  1632. wrapIndicator: ' <span class="wrap-indicator" title="{title}" onclick="{dialog}">[&hellip;]</span>',
  1633. elCaptionContainer: null,
  1634. elCaptionText: null,
  1635. elPreviewContainer: null,
  1636. elPreviewImage: null,
  1637. elPreviewStatus: null,
  1638. elErrorContainer: null,
  1639. slugCallback: null,
  1640. dropZoneEnabled: true,
  1641. dropZoneTitle: 'Drag & drop files here &hellip;',
  1642. dropZoneTitleClass: 'file-drop-zone-title',
  1643. fileActionSettings: {},
  1644. otherActionButtons: '',
  1645. textEncoding: 'UTF-8'
  1646. };
  1647. $.fn.fileinput.Constructor = FileInput;
  1648. /**
  1649. * Convert automatically file inputs with class 'file'
  1650. * into a bootstrap fileinput control.
  1651. */
  1652. $(document).ready(function () {
  1653. var $input = $('input.file[type=file]'), count = $input.attr('type') != null ? $input.length : 0;
  1654. if (count > 0) {
  1655. $input.fileinput();
  1656. }
  1657. });
  1658. })(window.jQuery);