fileinput.js 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660
  1. /*!
  2. * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014
  3. * @version 4.1.4
  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: 2014, 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, responsedata = arguments.length > 0 ? arguments[0] : {},
  333. filesdata = arguments.length > 1 ? arguments[1] : self.filestack;
  334. return {
  335. form: self.formdata,
  336. files: filesdata,
  337. extra: self.getExtraData(),
  338. response: responsedata,
  339. reader: self.reader
  340. };
  341. },
  342. listen: function () {
  343. var self = this, $el = self.$element, $cap = self.$captionContainer, $btnFile = self.$btnFile;
  344. $el.on('change', $.proxy(self.change, self));
  345. $(window).off('resize').on('resize', function() {
  346. setTimeout(function() {
  347. self.autoSizeCaption();
  348. }, 50);
  349. });
  350. $btnFile.off('click').on('click', function (ev) {
  351. self.raise('filebrowse');
  352. if (self.isError && !self.isUploadable) {
  353. self.clear(false);
  354. }
  355. $cap.focus();
  356. });
  357. $el.closest('form').off('reset').on('reset', $.proxy(self.reset, self));
  358. self.$container.off('click')
  359. .on('click', '.fileinput-remove:not([disabled])', $.proxy(self.clear, self))
  360. .on('click', '.fileinput-cancel', $.proxy(self.cancel, self));
  361. if (self.isUploadable && self.dropZoneEnabled && self.showPreview) {
  362. self.initDragDrop();
  363. }
  364. if (!self.isUploadable) {
  365. return;
  366. }
  367. self.$container.find('.kv-fileinput-upload').off('click').on('click', function(e) {
  368. if (!self.isUploadable) {
  369. return;
  370. }
  371. e.preventDefault();
  372. var totLen = self.getFileStack().length;
  373. if (self.isDisabled || $(this).hasClass('disabled') || !isEmpty($(this).attr('disabled')) || totLen == 0) {
  374. return;
  375. }
  376. self.resetUpload();
  377. self.$progress.removeClass('hide');
  378. self.uploadCount = 0;
  379. self.uploadPercent = 0;
  380. var i, len = self.filestack.length, template = self.getLayoutTemplate('progress');
  381. self.lock();
  382. self.setProgress(0);
  383. if ((self.uploadAsync || totLen == 1) && self.showPreview) {
  384. var outData = self.getOutData();
  385. self.raise('filebatchpreupload', [outData]);
  386. for (i = 0; i < len; i++) {
  387. if (self.filestack[i] !== undefined) {
  388. self.upload(i, self.getFileStack(), true);
  389. }
  390. }
  391. setTimeout(function() {
  392. $(document).ajaxStop(function() {
  393. self.setProgress(100);
  394. self.$preview.find('file-preview-frame').removeClass('file-loading');
  395. self.unlock();
  396. self.clearFileInput();
  397. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  398. });
  399. }, 100);
  400. return;
  401. }
  402. self.uploadBatch();
  403. });
  404. },
  405. setProgress: function(percent) {
  406. var self = this, template = self.getLayoutTemplate('progress'), pct = Math.min(percent, 100);
  407. self.$progress.html(template.replace(/\{percent\}/g, pct));
  408. },
  409. lock: function() {
  410. var self = this;
  411. self.resetErrors();
  412. self.disable();
  413. if (self.showRemove) {
  414. addCss(self.$container.find('.fileinput-remove'), 'hide');
  415. }
  416. if (self.showCancel) {
  417. self.$container.find('.fileinput-cancel').removeClass('hide');
  418. }
  419. self.raise('filelock', [self.filestack, self.getExtraData()]);
  420. },
  421. unlock: function() {
  422. var self = this;
  423. self.enable();
  424. if (self.showCancel) {
  425. addCss(self.$container.find('.fileinput-cancel'), 'hide');
  426. }
  427. if (self.showRemove) {
  428. self.$container.find('.fileinput-remove').removeClass('hide');
  429. }
  430. self.raise('fileunlock', [self.filestack, self.getExtraData()]);
  431. },
  432. refresh: function (options) {
  433. var self = this, $el = self.$element,
  434. params = (arguments.length) ? $.extend(self.options, options) : self.options;
  435. $el.off();
  436. self.init(params);
  437. var $zone = self.$container.find('.file-drop-zone');
  438. $zone.off('dragenter dragover drop');
  439. $(document).off('dragenter dragover drop');
  440. self.listen();
  441. self.setFileDropZoneTitle();
  442. },
  443. initDragDrop: function() {
  444. var self = this, $zone = self.$container.find('.file-drop-zone');
  445. $zone.off('dragenter dragover drop');
  446. $(document).off('dragenter dragover drop');
  447. $zone.on('dragenter dragover', function (e) {
  448. e.stopPropagation();
  449. e.preventDefault();
  450. if (self.isDisabled) {
  451. return;
  452. }
  453. addCss($(this), 'highlighted');
  454. });
  455. $zone.on('dragleave', function (e) {
  456. e.stopPropagation();
  457. e.preventDefault();
  458. if (self.isDisabled) {
  459. return;
  460. }
  461. $(this).removeClass('highlighted');
  462. });
  463. $zone.on('drop', function (e) {
  464. e.preventDefault();
  465. if (self.isDisabled) {
  466. return;
  467. }
  468. self.change(e, 'dragdrop');
  469. $(this).removeClass('highlighted');
  470. });
  471. $(document).on('dragenter dragover drop', function (e) {
  472. e.stopPropagation();
  473. e.preventDefault();
  474. });
  475. },
  476. setFileDropZoneTitle: function() {
  477. var self = this, $zone = self.$container.find('.file-drop-zone');
  478. $zone.find('.' + self.dropZoneTitleClass).remove();
  479. if (!self.isUploadable || !self.showPreview ||
  480. $zone.length == 0 || self.getFileStack().length > 0 ||
  481. !self.dropZoneEnabled) {
  482. return;
  483. }
  484. if ($zone.find('.file-preview-frame').length == 0) {
  485. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + self.dropZoneTitle + '</div>');
  486. }
  487. self.$container.removeClass('file-input-new');
  488. },
  489. initFileActions: function() {
  490. var self = this;
  491. self.$preview.find('.kv-file-remove').each(function() {
  492. var $el = $(this), $frame = $el.closest('.file-preview-frame'),
  493. ind = $frame.attr('data-fileindex');
  494. $el.off('click').on('click', function() {
  495. $frame.fadeOut('slow', function() {
  496. self.filestack[ind] = undefined;
  497. self.clearObjects($frame);
  498. $frame.remove();
  499. var filestack = self.getFileStack(), len = filestack.length,
  500. chk = self.$container.find('.file-preview-initial').length;
  501. if (len == 0 && chk == 0) {
  502. self.original.preview = '';
  503. self.reset();
  504. } else {
  505. var n = self.initialPreviewCount + len,
  506. cap = n > 1 ? self.msgSelected.replace(/\{n\}/g, n) : filestack[0].name;
  507. self.setCaption(cap);
  508. }
  509. });
  510. });
  511. });
  512. self.$preview.find('.kv-file-upload').each(function() {
  513. var $el = $(this);
  514. $el.off('click').on('click', function() {
  515. var $frame = $el.closest('.file-preview-frame'),
  516. ind = $frame.attr('data-fileindex');
  517. self.upload(ind, self.getFileStack());
  518. });
  519. });
  520. },
  521. renderInitFileFooter: function(i) {
  522. var self = this, hasConfig = self.initialPreviewConfig.length > 0,
  523. template = self.getLayoutTemplate('footer');
  524. if (hasConfig && !isEmpty(self.initialPreviewConfig[i])) {
  525. var config = self.initialPreviewConfig[i],
  526. caption = ('caption' in config) ? config.caption : '',
  527. width = ('width' in config) ? config.width : 'auto',
  528. url = ('url' in config) ? config.url : false,
  529. key = ('key' in config) ? config.key : null,
  530. disabled = url === false ? true : false,
  531. actions = self.initialPreviewShowDelete ? self.renderFileActions(false, true, disabled, url, key) : '',
  532. footer = template.replace(/\{actions\}/g, actions);
  533. return footer.replace(/\{caption\}/g, caption).replace(/\{width\}/g, width)
  534. .replace(/\{indicator\}/g, '').replace(/\{indicatorTitle\}/g, '');
  535. }
  536. return '';
  537. },
  538. renderFileFooter: function(caption, width) {
  539. var self = this, config = self.fileActionSettings,
  540. template = self.getLayoutTemplate('footer');
  541. if (self.isUploadable) {
  542. var footer = template.replace(/\{actions\}/g, self.renderFileActions(true, true, false, false, false));
  543. return footer.replace(/\{caption\}/g, caption).replace(/\{width\}/g, width)
  544. .replace(/\{indicator\}/g, config.indicatorNew).replace(/\{indicatorTitle\}/g, config.indicatorNewTitle);
  545. } else {
  546. return template.replace(/\{actions\}/g, '').replace(/\{caption\}/g, caption).replace(/\{width\}/g, width)
  547. .replace(/\{indicator\}/g, '').replace(/\{indicatorTitle\}/g, '');
  548. }
  549. return '';
  550. },
  551. renderFileActions: function(showUpload, showDelete, disabled, url, key) {
  552. if (!showUpload && !showDelete) {
  553. return '';
  554. }
  555. var self = this,
  556. vUrl = url == false ? '' : ' data-url="' + url + '"',
  557. vKey = key == false ? '' : ' data-key="' + key + '"',
  558. btnDelete = self.getLayoutTemplate('actionDelete'),
  559. btnUpload = '',
  560. template = self.getLayoutTemplate('actions'),
  561. otherActionButtons = self.otherActionButtons.replace(/\{dataKey\}/g, vKey),
  562. config = self.fileActionSettings,
  563. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  564. btnDelete = btnDelete
  565. .replace(/\{removeClass\}/g, removeClass)
  566. .replace(/\{removeIcon\}/g, config.removeIcon)
  567. .replace(/\{removeTitle\}/g, config.removeTitle)
  568. .replace(/\{dataUrl\}/g, vUrl)
  569. .replace(/\{dataKey\}/g, vKey);
  570. if (showUpload) {
  571. btnUpload = self.getLayoutTemplate('actionUpload')
  572. .replace(/\{uploadClass\}/g, config.uploadClass)
  573. .replace(/\{uploadIcon\}/g, config.uploadIcon)
  574. .replace(/\{uploadTitle\}/g, config.uploadTitle);
  575. }
  576. return template
  577. .replace(/\{delete\}/g, btnDelete)
  578. .replace(/\{upload\}/g, btnUpload)
  579. .replace(/\{other\}/g, otherActionButtons);
  580. },
  581. getInitialPreview: function(template, content, i) {
  582. var self = this, ind = 'init_' + i,
  583. previewId = self.previewInitId + '-' + ind;
  584. footer = self.renderInitFileFooter(i, false);
  585. return template
  586. .replace(/\{previewId\}/g, previewId)
  587. .replace(/\{frameClass\}/g, ' file-preview-initial')
  588. .replace(/\{fileindex\}/g, ind)
  589. .replace(/\{content\}/g, content)
  590. .replace(/\{footer\}/g, footer);
  591. },
  592. initPreview: function () {
  593. var self = this, html = '', content = self.initialPreview, len = self.initialPreviewCount,
  594. cap = self.initialCaption.length, previewId = self.previewInitId + '-init_' + i;
  595. caption = (cap > 0) ? self.initialCaption : self.msgSelected.replace(/\{n\}/g, len);
  596. if (isArray(content) && len > 0) {
  597. for (var i = 0; i < len; i++) {
  598. html += self.getInitialPreview(self.previewGenericTemplate, content[i], i);
  599. }
  600. if (len > 1 && cap == 0) {
  601. caption = self.msgSelected.replace(/\{n\}/g, len);
  602. }
  603. } else {
  604. if (len > 0) {
  605. var fileList = content.split(self.initialPreviewDelimiter);
  606. for (var i = 0; i < len; i++) {
  607. html += self.getInitialPreview(self.previewGenericTemplate, content[i], i);
  608. }
  609. if (len > 1 && cap == 0) {
  610. caption = self.msgSelected.replace(/\{n\}/g, len);
  611. }
  612. } else {
  613. if (cap > 0) {
  614. self.setCaption(caption);
  615. return;
  616. } else {
  617. return;
  618. }
  619. }
  620. }
  621. self.initialPreviewContent = html;
  622. self.$preview.html(html);
  623. self.setCaption(caption);
  624. self.$container.removeClass('file-input-new');
  625. },
  626. initPreviewDeletes: function() {
  627. var self = this,
  628. resetProgress = function() {
  629. if (self.$preview.find('.kv-file-remove').length == 0) {
  630. self.reset();
  631. }
  632. };
  633. self.$preview.find('.kv-file-remove').each(function() {
  634. var $el = $(this), $frame = $el.closest('.file-preview-frame'),
  635. vUrl = $el.attr('data-url'), vKey = $el.attr('data-key'),
  636. $content = $(self.initialPreviewContent);
  637. if (vUrl === undefined || vKey === undefined) {
  638. return;
  639. }
  640. $el.off('click').on('click', function() {
  641. $.ajax({
  642. url: vUrl,
  643. type: 'POST',
  644. dataType: 'json',
  645. data: {key: vKey},
  646. beforeSend: function() {
  647. addCss($frame, 'file-uploading');
  648. addCss($el, 'disabled');
  649. self.raise('filepredelete', [vKey]);
  650. },
  651. success: function(data, textStatus, jqXHR) {
  652. if(typeof data.error === 'undefined') {
  653. self.raise('filedeleted', [vKey]);
  654. } else {
  655. self.showError(data.error, null, $el.attr('id'), key, 'filedeleteerror');
  656. resetProgress();
  657. }
  658. $frame.removeClass('file-uploading').addClass('file-deleted');
  659. $frame.fadeOut('slow', function() {
  660. self.clearObjects($frame);
  661. $frame.remove();
  662. var $content = $(document.createElement('div')).html(self.original.preview);
  663. $content.find('.file-preview-frame').each(function() {
  664. var $el = $(this);
  665. if ($el.find('.kv-file-remove').attr('data-key') == vKey) {
  666. $el.remove();
  667. }
  668. });
  669. self.initialPreviewContent = $content.html();
  670. if (self.initialPreviewCount > 0) {
  671. self.initialPreviewCount--;
  672. }
  673. var caption = (self.initialCaption.length > 0) ?
  674. self.initialCaption :
  675. self.msgSelected.replace(/\{n\}/g, self.initialPreviewCount);
  676. self.original.preview = $content.html();
  677. self.setCaption(caption);
  678. self.original.caption = self.$caption.html();
  679. $content.remove();
  680. resetProgress();
  681. });
  682. },
  683. error: function(jqXHR, textStatus, errorThrown) {
  684. self.showError(errorThrown, null, $el.attr('id'), key, 'filedeleteerror');
  685. $frame.removeClass('file-uploading');
  686. resetProgress();
  687. }
  688. });
  689. });
  690. });
  691. },
  692. clearObjects: function($el) {
  693. $el.find('video audio').each(function() {
  694. this.pause();
  695. delete(this);
  696. $(this).remove();
  697. });
  698. $el.find('img object div').each(function() {
  699. delete(this);
  700. $(this).remove();
  701. });
  702. },
  703. clearFileInput: function() {
  704. var self = this, $el = self.$element;
  705. if (isEmpty($el.val())) {
  706. return;
  707. }
  708. // Fix for IE ver < 11, that does not clear file inputs
  709. // Requires a sequence of steps to prevent IE crashing but
  710. // still allow clearing of the file input.
  711. if (self.isIE9 || self.isIE10) {
  712. var $srcFrm = $el.closest('form'),
  713. $tmpFrm = $(document.createElement('form')),
  714. $tmpEl = $(document.createElement('div'));
  715. $el.before($tmpEl);
  716. if ($srcFrm.length) {
  717. $srcFrm.after($tmpFrm);
  718. } else {
  719. $tmpEl.after($tmpFrm);
  720. }
  721. $tmpFrm.append($el).trigger('reset');
  722. $tmpEl.before($el).remove();
  723. $tmpFrm.remove();
  724. } else { // normal input clear behavior for other sane browsers
  725. $el.val('');
  726. }
  727. },
  728. resetUpload: function() {
  729. var self = this;
  730. self.uploadCount = 0;
  731. self.uploadPercent = 0;
  732. self.$btnUpload.removeAttr('disabled');
  733. self.setProgress(0);
  734. addCss(self.$progress, 'hide');
  735. self.resetErrors(false);
  736. self.ajaxRequests = [];
  737. },
  738. cancel: function() {
  739. var self = this, xhr = self.ajaxRequests, len = xhr.length;
  740. if (len > 0) {
  741. for (i = 0; i < len; i++) {
  742. xhr[i].abort();
  743. }
  744. self.$preview.find('file-preview-frame').each(function() {
  745. $thumb = $(this), ind = $thumb.attr('data-fileindex');
  746. $thumb.removeClass('file-uploading');
  747. if (self.filestack[ind] !== undefined) {
  748. $thumb.find('.kv-file-upload').removeClass('disabled');
  749. $thumb.find('.kv-file-upload').removeClass('disabled');
  750. }
  751. });
  752. self.unlock();
  753. }
  754. },
  755. clear: function () {
  756. var self = this, e = arguments.length && arguments[0];
  757. if (!self.isIE9 && self.reader instanceof FileReader) {
  758. self.reader.abort();
  759. }
  760. self.$btnUpload.removeAttr('disabled');
  761. self.resetUpload();
  762. self.filestack = [];
  763. self.autoSizeCaption();
  764. self.clearFileInput();
  765. self.resetErrors(true);
  766. if (e !== false) {
  767. self.raise('change');
  768. self.raise('fileclear');
  769. }
  770. if (self.overwriteInitial) {
  771. self.initialPreviewCount = 0;
  772. self.initialPreviewContent = '';
  773. }
  774. if (!self.overwriteInitial && self.initialPreviewContent.length > 0) {
  775. self.showFileIcon();
  776. self.$preview.html(self.original.preview);
  777. self.$caption.html(self.original.caption);
  778. self.initPreviewDeletes();
  779. self.$container.removeClass('file-input-new');
  780. } else {
  781. self.$preview.find('.file-preview-frame').each(function() {
  782. self.clearObjects($(this));
  783. });
  784. self.$preview.html('');
  785. var cap = (!self.overwriteInitial && self.initialCaption.length > 0) ?
  786. self.original.caption : '';
  787. self.$caption.html(cap);
  788. self.$caption.attr('title', '');
  789. addCss(self.$container, 'file-input-new');
  790. }
  791. if (self.$container.find('.file-preview-frame').length == 0) {
  792. self.initialCaption = '';
  793. self.original.caption = '';
  794. self.$caption.html('');
  795. self.$captionContainer.find('.kv-caption-icon').hide();
  796. }
  797. self.hideFileIcon();
  798. self.raise('filecleared');
  799. self.$captionContainer.focus();
  800. self.setFileDropZoneTitle();
  801. },
  802. reset: function () {
  803. var self = this;
  804. self.clear(false);
  805. self.$preview.html(self.original.preview);
  806. self.$caption.html(self.original.caption);
  807. self.$container.find('.fileinput-filename').text('');
  808. self.raise('filereset');
  809. if (self.initialPreview.length > 0) {
  810. self.$container.removeClass('file-input-new');
  811. }
  812. self.setFileDropZoneTitle();
  813. if (self.isUploadable) {
  814. self.resetUpload();
  815. }
  816. self.filestack = [];
  817. self.formdata = {};
  818. },
  819. disable: function (e) {
  820. var self = this;
  821. self.isDisabled = true;
  822. self.$element.attr('disabled', 'disabled');
  823. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  824. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").attr("disabled", true);
  825. self.initDragDrop();
  826. },
  827. enable: function (e) {
  828. var self = this;
  829. self.isDisabled = false;
  830. self.$element.removeAttr('disabled');
  831. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  832. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").removeAttr("disabled");
  833. self.initDragDrop();
  834. },
  835. getExtraData: function() {
  836. var self = this, data = self.uploadExtraData;
  837. if (typeof(self.uploadExtraData) == "function") {
  838. data = self.uploadExtraData();
  839. }
  840. return data;
  841. },
  842. uploadExtra: function(fd) {
  843. var self = this, data = self.getExtraData();
  844. if (data.length == 0) {
  845. return;
  846. }
  847. $.each(data, function(key, value) {
  848. if (!isEmpty(key) && !isEmpty(value)) {
  849. fd.append(key, value);
  850. }
  851. });
  852. },
  853. initXhr: function(xhrobj, factor) {
  854. var self = this;
  855. if (xhrobj.upload) {
  856. xhrobj.upload.addEventListener('progress', function(event) {
  857. var pct = 0, position = event.loaded || event.position, total = event.total;
  858. if (event.lengthComputable) {
  859. pct = Math.ceil(position / total * factor);
  860. }
  861. self.uploadPercent = Math.max(pct, self.uploadPercent);
  862. self.setProgress(self.uploadPercent);
  863. }, false);
  864. }
  865. return xhrobj;
  866. },
  867. upload: function(i, files) {
  868. self.formdata = new FormData();
  869. var self = this, total = files.length, formdata = self.formdata,
  870. previewId = self.previewInitId + "-" + i, $thumb = $('#' + previewId),
  871. $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove'),
  872. $indicator = $thumb.find('.file-upload-indicator'), config = self.fileActionSettings;
  873. if (total == 0) {
  874. return;
  875. }
  876. if ($btnUpload.hasClass('disabled')) {
  877. return;
  878. }
  879. var percent,
  880. allFiles = arguments.length > 2,
  881. setIndicator = function (icon, msg) {
  882. $indicator.html(config[icon]);
  883. $indicator.attr('title', config[msg]);
  884. },
  885. updateProgress = function() {
  886. if (!allFiles || total == 0 || self.uploadPercent >= 100) {
  887. return;
  888. }
  889. self.uploadCount++;
  890. var pct = 80 + Math.ceil(self.uploadCount * 20/total);
  891. self.uploadPercent = Math.max(pct, self.uploadPercent);
  892. self.setProgress(self.uploadPercent);
  893. self.initPreviewDeletes();
  894. },
  895. resetActions = function() {
  896. $btnUpload.removeAttr('disabled');
  897. $btnDelete.removeAttr('disabled');
  898. $thumb.removeClass('file-uploading');
  899. };
  900. formdata.append(self.uploadFileAttr, files[i]);
  901. formdata.append('file_id', i);
  902. self.uploadExtra(formdata);
  903. self.ajaxRequests.push($.ajax({
  904. xhr: function() {
  905. var xhrobj = $.ajaxSettings.xhr();
  906. return self.initXhr(xhrobj, 80);
  907. },
  908. url: self.uploadUrl,
  909. type: 'POST',
  910. dataType: 'json',
  911. data: formdata,
  912. cache: false,
  913. processData: false,
  914. contentType: false,
  915. beforeSend: function() {
  916. var outData = self.getOutData();
  917. setIndicator('indicatorLoading', 'indicatorLoadingTitle');
  918. addCss($thumb, 'file-uploading');
  919. $btnUpload.attr('disabled', true);
  920. $btnDelete.attr('disabled', true);
  921. if (!allFiles) {
  922. self.lock();
  923. }
  924. self.raise('filepreupload', [outData, previewId, i])
  925. },
  926. success: function(data, textStatus, jqXHR) {
  927. var outData = self.getOutData(data);
  928. setTimeout(function() {
  929. if(typeof data.error === 'undefined') {
  930. setIndicator('indicatorSuccess', 'indicatorSuccessTitle');
  931. $btnUpload.hide();
  932. $btnDelete.hide();
  933. self.filestack[i] = undefined;
  934. self.raise('fileuploaded', [outData, previewId, i]);
  935. } else {
  936. setIndicator('indicatorError', 'indicatorErrorTitle');
  937. self.showUploadError(data.error, outData, previewId, i);
  938. }
  939. }, 100);
  940. },
  941. complete: function() {
  942. setTimeout(function() {
  943. updateProgress();
  944. resetActions();
  945. }, 100);
  946. },
  947. error: function(jqXHR, textStatus, errorThrown) {
  948. setIndicator('indicatorError', 'indicatorErrorTitle');
  949. var outData = self.getOutData();
  950. if (allFiles) {
  951. var cap = files[i].name;
  952. self.showUploadError('<b>' + cap + '</b>: ' + errorThrown, outData, previewId, i);
  953. } else {
  954. self.showUploadError(errorThrown, outData, previewId, i);
  955. }
  956. }
  957. }));
  958. },
  959. uploadBatch: function() {
  960. var self = this, files = self.filestack, total = files.length;
  961. self.formdata = new FormData();
  962. if (total == 0) {
  963. return;
  964. }
  965. var config = self.fileActionSettings, formdata = self.formdata,
  966. setIndicator = function (i, icon, msg) {
  967. var $indicator = $('#' + self.previewInitId + "-" + i).find('.file-upload-indicator');
  968. $indicator.html(config[icon]);
  969. $indicator.attr('title', config[msg]);
  970. },
  971. enableActions = function (i, disabled) {
  972. var $thumb = $('#' + self.previewInitId + "-" + i),
  973. $btnUpload = $thumb.find('.kv-file-upload'),
  974. $btnDelete = $thumb.find('.kv-file-delete');
  975. $thumb.removeClass('file-uploading');
  976. $btnUpload.removeAttr('disabled');
  977. $btnDelete.removeAttr('disabled');
  978. },
  979. setAllUploaded = function() {
  980. $.each(files, function(key, data) {
  981. self.filestack[key] = undefined;
  982. });
  983. self.clearFileInput();
  984. };
  985. $.each(files, function(key, data) {
  986. if (files[key] !== undefined) {
  987. formdata.append(self.uploadFileAttr, files[key]);
  988. }
  989. });
  990. self.uploadExtra(formdata);
  991. $.ajax({
  992. xhr: function() {
  993. var xhrobj = $.ajaxSettings.xhr();
  994. return self.initXhr(xhrobj, 98);
  995. },
  996. url: self.uploadUrl,
  997. type: 'POST',
  998. dataType: 'json',
  999. data: formdata,
  1000. cache: false,
  1001. processData: false,
  1002. contentType: false,
  1003. beforeSend: function() {
  1004. self.lock();
  1005. var outData = self.getOutData();
  1006. if (!self.showPreview) {
  1007. return;
  1008. }
  1009. self.$preview.find('.file-preview-frame').each(function() {
  1010. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove');
  1011. addCss($thumb, 'file-uploading');
  1012. $btnUpload.attr('disabled', true);
  1013. $btnDelete.attr('disabled', true);
  1014. });
  1015. self.raise('filebatchpreupload', [outData]);
  1016. },
  1017. success: function(data, textStatus, jqXHR) {
  1018. var outData = self.getOutData(data);
  1019. var keys = isEmpty(data.errorkeys) ? [] : data.errorkeys;
  1020. if(typeof data.error === 'undefined' || isEmpty(data.error)) {
  1021. self.raise('filebatchuploadsuccess', [outData]);
  1022. setAllUploaded();
  1023. if (self.showPreview) {
  1024. self.$preview.find('.kv-file-upload').hide();
  1025. self.$preview.find('.kv-file-remove').hide();
  1026. self.$preview.find('.file-preview-frame').each(function() {
  1027. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1028. setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle');
  1029. enableActions(key);
  1030. });
  1031. } else {
  1032. self.reset();
  1033. }
  1034. } else {
  1035. self.$preview.find('.file-preview-frame').each(function() {
  1036. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1037. enableActions(key);
  1038. if (keys.length == 0) {
  1039. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1040. return;
  1041. }
  1042. if ($.inArray(key, keys)) {
  1043. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1044. } else {
  1045. $thumb.find('.kv-file-upload').hide();
  1046. $thumb.find('.kv-file-remove').hide();
  1047. setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle');
  1048. self.filestack[key] = undefined;
  1049. }
  1050. });
  1051. self.showUploadError(data.error, outData, null, null, 'filebatchuploaderror');
  1052. }
  1053. },
  1054. complete: function () {
  1055. self.setProgress(100);
  1056. self.unlock();
  1057. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1058. self.clearFileInput();
  1059. },
  1060. error: function(jqXHR, textStatus, errorThrown) {
  1061. var outData = self.getOutData();
  1062. self.showUploadError(errorThrown, outData, null, null, 'filebatchuploaderror');
  1063. self.uploadFileCount = total - 1;
  1064. self.$preview.find('.file-preview-frame').removeClass('file-uploading');
  1065. self.$preview.find('.file-preview-frame kv-file-upload').removeAttr('disabled');
  1066. self.$preview.find('.file-preview-frame kv-file-delete').removeAttr('disabled');
  1067. }
  1068. });
  1069. },
  1070. hideFileIcon: function () {
  1071. if (this.overwriteInitial) {
  1072. this.$captionContainer.find('.kv-caption-icon').hide();
  1073. }
  1074. },
  1075. showFileIcon: function () {
  1076. this.$captionContainer.find('.kv-caption-icon').show();
  1077. },
  1078. resetErrors: function (fade) {
  1079. var self = this, $error = self.$errorContainer;
  1080. self.isError = false;
  1081. self.$container.removeClass('has-error');
  1082. $error.html('');
  1083. if (fade) {
  1084. $error.fadeOut('slow');
  1085. } else {
  1086. $error.hide();
  1087. }
  1088. },
  1089. showUploadError: function (msg, data, previewId, index) {
  1090. var self = this, $error = self.$errorContainer,
  1091. ev = arguments.length > 4 ? arguments[4] : 'fileuploaderror';
  1092. if ($error.find('ul').length == 0) {
  1093. $error.html('<ul class="text-left"><li>' + msg + '</li></ul>');
  1094. } else {
  1095. $error.find('ul').append('<li>' + msg + '</li>');
  1096. }
  1097. $error.fadeIn(800);
  1098. self.raise(ev, [data, previewId, index, self.reader]);
  1099. addCss(self.$container, 'has-error');
  1100. return true;
  1101. },
  1102. showError: function (msg, file, previewId, index) {
  1103. var self = this, $error = self.$errorContainer,
  1104. ev = arguments.length > 4 ? arguments[4] : 'fileerror';
  1105. $error.html(msg);
  1106. $error.fadeIn(800);
  1107. self.raise(ev, [file, previewId, index, self.reader]);
  1108. if (!self.isUploadable) {
  1109. self.clearFileInput();
  1110. }
  1111. addCss(self.$container, 'has-error');
  1112. self.$btnUpload.attr('disabled', true);
  1113. return true;
  1114. },
  1115. errorHandler: function (evt, caption) {
  1116. var self = this;
  1117. switch (evt.target.error.code) {
  1118. case evt.target.error.NOT_FOUND_ERR:
  1119. self.addError(self.msgFileNotFound.replace(/\{name\}/g, caption));
  1120. break;
  1121. case evt.target.error.NOT_READABLE_ERR:
  1122. self.addError(self.msgFileNotReadable.replace(/\{name\}/g, caption));
  1123. break;
  1124. case evt.target.error.ABORT_ERR:
  1125. self.addError(self.msgFilePreviewAborted.replace(/\{name\}/g, caption));
  1126. break;
  1127. default:
  1128. self.addError(self.msgFilePreviewError.replace(/\{name\}/g, caption));
  1129. }
  1130. },
  1131. parseFileType: function(file) {
  1132. var isValid, vType;
  1133. for (var i = 0; i < defaultPreviewTypes.length; i++) {
  1134. cat = defaultPreviewTypes[i];
  1135. isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  1136. vType = isValid(file.type, file.name) ? cat : '';
  1137. if (vType != '') {
  1138. return vType;
  1139. }
  1140. }
  1141. return 'other';
  1142. },
  1143. previewDefault: function(file, previewId) {
  1144. var self = this;
  1145. if (!self.showPreview) {
  1146. return;
  1147. }
  1148. var data = vUrl.createObjectURL(file), $obj = $('#' + previewId),
  1149. config = self.previewSettings.other,
  1150. footer = self.isUploadable ?
  1151. self.renderFileFooter(file.name, config.width) :
  1152. self.renderFileFooter(file.name, config.width, false),
  1153. previewOtherTemplate = self.getPreviewTemplate('other'),
  1154. ind = previewId.slice(previewId.lastIndexOf('-') + 1),
  1155. frameClass = '';
  1156. if (arguments.length > 2) {
  1157. var $err = $(self.msgValidationError);
  1158. frameClass = ' btn disabled';
  1159. footer += '<div class="file-other-error text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i></div>';
  1160. }
  1161. self.$preview.append("\n" + previewOtherTemplate
  1162. .replace(/\{previewId\}/g, previewId)
  1163. .replace(/\{frameClass\}/g, frameClass)
  1164. .replace(/\{fileindex\}/g, ind)
  1165. .replace(/\{caption\}/g, self.slug(file.name))
  1166. .replace(/\{width\}/g, config.width)
  1167. .replace(/\{height\}/g, config.height)
  1168. .replace(/\{type\}/g, file.type)
  1169. .replace(/\{data\}/g, data)
  1170. .replace(/\{footer\}/g, footer));
  1171. $obj.on('load', function(e) {
  1172. vUrl.revokeObjectURL($obj.attr('data'));
  1173. });
  1174. },
  1175. previewFile: function(file, theFile, previewId, data) {
  1176. var self = this;
  1177. if (!self.showPreview) {
  1178. return;
  1179. }
  1180. var cat = self.parseFileType(file), caption = self.slug(file.name), data, obj, content,
  1181. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes, fType = file.type,
  1182. template = isSet(cat, self.previewTemplates) ? self.previewTemplates[cat] : defaultPreviewTemplates[cat],
  1183. config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat],
  1184. wrapLen = parseInt(self.wrapTextLength), wrapInd = self.wrapIndicator, $preview = self.$preview,
  1185. chkTypes = types.indexOf(cat) >=0, chkMimes = isEmpty(mimes) || (!isEmpty(mimes) && isSet(file.type, mimes)),
  1186. footer = self.renderFileFooter(caption, config.width),
  1187. ind = previewId.slice(previewId.lastIndexOf('-') + 1);
  1188. if (chkTypes && chkMimes) {
  1189. if (cat == 'text') {
  1190. var strText = htmlEncode(theFile.target.result);
  1191. vUrl.revokeObjectURL(data);
  1192. if (strText.length > wrapLen) {
  1193. var id = 'text-' + uniqId(), height = window.innerHeight * .75,
  1194. modal = self.getLayoutTemplate('modal')
  1195. .replace(/\{id\}/g, id)
  1196. .replace(/\{title\}/g, caption)
  1197. .replace(/\{height\}/g, height)
  1198. .replace(/\{body\}/g, strText);
  1199. wrapInd = wrapInd
  1200. .replace(/\{title\}/g, caption)
  1201. .replace(/\{dialog\}/g, "$('#" + id + "').modal('show')");
  1202. strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
  1203. }
  1204. content = template
  1205. .replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption)
  1206. .replace(/\{frameClass\}/g, '')
  1207. .replace(/\{type\}/g, file.type).replace(/\{width\}/g, config.width)
  1208. .replace(/\{height\}/g, config.height).replace(/\{data\}/g, strText)
  1209. .replace(/\{footer\}/g, footer).replace(/\{fileindex\}/g, ind) + modal;
  1210. } else {
  1211. content = template
  1212. .replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption)
  1213. .replace(/\{frameClass\}/g, '')
  1214. .replace(/\{type\}/g, file.type).replace(/\{data\}/g, data)
  1215. .replace(/\{width\}/g, config.width).replace(/\{height\}/g, config.height)
  1216. .replace(/\{footer\}/g, footer).replace(/\{fileindex\}/g, ind);
  1217. }
  1218. $preview.append("\n" + content);
  1219. self.autoSizeImage(previewId);
  1220. } else {
  1221. self.previewDefault(file, previewId);
  1222. }
  1223. },
  1224. slugDefault: function (text) {
  1225. return isEmpty(text) ? '' : text.split(/(\\|\/)/g).pop().replace(/[^\w-.\\\/ ]+/g,'');
  1226. },
  1227. getFileStack: function() {
  1228. var size = 0, self = this;
  1229. return self.filestack.filter(function(n){ return n != undefined });
  1230. },
  1231. readFiles: function (files) {
  1232. this.reader = new FileReader();
  1233. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  1234. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  1235. msgProgress = self.msgProgress, msgSelected = self.msgSelected, fileType = self.previewFileType,
  1236. wrapLen = parseInt(self.wrapTextLength), wrapInd = self.wrapIndicator,
  1237. previewInitId = self.previewInitId, numFiles = files.length, settings = self.fileTypeSettings,
  1238. isText = isSet('text', settings) ? settings['text'] : defaultFileTypeSettings['text'],
  1239. ctr = self.filestack.length,
  1240. throwError = function(msg, file, previewId, index) {
  1241. self.previewDefault(file, previewId, true);
  1242. var outData = self.getOutData({}, files);
  1243. return self.isUploadable ? self.showUploadError(msg, outData, previewId, index) : self.showError(msg, file, previewId, index);
  1244. };
  1245. function readFile(i) {
  1246. if (isEmpty($el.attr('multiple'))) {
  1247. numFiles = 1;
  1248. }
  1249. if (i >= numFiles) {
  1250. $container.removeClass('loading');
  1251. $status.html('');
  1252. return;
  1253. }
  1254. var node = ctr + i, previewId = previewInitId + "-" + node, file = files[i], caption = self.slug(file.name),
  1255. fileSize = (file.size ? file.size : 0) / 1000, checkFile,
  1256. previewData = vUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk,
  1257. fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '),
  1258. fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', '),
  1259. fileExtExpr = isEmpty(fileExt) ? '' : new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  1260. fileSize = fileSize.toFixed(2);
  1261. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  1262. msg = self.msgSizeTooLarge.replace(/\{name\}/g, caption).replace(/\{size\}/g,
  1263. fileSize).replace(/\{maxSize\}/g, self.maxFileSize);
  1264. self.isError = throwError(msg, file, previewId, i);
  1265. return;
  1266. }
  1267. if (!isEmpty(fileTypes) && isArray(fileTypes)) {
  1268. for (j = 0; j < fileTypes.length; j++) {
  1269. typ = fileTypes[j];
  1270. checkFile = settings[typ];
  1271. chk = (checkFile !== undefined && checkFile(file.type, caption));
  1272. fileCount += isEmpty(chk) ? 0 : chk.length;
  1273. }
  1274. if (fileCount == 0) {
  1275. msg = self.msgInvalidFileType.replace(/\{name\}/g, caption).replace(/\{types\}/g, strTypes);
  1276. self.isError = throwError(msg, file, previewId, i);
  1277. return;
  1278. }
  1279. }
  1280. if (fileCount == 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) {
  1281. chk = caption.match(fileExtExpr);
  1282. fileCount += isEmpty(chk) ? 0 : chk.length;
  1283. if (fileCount == 0) {
  1284. msg = self.msgInvalidFileExtension.replace(/\{name\}/g, caption).replace(/\{extensions\}/g, strExt);
  1285. self.isError = throwError(msg, file, previewId, i);
  1286. return;
  1287. }
  1288. }
  1289. if (!self.showPreview) {
  1290. self.filestack.push(file);
  1291. setTimeout(readFile(i + 1), 100);
  1292. self.raise('fileloaded', [file, previewId, i, reader]);
  1293. return;
  1294. }
  1295. if ($preview.length > 0 && typeof FileReader !== "undefined") {
  1296. $status.html(msgLoading.replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles));
  1297. $container.addClass('loading');
  1298. reader.onerror = function (evt) {
  1299. self.errorHandler(evt, caption);
  1300. };
  1301. reader.onload = function (theFile) {
  1302. self.previewFile(file, theFile, previewId, previewData);
  1303. self.initFileActions();
  1304. };
  1305. reader.onloadend = function (e) {
  1306. var msg = msgProgress
  1307. .replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles)
  1308. .replace(/\{percent\}/g, 50).replace(/\{name\}/g, caption);
  1309. setTimeout(function () {
  1310. $status.html(msg);
  1311. vUrl.revokeObjectURL(previewData);
  1312. }, 100);
  1313. setTimeout(function () {
  1314. readFile(i + 1);
  1315. self.updateFileDetails(numFiles);
  1316. }, 100);
  1317. self.raise('fileloaded', [file, previewId, i, reader]);
  1318. };
  1319. reader.onprogress = function (data) {
  1320. if (data.lengthComputable) {
  1321. var progress = parseInt(((data.loaded / data.total) * 100), 10);
  1322. var msg = msgProgress
  1323. .replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles)
  1324. .replace(/\{percent\}/g, progress).replace(/\{name\}/g, caption);
  1325. setTimeout(function () {
  1326. $status.html(msg);
  1327. }, 100);
  1328. }
  1329. };
  1330. if (isText(file.type, caption)) {
  1331. reader.readAsText(file, self.textEncoding);
  1332. } else {
  1333. reader.readAsArrayBuffer(file);
  1334. }
  1335. } else {
  1336. self.previewDefault(file, previewId);
  1337. setTimeout(function() {
  1338. readFile(i + 1);
  1339. self.updateFileDetails(numFiles);
  1340. }, 100);
  1341. self.raise('fileloaded', [file, previewId, i, reader]);
  1342. }
  1343. self.filestack.push(file);
  1344. }
  1345. readFile(0);
  1346. self.updateFileDetails(numFiles, false);
  1347. },
  1348. updateFileDetails: function(numFiles) {
  1349. var self = this, msgSelected = self.msgSelected, $el = self.$element, fileStack = self.getFileStack(),
  1350. name = $el.val() || (fileStack.length && fileStack[0].name) || '', label = self.slug(name),
  1351. n = self.isUploadable ? fileStack.length : numFiles;
  1352. numFiles = self.initialPreviewCount + n,
  1353. log = n > 1 ? msgSelected.replace(/\{n\}/g, numFiles) : label;
  1354. if (self.isError) {
  1355. self.$previewContainer.removeClass('loading');
  1356. self.$previewStatus.html('');
  1357. self.$captionContainer.find('.kv-caption-icon').hide();
  1358. log = self.msgValidationError;
  1359. } else {
  1360. self.showFileIcon();
  1361. }
  1362. self.setCaption(log);
  1363. self.$container.removeClass('file-input-new');
  1364. if (arguments.length == 1) {
  1365. self.raise('fileselect', [numFiles, label]);
  1366. }
  1367. },
  1368. change: function (e) {
  1369. var self = this, $el = self.$element, label = self.slug($el.val()),
  1370. total = 0, $preview = self.$preview, isDragDrop = arguments.length > 1,
  1371. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files,
  1372. msgSelected = self.msgSelected,
  1373. numFiles = !isEmpty(files) ? (files.length + self.initialPreviewCount) : 1, tfiles,
  1374. ctr = self.filestack.length, isAjaxUpload = (self.isUploadable && ctr != 0),
  1375. throwError = function(msg, file, previewId, index) {
  1376. var outData = self.getOutData({}, files);
  1377. return self.isUploadable ? self.showUploadError(msg, outData, previewId, index) : self.showError(msg, file, previewId, index);
  1378. };
  1379. self.resetUpload();
  1380. self.hideFileIcon();
  1381. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  1382. if (isDragDrop) {
  1383. tfiles = files;
  1384. } else {
  1385. if (e.target.files === undefined) {
  1386. tfiles = e.target && e.target.value ? [
  1387. {name: e.target.value.replace(/^.+\\/, '')}
  1388. ] : [];
  1389. } else {
  1390. tfiles = e.target.files;
  1391. }
  1392. }
  1393. if (isEmpty(tfiles) || tfiles.length === 0) {
  1394. if (!isAjaxUpload) {
  1395. self.clear(false);
  1396. }
  1397. self.raise('fileselectnone');
  1398. return;
  1399. }
  1400. self.resetErrors();
  1401. if (!isAjaxUpload) {
  1402. if (!self.overwriteInitial) {
  1403. $preview.html(self.initialPreviewContent);
  1404. } else {
  1405. $preview.html('');
  1406. }
  1407. }
  1408. var total = self.isUploadable ? self.getFileStack().length + tfiles.length : tfiles.length;
  1409. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  1410. var msg = self.msgFilesTooMany.replace(/\{m\}/g, self.maxFileCount).replace(/\{n\}/g, total);
  1411. self.isError = throwError(msg, null, null, null);
  1412. self.$captionContainer.find('.kv-caption-icon').hide();
  1413. self.$caption.html(self.msgValidationError);
  1414. self.$container.removeClass('file-input-new');
  1415. return;
  1416. }
  1417. if (!self.isIE9) {
  1418. self.readFiles(files);
  1419. } else {
  1420. self.updateFileDetails(1);
  1421. }
  1422. self.reader = null;
  1423. },
  1424. autoSizeImage: function(previewId) {
  1425. var self = this, $preview = self.$preview,
  1426. $thumb = $preview.find("#" + previewId),
  1427. $img = $thumb.find('img');
  1428. if (!$img.length) {
  1429. return;
  1430. }
  1431. $img.on('load', function() {
  1432. var w1 = $thumb.width(), w2 = $preview.width();
  1433. if (w1 > w2) {
  1434. $img.css('width', '100%');
  1435. $thumb.css('width', '97%');
  1436. }
  1437. var $cap = $img.closest('.file-preview-frame').find('.file-caption-name');
  1438. if ($cap.length) {
  1439. $cap.width($img.width());
  1440. $cap.attr('title', $cap.text());
  1441. }
  1442. self.raise('fileimageloaded', previewId);
  1443. });
  1444. },
  1445. autoSizeCaption: function() {
  1446. var self = this;
  1447. if (self.$caption.length == 0 || !self.autoFitCaption) {
  1448. return;
  1449. }
  1450. self.$caption.css('width', 0);
  1451. setTimeout(function() {
  1452. var w = self.$captionContainer.width();
  1453. self.$caption.css('width', 0.98 * w);
  1454. }, 50);
  1455. },
  1456. setCaption: function(content) {
  1457. var self = this, title = $('<div>' + content + '</div>').text(),
  1458. icon = self.layoutTemplates['icon'],
  1459. out = icon + title;
  1460. if (self.$caption.length == 0) {
  1461. return;
  1462. }
  1463. self.$caption.html(out);
  1464. self.$caption.attr('title', title);
  1465. self.autoSizeCaption();
  1466. },
  1467. initBrowse: function ($container) {
  1468. var self = this;
  1469. self.$btnFile = $container.find('.btn-file');
  1470. self.$btnFile.append(self.$element);
  1471. },
  1472. createContainer: function () {
  1473. var self = this;
  1474. var $container = $(document.createElement("span")).attr({"class": 'file-input file-input-new'}).html(self.renderMain());
  1475. self.$element.before($container);
  1476. self.initBrowse($container);
  1477. return $container;
  1478. },
  1479. refreshContainer: function () {
  1480. var self = this, $container = self.$container;
  1481. $container.before(self.$element);
  1482. $container.html(self.renderMain());
  1483. self.initBrowse($container);
  1484. },
  1485. renderMain: function () {
  1486. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : '';;
  1487. var preview = self.showPreview ? self.getLayoutTemplate('preview')
  1488. .replace(/\{class\}/g, self.previewClass)
  1489. .replace(/\{dropClass\}/g, dropCss)
  1490. : '';
  1491. var css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass;
  1492. var caption = self.captionTemplate.replace(/\{class\}/g, css + ' kv-fileinput-caption');
  1493. return self.mainTemplate.replace(/\{class\}/g, self.mainClass).
  1494. replace(/\{preview\}/g, preview).
  1495. replace(/\{caption\}/g, caption).
  1496. replace(/\{upload\}/g, self.renderUpload()).
  1497. replace(/\{remove\}/g, self.renderRemove()).
  1498. replace(/\{cancel\}/g, self.renderCancel()).
  1499. replace(/\{browse\}/g, self.renderBrowse());
  1500. },
  1501. renderBrowse: function () {
  1502. var self = this, css = self.browseClass + ' btn-file', status = '';
  1503. if (self.isDisabled) {
  1504. status = ' disabled ';
  1505. }
  1506. return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>';
  1507. },
  1508. renderRemove: function () {
  1509. var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
  1510. if (!self.showRemove) {
  1511. return '';
  1512. }
  1513. if (self.isDisabled) {
  1514. status = ' disabled ';
  1515. }
  1516. return '<button type="button" title="' + self.removeTitle + '" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
  1517. },
  1518. renderCancel: function () {
  1519. var self = this, css = self.cancelClass + ' fileinput-cancel fileinput-cancel-button', status = '';
  1520. if (!self.showCancel) {
  1521. return '';
  1522. }
  1523. return '<button type="button" title="' + self.cancelTitle + '" class="hide ' + css + '">' + self.cancelIcon + self.cancelLabel + '</button>';
  1524. },
  1525. renderUpload: function () {
  1526. var self = this, css = self.uploadClass + ' kv-fileinput-upload', content = '', status = '';
  1527. if (!self.showUpload) {
  1528. return '';
  1529. }
  1530. if (self.isDisabled) {
  1531. status = ' disabled ';
  1532. }
  1533. if (!self.isUploadable || self.isDisabled) {
  1534. content = '<button type="submit" title="' + self.uploadTitle + '"class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
  1535. } else {
  1536. content = '<a href="' + self.uploadUrl + '" title="' + self.uploadTitle + '" class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>';
  1537. }
  1538. return content;
  1539. }
  1540. }
  1541. //FileInput plugin definition
  1542. $.fn.fileinput = function (option) {
  1543. if (!hasFileAPISupport() && !isIE(9)) {
  1544. return;
  1545. }
  1546. var args = Array.apply(null, arguments);
  1547. args.shift();
  1548. return this.each(function () {
  1549. var $this = $(this),
  1550. data = $this.data('fileinput'),
  1551. options = typeof option === 'object' && option;
  1552. if (!data) {
  1553. $this.data('fileinput',
  1554. (data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data()))));
  1555. }
  1556. if (typeof option === 'string') {
  1557. data[option].apply(data, args);
  1558. }
  1559. });
  1560. };
  1561. $.fn.fileinput.defaults = {
  1562. showCaption: true,
  1563. showPreview: true,
  1564. showRemove: true,
  1565. showUpload: true,
  1566. showCancel: true,
  1567. autoFitCaption: true,
  1568. mainClass: '',
  1569. previewClass: '',
  1570. captionClass: '',
  1571. mainTemplate: null,
  1572. initialCaption: '',
  1573. initialPreview: '',
  1574. initialPreviewCount: 0,
  1575. initialPreviewDelimiter: '*$$*',
  1576. initialPreviewConfig: [],
  1577. initialPreviewShowDelete: true,
  1578. overwriteInitial: true,
  1579. layoutTemplates: defaultLayoutTemplates,
  1580. previewTemplates: defaultPreviewTemplates,
  1581. allowedPreviewTypes: defaultPreviewTypes,
  1582. allowedPreviewMimeTypes: null,
  1583. allowedFileTypes: null,
  1584. allowedFileExtensions: null,
  1585. previewSettings: defaultPreviewSettings,
  1586. fileTypeSettings: defaultFileTypeSettings,
  1587. browseLabel: 'Browse &hellip;',
  1588. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  1589. browseClass: 'btn btn-primary',
  1590. removeLabel: 'Remove',
  1591. removeTitle: 'Clear selected files',
  1592. removeIcon: '<i class="glyphicon glyphicon-trash"></i> ',
  1593. removeClass: 'btn btn-default',
  1594. cancelLabel: 'Cancel',
  1595. cancelTitle: 'Abort ongoing upload',
  1596. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  1597. cancelClass: 'btn btn-default',
  1598. uploadLabel: 'Upload',
  1599. uploadTitle: 'Upload selected files',
  1600. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  1601. uploadClass: 'btn btn-default',
  1602. uploadUrl: null,
  1603. uploadExtraData: [],
  1604. uploadAsync: true,
  1605. maxFileSize: 0,
  1606. maxFileCount: 0,
  1607. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>. Please retry your upload!',
  1608. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>. Please retry your upload!',
  1609. msgFileNotFound: 'File "{name}" not found!',
  1610. msgFileNotReadable: 'File "{name}" is not readable.',
  1611. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  1612. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  1613. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  1614. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  1615. msgValidationError: '<span class="text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i> File Upload Error</span>',
  1616. msgErrorClass: 'file-error-message',
  1617. msgLoading: 'Loading file {index} of {files} &hellip;',
  1618. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  1619. msgSelected: '{n} files selected',
  1620. previewFileType: 'image',
  1621. wrapTextLength: 250,
  1622. wrapIndicator: ' <span class="wrap-indicator" title="{title}" onclick="{dialog}">[&hellip;]</span>',
  1623. elCaptionContainer: null,
  1624. elCaptionText: null,
  1625. elPreviewContainer: null,
  1626. elPreviewImage: null,
  1627. elPreviewStatus: null,
  1628. elErrorContainer: null,
  1629. slugCallback: null,
  1630. dropZoneEnabled: true,
  1631. dropZoneTitle: 'Drag & drop files here &hellip;',
  1632. dropZoneTitleClass: 'file-drop-zone-title',
  1633. fileActionSettings: {},
  1634. otherActionButtons: '',
  1635. textEncoding: 'UTF-8'
  1636. };
  1637. $.fn.fileinput.Constructor = FileInput;
  1638. /**
  1639. * Convert automatically file inputs with class 'file'
  1640. * into a bootstrap fileinput control.
  1641. */
  1642. $(document).ready(function () {
  1643. var $input = $('input.file[type=file]'), count = $input.attr('type') != null ? $input.length : 0;
  1644. if (count > 0) {
  1645. $input.fileinput();
  1646. }
  1647. });
  1648. })(window.jQuery);