fileinput.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  1. /*!
  2. * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014
  3. * @version 2.4.0
  4. *
  5. * File input styled for Bootstrap 3.0 that utilizes HTML5 File Input's advanced
  6. * features including the FileReader API. This plugin is inspired by the blog article at
  7. * http://www.abeautifulsite.net/blog/2013/08/whipping-file-inputs-into-shape-with-bootstrap-3/
  8. * and Jasny's File Input plugin http://jasny.github.io/bootstrap/javascript/#fileinput
  9. *
  10. * The plugin drastically enhances the file input to preview multiple files on the client before
  11. * upload. In addition it provides the ability to preview content of images and text files.
  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 STYLE_SETTING = 'style="width:{width};height:{height};"';
  20. var PREVIEW_LABEL = ' <div class="text-center"><small>{caption}</small></div>\n';
  21. var OBJECT_PARAMS = ' <param name="controller" value="true" />\n' +
  22. ' <param name="allowFullScreen" value="true" />\n' +
  23. ' <param name="allowScriptAccess" value="always" />\n' +
  24. ' <param name="autoPlay" value="false" />\n' +
  25. ' <param name="autoStart" value="false" />\n'+
  26. ' <param name="quality" value="high" />\n';
  27. var DEFAULT_PREVIEW = '<div class="file-preview-other" ' + STYLE_SETTING + '>\n' +
  28. ' <h2><i class="glyphicon glyphicon-file"></i></h2>\n' +
  29. ' </div>';
  30. var defaultLayoutTemplates = {
  31. main1: '{preview}\n' +
  32. '<div class="input-group {class}">\n' +
  33. ' {caption}\n' +
  34. ' <div class="input-group-btn">\n' +
  35. ' {remove}\n' +
  36. ' {upload}\n' +
  37. ' {browse}\n' +
  38. ' </div>\n' +
  39. '</div>',
  40. main2: '{preview}\n{remove}\n{upload}\n{browse}\n',
  41. preview: '<div class="file-preview {class}">\n' +
  42. ' <div class="close fileinput-remove text-right">&times;</div>\n' +
  43. ' <div class="file-preview-thumbnails"></div>\n' +
  44. ' <div class="clearfix"></div>' +
  45. ' <div class="file-preview-status text-center text-success"></div>\n' +
  46. '</div>',
  47. caption: '<div tabindex="-1" class="form-control file-caption {class}">\n' +
  48. ' <span class="glyphicon glyphicon-file kv-caption-icon"></span><div class="file-caption-name"></div>\n' +
  49. '</div>',
  50. modal: '<div id="{id}" class="modal fade">\n' +
  51. ' <div class="modal-dialog modal-lg">\n' +
  52. ' <div class="modal-content">\n' +
  53. ' <div class="modal-header">\n' +
  54. ' <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>\n' +
  55. ' <h3 class="modal-title">Detailed Preview <small>{title}</small></h3>\n' +
  56. ' </div>\n' +
  57. ' <div class="modal-body">\n' +
  58. ' <textarea class="form-control" style="font-family:Monaco,Consolas,monospace; height: {height}px;" readonly>{body}</textarea>\n' +
  59. ' </div>\n' +
  60. ' </div>\n' +
  61. ' </div>\n' +
  62. '</div>\n'
  63. };
  64. var defaultPreviewTypes = ['image', 'html', 'text', 'video', 'audio', 'flash', 'object'];
  65. var defaultPreviewTemplates = {
  66. generic: '<div class="file-preview-frame" id="{previewId}">\n' +
  67. ' {content}\n' +
  68. '</div>\n',
  69. html: '<div class="file-preview-frame" id="{previewId}">\n' +
  70. ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  71. ' ' + DEFAULT_PREVIEW + '\n' +
  72. ' </object>\n' + PREVIEW_LABEL +
  73. '</div>',
  74. image: '<div class="file-preview-frame" id="{previewId}">\n' +
  75. ' <img src="{data}" class="file-preview-image" title="{caption}" alt="{caption}" ' + STYLE_SETTING + '>\n' +
  76. '</div>\n',
  77. text: '<div class="file-preview-frame" id="{previewId}">\n' +
  78. ' <div class="file-preview-text" title="{caption}" ' + STYLE_SETTING + '>\n' +
  79. ' {data}\n' +
  80. ' </div>\n' +
  81. '</div>\n',
  82. video: '<div class="file-preview-frame" id="{previewId}" title="{caption}" ' + STYLE_SETTING + '>\n' +
  83. ' <video width="{width}" height="{height}" controls>\n' +
  84. ' <source src="{data}" type="{type}">\n' +
  85. ' ' + DEFAULT_PREVIEW + '\n' +
  86. ' </video>\n' + PREVIEW_LABEL +
  87. '</div>\n',
  88. audio: '<div class="file-preview-frame" id="{previewId}" title="{caption}" ' + STYLE_SETTING + '>\n' +
  89. ' <audio controls>\n' +
  90. ' <source src="{data}" type="{type}">\n' +
  91. ' ' + DEFAULT_PREVIEW + '\n' +
  92. ' </audio>\n' + PREVIEW_LABEL +
  93. '</div>\n',
  94. flash: '<div class="file-preview-frame" id="{previewId}" title="{caption}" ' + STYLE_SETTING + '>\n' +
  95. ' <object type="application/x-shockwave-flash" width="{width}" height="{height}" data="{data}">\n' +
  96. OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' +
  97. ' </object>\n' + PREVIEW_LABEL +
  98. '</div>\n',
  99. object: '<div class="file-preview-frame" id="{previewId}" title="{caption}" ' + STYLE_SETTING + '>\n' +
  100. ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  101. ' <param name="movie" value="{caption}" />\n' +
  102. OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' +
  103. ' </object>\n' + PREVIEW_LABEL +
  104. '</div>',
  105. other: '<div class="file-preview-frame" id="{previewId}" title="{caption}" ' + STYLE_SETTING + '>\n' +
  106. ' ' + DEFAULT_PREVIEW + '\n' + PREVIEW_LABEL +
  107. '</div>',
  108. };
  109. var defaultPreviewSettings = {
  110. image: {width: "auto", height: "160px"},
  111. html: {width: "320px", height: "180px"},
  112. text: {width: "160px", height: "160px"},
  113. video: {width: "320px", height: "240px"},
  114. audio: {width: "320px", height: "80px"},
  115. flash: {width: "320px", height: "240px"},
  116. object: {width: "320px", height: "300px"},
  117. other: {width: "160px", height: "120px"}
  118. };
  119. var defaultFileTypeSettings = {
  120. image: function(vType, vName) {
  121. return (typeof vType !== "undefined") ? vType.match('image.*') : vName.match(/\.(gif|png|jpe?g)$/i);
  122. },
  123. html: function(vType, vName) {
  124. return (typeof vType !== "undefined") ? vType == 'text/html' : vName.match(/\.(htm|html)$/i);
  125. },
  126. text: function(vType, vName) {
  127. return (typeof vType !== "undefined") ? vType.match('text.*') : vName.match(/\.(txt|md|csv|nfo|php|ini)$/i);
  128. },
  129. video: function (vType, vName) {
  130. return (typeof vType !== "undefined" && vType.match(/\.video\/(ogg|mp4|webm)$/i)) || vName.match(/\.(og?|mp4|webm)$/i);
  131. },
  132. audio: function (vType, vName) {
  133. return (typeof vType !== "undefined" && vType.match(/\.audio\/(ogg|mp3|wav)$/i)) || vName.match(/\.(ogg|mp3|wav)$/i);
  134. },
  135. flash: function (vType, vName) {
  136. return (typeof vType !== "undefined" && vType == 'application/x-shockwave-flash') || vName.match(/\.(swf)$/i);
  137. },
  138. object: function (vType, vName) {
  139. return true;
  140. },
  141. other: function (vType, vName) {
  142. return true;
  143. },
  144. };
  145. var isEmpty = function (value, trim) {
  146. return value === null || value === undefined || value == []
  147. || value === '' || trim && $.trim(value) === '';
  148. },
  149. isArray = function (a) {
  150. return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]';
  151. },
  152. isSet = function (needle, haystack) {
  153. return (typeof haystack == 'object' && typeof haystack[needle] !== 'undefined');
  154. },
  155. getValue = function (options, param, value) {
  156. return (isEmpty(options) || isEmpty(options[param])) ? value : options[param];
  157. },
  158. getElement = function (options, param, value) {
  159. return (isEmpty(options) || isEmpty(options[param])) ? value : $(options[param]);
  160. },
  161. uniqId = function () {
  162. return Math.round(new Date().getTime() + (Math.random() * 100));
  163. },
  164. hasFileAPISupport = function () {
  165. return window.File && window.FileReader && window.FileList && window.Blob;
  166. },
  167. vUrl = window.URL || window.webkitURL;
  168. var FileInput = function (element, options) {
  169. this.$element = $(element);
  170. if (hasFileAPISupport()) {
  171. this.init(options);
  172. this.listen();
  173. } else {
  174. this.$element.removeClass('file-loading');
  175. }
  176. };
  177. FileInput.prototype = {
  178. constructor: FileInput,
  179. init: function (options) {
  180. var self = this;
  181. self.reader = null;
  182. self.showCaption = options.showCaption;
  183. self.showPreview = options.showPreview;
  184. self.maxFileSize = options.maxFileSize;
  185. self.maxFileCount = options.maxFileCount;
  186. self.msgSizeTooLarge = options.msgSizeTooLarge;
  187. self.msgFilesTooMany = options.msgFilesTooMany;
  188. self.msgFileNotFound = options.msgFileNotFound;
  189. self.msgFileNotReadable = options.msgFileNotReadable;
  190. self.msgFilePreviewAborted = options.msgFilePreviewAborted;
  191. self.msgFilePreviewError = options.msgFilePreviewError;
  192. self.msgValidationError = options.msgValidationError;
  193. self.msgErrorClass = options.msgErrorClass;
  194. self.initialDelimiter = options.initialDelimiter;
  195. self.initialPreview = options.initialPreview;
  196. self.initialCaption = options.initialCaption;
  197. self.initialPreviewCount = options.initialPreviewCount;
  198. self.initialPreviewContent = options.initialPreviewContent;
  199. self.overwriteInitial = options.overwriteInitial;
  200. self.layoutTemplates = options.layoutTemplates;
  201. self.previewTemplates = options.previewTemplates;
  202. self.allowedPreviewTypes = isEmpty(options.allowedPreviewTypes) ? defaultPreviewTypes : options.allowedPreviewTypes;
  203. self.allowedPreviewMimeTypes = options.allowedPreviewMimeTypes;
  204. self.previewSettings = options.previewSettings;
  205. self.fileTypeSettings = options.fileTypeSettings;
  206. self.showRemove = options.showRemove;
  207. self.showUpload = options.showUpload;
  208. self.captionClass = options.captionClass;
  209. self.previewClass = options.previewClass;
  210. self.mainClass = options.mainClass;
  211. self.mainTemplate = self.showCaption ? self.getLayoutTemplate('main1') : self.getLayoutTemplate('main2');
  212. self.captionTemplate = self.getLayoutTemplate('caption');
  213. self.previewGenericTemplate = self.getPreviewTemplate('generic');
  214. self.browseLabel = options.browseLabel;
  215. self.browseIcon = options.browseIcon;
  216. self.browseClass = options.browseClass;
  217. self.removeLabel = options.removeLabel;
  218. self.removeIcon = options.removeIcon;
  219. self.removeClass = options.removeClass;
  220. self.uploadLabel = options.uploadLabel;
  221. self.uploadIcon = options.uploadIcon;
  222. self.uploadClass = options.uploadClass;
  223. self.uploadUrl = options.uploadUrl;
  224. self.msgLoading = options.msgLoading;
  225. self.msgProgress = options.msgProgress;
  226. self.msgSelected = options.msgSelected;
  227. self.previewFileType = options.previewFileType;
  228. self.wrapTextLength = options.wrapTextLength;
  229. self.wrapIndicator = options.wrapIndicator;
  230. self.isError = false;
  231. self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly');
  232. if (isEmpty(self.$element.attr('id'))) {
  233. self.$element.attr('id', uniqId());
  234. }
  235. if (typeof self.$container == 'undefined') {
  236. self.$container = self.createContainer();
  237. } else {
  238. self.refreshContainer();
  239. }
  240. self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption'));
  241. self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name'));
  242. self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview'));
  243. self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails'));
  244. self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status'));
  245. var content = self.initialPreview;
  246. self.initialPreviewCount = isArray(content) ? content.length : (content.length > 0 ? content.split(self.initialDelimiter).length : 0)
  247. self.initPreview();
  248. self.original = {
  249. preview: self.$preview.html(),
  250. caption: self.$caption.html()
  251. };
  252. self.options = options;
  253. self.$element.removeClass('file-loading');
  254. },
  255. getLayoutTemplate: function(t) {
  256. return isSet(t, self.layoutTemplates) ? self.layoutTemplates[t] : defaultLayoutTemplates[t];
  257. },
  258. getPreviewTemplate: function(t) {
  259. return isSet(t, self.previewTemplates) ? self.previewTemplates[t] : defaultPreviewTemplates[t];
  260. },
  261. listen: function () {
  262. var self = this, $el = self.$element, $cap = self.$captionContainer, $btnFile = self.$btnFile;
  263. $el.on('change', $.proxy(self.change, self));
  264. $btnFile.on('click', function (ev) {
  265. self.clear(false);
  266. $cap.focus();
  267. });
  268. $($el[0].form).on('reset', $.proxy(self.reset, self));
  269. self.$container.on('click', '.fileinput-remove:not([disabled])', $.proxy(self.clear, self));
  270. },
  271. refresh: function (options) {
  272. var self = this, params = (arguments.length) ? $.extend(self.options, options) : self.options;
  273. self.init(params);
  274. },
  275. initPreview: function () {
  276. var self = this, html = '', content = self.initialPreview, len = self.initialPreviewCount,
  277. cap = self.initialCaption.length, previewId = "preview-" + uniqId(),
  278. caption = (cap > 0) ? self.initialCaption : self.msgSelected.replace(/\{n\}/g, len);
  279. if (isArray(content) && len > 0) {
  280. for (var i = 0; i < len; i++) {
  281. previewId += '-' + i;
  282. html += self.previewGenericTemplate.replace(/\{previewId\}/g, previewId).replace(/\{content\}/g,
  283. content[i]);
  284. }
  285. if (len > 1 && cap == 0) {
  286. caption = self.msgSelected.replace(/\{n\}/g, len);
  287. }
  288. } else {
  289. if (len > 0) {
  290. var fileList = content.split(self.initialDelimiter);
  291. for (var i = 0; i < len; i++) {
  292. previewId += '-' + i;
  293. html += self.previewGenericTemplate.replace(/\{previewId\}/g, previewId).replace(/\{content\}/g,
  294. fileList[i]);
  295. }
  296. if (len > 1 && cap == 0) {
  297. caption = self.msgSelected.replace(/\{n\}/g, len);
  298. }
  299. } else {
  300. if (cap > 0) {
  301. self.$caption.html(caption);
  302. self.$captionContainer.attr('title', caption);
  303. return;
  304. } else {
  305. return;
  306. }
  307. }
  308. }
  309. self.initialPreviewContent = html;
  310. self.$preview.html(html);
  311. self.$caption.html(caption);
  312. self.$captionContainer.attr('title', caption);
  313. self.$container.removeClass('file-input-new');
  314. },
  315. clearObjects: function() {
  316. var self = this, $preview = self.$preview;
  317. $preview.find('video audio').each(function() {
  318. this.pause();
  319. delete(this);
  320. $(this).remove();
  321. });
  322. $preview.find('img object div').each(function() {
  323. delete(this);
  324. $(this).remove();
  325. });
  326. },
  327. clear: function (e) {
  328. var self = this;
  329. if (e) {
  330. e.preventDefault();
  331. }
  332. if (self.reader instanceof FileReader) {
  333. self.reader.abort();
  334. }
  335. self.$element.val('');
  336. self.resetErrors(true);
  337. if (e !== false) {
  338. self.$element.trigger('change');
  339. self.$element.trigger('fileclear');
  340. }
  341. if (self.overwriteInitial) {
  342. self.initialPreviewCount = 0;
  343. }
  344. if (!self.overwriteInitial && !isEmpty(self.initialPreviewContent)) {
  345. self.showFileIcon();
  346. self.$preview.html(self.original.preview);
  347. self.$caption.html(self.original.caption);
  348. self.$container.removeClass('file-input-new');
  349. } else {
  350. self.clearObjects();
  351. self.$preview.html('');
  352. var cap = (!self.overwriteInitial && self.initialCaption.length > 0) ?
  353. self.original.caption : '';
  354. self.$caption.html(cap);
  355. self.$captionContainer.attr('title', '');
  356. self.$container.removeClass('file-input-new').addClass('file-input-new');
  357. }
  358. self.hideFileIcon();
  359. self.$element.trigger('filecleared');
  360. self.$captionContainer.focus();
  361. },
  362. reset: function (e) {
  363. var self = this;
  364. self.clear(false);
  365. self.$preview.html(self.original.preview);
  366. self.$caption.html(self.original.caption);
  367. self.$container.find('.fileinput-filename').text('');
  368. self.$element.trigger('filereset');
  369. if (self.initialPreview.length > 0) {
  370. self.$container.removeClass('file-input-new');
  371. }
  372. },
  373. disable: function (e) {
  374. var self = this;
  375. self.isDisabled = true;
  376. self.$element.attr('disabled', 'disabled');
  377. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  378. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").attr("disabled", true);
  379. },
  380. enable: function (e) {
  381. var self = this;
  382. self.isDisabled = false;
  383. self.$element.removeAttr('disabled');
  384. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  385. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").removeAttr("disabled");
  386. },
  387. hideFileIcon: function () {
  388. if (this.overwriteInitial) {
  389. this.$captionContainer.find('.kv-caption-icon').hide();
  390. }
  391. },
  392. showFileIcon: function () {
  393. this.$captionContainer.find('.kv-caption-icon').show();
  394. },
  395. resetErrors: function (fade) {
  396. var self = this, $error = self.$previewContainer.find('.kv-fileinput-error');
  397. self.isError = false;
  398. if (fade) {
  399. $error.fadeOut('slow');
  400. } else {
  401. $error.remove();
  402. }
  403. },
  404. showError: function (msg, file, previewId, index) {
  405. var self = this, $error = self.$previewContainer.find('.kv-fileinput-error');
  406. if (isEmpty($error.attr('class'))) {
  407. self.$previewContainer.append(
  408. '<div class="kv-fileinput-error ' + self.msgErrorClass + '">' + msg + '</div>'
  409. );
  410. } else {
  411. $error.html(msg);
  412. }
  413. $error.hide();
  414. $error.fadeIn(800);
  415. self.$element.trigger('fileerror', [file, previewId, index]);
  416. self.$element.val('');
  417. return true;
  418. },
  419. errorHandler: function (evt, caption) {
  420. var self = this;
  421. switch (evt.target.error.code) {
  422. case evt.target.error.NOT_FOUND_ERR:
  423. self.addError(self.msgFileNotFound.replace(/\{name\}/g, caption));
  424. break;
  425. case evt.target.error.NOT_READABLE_ERR:
  426. self.addError(self.msgFileNotReadable.replace(/\{name\}/g, caption));
  427. break;
  428. case evt.target.error.ABORT_ERR:
  429. self.addError(self.msgFilePreviewAborted.replace(/\{name\}/g, caption));
  430. break;
  431. default:
  432. self.addError(self.msgFilePreviewError.replace(/\{name\}/g, caption));
  433. }
  434. },
  435. parseFileType: function(file) {
  436. var isValid, vType;
  437. for (var i = 0; i < defaultPreviewTypes.length; i++) {
  438. cat = defaultPreviewTypes[i];
  439. isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  440. vType = isValid(file.type, file.name) ? cat : '';
  441. if (vType != '') {
  442. return vType;
  443. }
  444. }
  445. return 'other';
  446. },
  447. previewDefault: function(file, previewId) {
  448. var self = this, data = vUrl.createObjectURL(file), $obj = $('#' + previewId),
  449. previewOtherTemplate = isSet('other', self.previewTemplates) ? self.previewTemplates['other'] : defaultPreviewTemplates['other'];
  450. self.$preview.append("\n" + previewOtherTemplate
  451. .replace(/\{previewId\}/g, previewId)
  452. .replace(/\{caption\}/g, file.name)
  453. .replace(/\{type\}/g, file.type)
  454. .replace(/\{data\}/g, data));
  455. $obj.on('load', function(e) {
  456. vUrl.revokeObjectURL($obj.attr('data'));
  457. });
  458. },
  459. previewFile: function(file, theFile, previewId, data) {
  460. var self = this, i, cat = self.parseFileType(file), caption = file.name, data, obj, content,
  461. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes, fType = file.type,
  462. template = isSet(cat, self.previewTemplates) ? self.previewTemplates[cat] : defaultPreviewTemplates[cat],
  463. config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat],
  464. wrapLen = parseInt(self.wrapTextLength), wrapInd = self.wrapIndicator, $preview = self.$preview,
  465. chkTypes = types.indexOf(cat) >=0, chkMimes = isEmpty(mimes) || (!isEmpty(mimes) && isSet(file.type, mimes));
  466. if (chkTypes && chkMimes) {
  467. if (cat == 'text') {
  468. var strText = theFile.target.result;
  469. vUrl.revokeObjectURL(data);
  470. if (strText.length > wrapLen) {
  471. var id = uniqId(), height = window.innerHeight * .75,
  472. modal = self.getLayoutTemplate('modal').replace(/\{id\}/g, id).replace(/\{title\}/g,
  473. caption).replace(/\{body\}/g, strText).replace(/\{height\}/g, height);
  474. wrapInd = wrapInd.replace(/\{title\}/g, caption).replace(/\{dialog\}/g,
  475. "$('#" + id + "').modal('show')");
  476. strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
  477. }
  478. content = template
  479. .replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption)
  480. .replace(/\{type\}/g, file.type).replace(/\{data\}/g, strText)
  481. .replace(/\{width\}/g, config.width).replace(/\{height\}/g, config.height);
  482. } else {
  483. content = template
  484. .replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption)
  485. .replace(/\{type\}/g, file.type).replace(/\{data\}/g, data)
  486. .replace(/\{width\}/g, config.width).replace(/\{height\}/g, config.height);
  487. }
  488. $preview.append("\n" + content);
  489. } else {
  490. self.previewDefault(file, previewId);
  491. }
  492. },
  493. readFiles: function (files) {
  494. this.reader = new FileReader();
  495. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  496. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  497. msgProgress = self.msgProgress, msgSelected = self.msgSelected, fileType = self.previewFileType,
  498. wrapLen = parseInt(self.wrapTextLength), wrapInd = self.wrapIndicator,
  499. previewInitId = "preview-" + uniqId(), numFiles = files.length,
  500. isText = isSet('text', self.fileTypeSettings) ? self.fileTypeSettings['text'] : defaultFileTypeSettings['text'];
  501. function readFile(i) {
  502. if (i >= numFiles) {
  503. $container.removeClass('loading');
  504. $status.html('');
  505. return;
  506. }
  507. var previewId = previewInitId + "-" + i, file = files[i], caption = file.name,
  508. fileSize = (file.size ? file.size : 0) / 1000, previewData = vUrl.createObjectURL(file);
  509. fileSize = fileSize.toFixed(2);
  510. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  511. var msg = self.msgSizeTooLarge.replace(/\{name\}/g, caption).replace(/\{size\}/g,
  512. fileSize).replace(/\{maxSize\}/g, self.maxFileSize);
  513. self.isError = self.showError(msg, file, previewId, i);
  514. return;
  515. }
  516. if (!self.showPreview) {
  517. setTimeout(readFile(i + 1), 1000);
  518. return;
  519. }
  520. if ($preview.length > 0 && typeof FileReader !== "undefined") {
  521. $status.html(msgLoading.replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles));
  522. $container.addClass('loading');
  523. reader.onerror = function (evt) {
  524. self.errorHandler(evt, caption);
  525. };
  526. reader.onload = function (theFile) {
  527. self.previewFile(file, theFile, previewId, previewData);
  528. };
  529. reader.onloadend = function (e) {
  530. var msg = msgProgress
  531. .replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles)
  532. .replace(/\{percent\}/g, 100).replace(/\{name\}/g, caption);
  533. setTimeout(function () {
  534. $status.html(msg);
  535. vUrl.revokeObjectURL(previewData);
  536. }, 1000);
  537. setTimeout(function () {
  538. readFile(i + 1);
  539. }, 1500);
  540. $el.trigger('fileloaded', [file, previewId, i]);
  541. };
  542. reader.onprogress = function (data) {
  543. if (data.lengthComputable) {
  544. var progress = parseInt(((data.loaded / data.total) * 100), 10);
  545. var msg = msgProgress
  546. .replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles)
  547. .replace(/\{percent\}/g, progress).replace(/\{name\}/g, caption);
  548. setTimeout(function () {
  549. $status.html(msg);
  550. }, 1000);
  551. }
  552. };
  553. if (isText(file.type, caption)) {
  554. reader.readAsText(file);
  555. } else {
  556. reader.readAsArrayBuffer(file);
  557. }
  558. } else {
  559. self.previewDefault(file, previewId);
  560. $el.trigger('fileloaded', [file, previewId, i]);
  561. setTimeout(readFile(i + 1), 1000);
  562. }
  563. }
  564. readFile(0);
  565. },
  566. change: function (e) {
  567. var self = this, $el = self.$element, label = $el.val().replace(/\\/g, '/').replace(/.*\//, ''),
  568. total = 0, $preview = self.$preview, files = $el.get(0).files, msgSelected = self.msgSelected,
  569. numFiles = !isEmpty(files) ? (files.length + self.initialPreviewCount) : 1, tfiles;
  570. self.hideFileIcon();
  571. if (e.target.files === undefined) {
  572. tfiles = e.target && e.target.value ? [
  573. {name: e.target.value.replace(/^.+\\/, '')}
  574. ] : [];
  575. } else {
  576. tfiles = e.target.files;
  577. }
  578. if (tfiles.length === 0) {
  579. return;
  580. }
  581. self.resetErrors();
  582. $preview.html('');
  583. if (!self.overwriteInitial) {
  584. $preview.html(self.initialPreviewContent);
  585. }
  586. var total = tfiles.length;
  587. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  588. var msg = self.msgFilesTooMany.replace(/\{m\}/g, self.maxFileCount).replace(/\{n\}/g, total);
  589. self.isError = self.showError(msg, null, null, null);
  590. self.$captionContainer.find('.kv-caption-icon').hide();
  591. self.$caption.html(self.msgValidationError);
  592. self.$container.removeClass('file-input-new');
  593. return;
  594. }
  595. self.readFiles(files);
  596. self.reader = null;
  597. var log = numFiles > 1 ? msgSelected.replace(/\{n\}/g, numFiles) : label;
  598. if (self.isError) {
  599. self.$captionContainer.find('.kv-caption-icon').hide();
  600. log = self.msgValidationError;
  601. } else {
  602. self.showFileIcon();
  603. }
  604. self.$caption.html(log);
  605. self.$captionContainer.attr('title', log);
  606. self.$container.removeClass('file-input-new');
  607. $el.trigger('fileselect', [numFiles, label]);
  608. },
  609. initBrowse: function ($container) {
  610. var self = this;
  611. self.$btnFile = $container.find('.btn-file');
  612. self.$btnFile.append(self.$element);
  613. },
  614. createContainer: function () {
  615. var self = this;
  616. var $container = $(document.createElement("span")).attr({"class": 'file-input file-input-new'}).html(self.renderMain());
  617. self.$element.before($container);
  618. self.initBrowse($container);
  619. return $container;
  620. },
  621. refreshContainer: function () {
  622. var self = this, $container = self.$container;
  623. $container.before(self.$element);
  624. $container.html(self.renderMain());
  625. self.initBrowse($container);
  626. },
  627. renderMain: function () {
  628. var self = this;
  629. var preview = self.showPreview ? self.getLayoutTemplate('preview').replace(/\{class\}/g, self.previewClass) : '';
  630. var css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass;
  631. var caption = self.captionTemplate.replace(/\{class\}/g, css + ' kv-fileinput-caption');
  632. return self.mainTemplate.replace(/\{class\}/g, self.mainClass).
  633. replace(/\{preview\}/g, preview).
  634. replace(/\{caption\}/g, caption).
  635. replace(/\{upload\}/g, self.renderUpload()).
  636. replace(/\{remove\}/g, self.renderRemove()).
  637. replace(/\{browse\}/g, self.renderBrowse());
  638. },
  639. renderBrowse: function () {
  640. var self = this, css = self.browseClass + ' btn-file', status = '';
  641. if (self.isDisabled) {
  642. status = ' disabled ';
  643. }
  644. return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>';
  645. },
  646. renderRemove: function () {
  647. var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
  648. if (!self.showRemove) {
  649. return '';
  650. }
  651. if (self.isDisabled) {
  652. status = ' disabled ';
  653. }
  654. return '<button type="button" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
  655. },
  656. renderUpload: function () {
  657. var self = this, css = self.uploadClass + ' kv-fileinput-upload', content = '', status = '';
  658. if (!self.showUpload) {
  659. return '';
  660. }
  661. if (self.isDisabled) {
  662. status = ' disabled ';
  663. }
  664. if (isEmpty(self.uploadUrl)) {
  665. content = '<button type="submit" class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
  666. } else {
  667. content = '<a href="' + self.uploadUrl + '" class="' + self.uploadClass + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>';
  668. }
  669. return content;
  670. }
  671. }
  672. $.fn.fileinput = function (options) {
  673. if (!hasFileAPISupport()) {
  674. return;
  675. }
  676. return this.each(function () {
  677. var $this = $(this), data = $this.data('fileinput')
  678. if (!data) {
  679. $this.data('fileinput', (data = new FileInput(this, options)))
  680. }
  681. if (typeof options == 'string') {
  682. data[options]()
  683. }
  684. })
  685. };
  686. //FileInput plugin definition
  687. $.fn.fileinput = function (option) {
  688. if (!hasFileAPISupport()) {
  689. return;
  690. }
  691. var args = Array.apply(null, arguments);
  692. args.shift();
  693. return this.each(function () {
  694. var $this = $(this),
  695. data = $this.data('fileinput'),
  696. options = typeof option === 'object' && option;
  697. if (!data) {
  698. $this.data('fileinput',
  699. (data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data()))));
  700. }
  701. if (typeof option === 'string') {
  702. data[option].apply(data, args);
  703. }
  704. });
  705. };
  706. $.fn.fileinput.defaults = {
  707. showCaption: true,
  708. showPreview: true,
  709. showRemove: true,
  710. showUpload: true,
  711. mainClass: '',
  712. previewClass: '',
  713. captionClass: '',
  714. mainTemplate: null,
  715. initialDelimiter: '*$$*',
  716. initialPreview: '',
  717. initialCaption: '',
  718. initialPreviewCount: 0,
  719. initialPreviewContent: '',
  720. overwriteInitial: true,
  721. layoutTemplates: defaultLayoutTemplates,
  722. previewTemplates: defaultPreviewTemplates,
  723. allowedPreviewTypes: defaultPreviewTypes,
  724. allowedPreviewMimeTypes: null,
  725. previewSettings: defaultPreviewSettings,
  726. fileTypeSettings: defaultFileTypeSettings,
  727. browseLabel: 'Browse &hellip;',
  728. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  729. browseClass: 'btn btn-primary',
  730. removeLabel: 'Remove',
  731. removeIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  732. removeClass: 'btn btn-default',
  733. uploadLabel: 'Upload',
  734. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  735. uploadClass: 'btn btn-default',
  736. uploadUrl: null,
  737. maxFileSize: 0,
  738. maxFileCount: 0,
  739. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>. Please retry your upload!',
  740. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>. Please retry your upload!',
  741. msgFileNotFound: 'File "{name}" not found!',
  742. msgFileNotReadable: 'File "{name}" is not readable.',
  743. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  744. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  745. msgValidationError: '<span class="text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i> File Upload Error</span>',
  746. msgErrorClass: 'file-error-message',
  747. msgLoading: 'Loading file {index} of {files} &hellip;',
  748. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  749. msgSelected: '{n} files selected',
  750. previewFileType: 'image',
  751. wrapTextLength: 250,
  752. wrapIndicator: ' <span class="wrap-indicator" title="{title}" onclick="{dialog}">[&hellip;]</span>',
  753. elCaptionContainer: null,
  754. elCaptionText: null,
  755. elPreviewContainer: null,
  756. elPreviewImage: null,
  757. elPreviewStatus: null
  758. };
  759. /**
  760. * Convert automatically file inputs with class 'file'
  761. * into a bootstrap fileinput control.
  762. */
  763. $(document).ready(function () {
  764. var $input = $('input.file[type=file]'), count = $input.attr('type') != null ? $input.length : 0;
  765. if (count > 0) {
  766. $input.fileinput();
  767. }
  768. });
  769. })(window.jQuery);