fileinput.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. /*!
  2. * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014
  3. * @version 2.6.0
  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.
  11. *
  12. * Author: Kartik Visweswaran
  13. * Copyright: 2014, Kartik Visweswaran, Krajee.com
  14. * For more JQuery plugins visit http://plugins.krajee.com
  15. * For more Yii related demos visit http://demos.krajee.com
  16. */
  17. (function ($) {
  18. var STYLE_SETTING = 'style="width:{width};height:{height};"';
  19. var PREVIEW_LABEL = ' <div class="text-center"><small>{caption}</small></div>\n';
  20. var OBJECT_PARAMS = ' <param name="controller" value="true" />\n' +
  21. ' <param name="allowFullScreen" value="true" />\n' +
  22. ' <param name="allowScriptAccess" value="always" />\n' +
  23. ' <param name="autoPlay" value="false" />\n' +
  24. ' <param name="autoStart" value="false" />\n'+
  25. ' <param name="quality" value="high" />\n';
  26. var DEFAULT_PREVIEW = '<div class="file-preview-other" ' + STYLE_SETTING + '>\n' +
  27. ' <h2><i class="glyphicon glyphicon-file"></i></h2>\n' +
  28. ' </div>';
  29. var defaultLayoutTemplates = {
  30. main1: '{preview}\n' +
  31. '<div class="input-group {class}">\n' +
  32. ' {caption}\n' +
  33. ' <div class="input-group-btn">\n' +
  34. ' {remove}\n' +
  35. ' {upload}\n' +
  36. ' {browse}\n' +
  37. ' </div>\n' +
  38. '</div>',
  39. main2: '{preview}\n{remove}\n{upload}\n{browse}\n',
  40. preview: '<div class="file-preview {class}">\n' +
  41. ' <div class="close fileinput-remove text-right">&times;</div>\n' +
  42. ' <div class="file-preview-thumbnails"></div>\n' +
  43. ' <div class="clearfix"></div>' +
  44. ' <div class="file-preview-status text-center text-success"></div>\n' +
  45. ' <div class="kv-fileinput-error"></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' && needle in haystack);
  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. htmlEncode = function(str) {
  168. return String(str)
  169. .replace(/&/g, '&amp;')
  170. .replace(/"/g, '&quot;')
  171. .replace(/'/g, '&#39;')
  172. .replace(/</g, '&lt;')
  173. .replace(/>/g, '&gt;');
  174. },
  175. vUrl = window.URL || window.webkitURL;
  176. var FileInput = function (element, options) {
  177. this.$element = $(element);
  178. if (hasFileAPISupport()) {
  179. this.init(options);
  180. this.listen();
  181. } else {
  182. this.$element.removeClass('file-loading');
  183. }
  184. };
  185. FileInput.prototype = {
  186. constructor: FileInput,
  187. init: function (options) {
  188. var self = this;
  189. self.reader = null;
  190. self.showCaption = options.showCaption;
  191. self.showPreview = options.showPreview;
  192. self.maxFileSize = options.maxFileSize;
  193. self.maxFileCount = options.maxFileCount;
  194. self.msgSizeTooLarge = options.msgSizeTooLarge;
  195. self.msgFilesTooMany = options.msgFilesTooMany;
  196. self.msgFileNotFound = options.msgFileNotFound;
  197. self.msgFileNotReadable = options.msgFileNotReadable;
  198. self.msgFilePreviewAborted = options.msgFilePreviewAborted;
  199. self.msgFilePreviewError = options.msgFilePreviewError;
  200. self.msgValidationError = options.msgValidationError;
  201. self.msgErrorClass = options.msgErrorClass;
  202. self.initialDelimiter = options.initialDelimiter;
  203. self.initialPreview = options.initialPreview;
  204. self.initialCaption = options.initialCaption;
  205. self.initialPreviewCount = options.initialPreviewCount;
  206. self.initialPreviewContent = options.initialPreviewContent;
  207. self.overwriteInitial = options.overwriteInitial;
  208. self.layoutTemplates = options.layoutTemplates;
  209. self.previewTemplates = options.previewTemplates;
  210. self.allowedPreviewTypes = isEmpty(options.allowedPreviewTypes) ? defaultPreviewTypes : options.allowedPreviewTypes;
  211. self.allowedPreviewMimeTypes = options.allowedPreviewMimeTypes;
  212. self.allowedFileTypes = options.allowedFileTypes;
  213. self.allowedFileExtensions = options.allowedFileExtensions;
  214. self.previewSettings = options.previewSettings;
  215. self.fileTypeSettings = options.fileTypeSettings;
  216. self.showRemove = options.showRemove;
  217. self.showUpload = options.showUpload;
  218. self.captionClass = options.captionClass;
  219. self.previewClass = options.previewClass;
  220. self.mainClass = options.mainClass;
  221. self.mainTemplate = self.showCaption ? self.getLayoutTemplate('main1') : self.getLayoutTemplate('main2');
  222. self.captionTemplate = self.getLayoutTemplate('caption');
  223. self.previewGenericTemplate = self.getPreviewTemplate('generic');
  224. self.browseLabel = options.browseLabel;
  225. self.browseIcon = options.browseIcon;
  226. self.browseClass = options.browseClass;
  227. self.removeLabel = options.removeLabel;
  228. self.removeIcon = options.removeIcon;
  229. self.removeClass = options.removeClass;
  230. self.uploadLabel = options.uploadLabel;
  231. self.uploadIcon = options.uploadIcon;
  232. self.uploadClass = options.uploadClass;
  233. self.uploadUrl = options.uploadUrl;
  234. self.msgLoading = options.msgLoading;
  235. self.msgProgress = options.msgProgress;
  236. self.msgSelected = options.msgSelected;
  237. self.msgInvalidFileType = options.msgInvalidFileType;
  238. self.msgInvalidFileExtension = options.msgInvalidFileExtension;
  239. self.previewFileType = options.previewFileType;
  240. self.wrapTextLength = options.wrapTextLength;
  241. self.wrapIndicator = options.wrapIndicator;
  242. self.isError = false;
  243. self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly');
  244. if (isEmpty(self.$element.attr('id'))) {
  245. self.$element.attr('id', uniqId());
  246. }
  247. if (typeof self.$container == 'undefined') {
  248. self.$container = self.createContainer();
  249. } else {
  250. self.refreshContainer();
  251. }
  252. self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption'));
  253. self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name'));
  254. self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview'));
  255. self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails'));
  256. self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status'));
  257. self.$errorContainer = getElement(options, 'elErrorContainer', self.$previewContainer.find('.kv-fileinput-error'));
  258. if (!isEmpty(self.msgErrorClass)) {
  259. self.$errorContainer.removeClass(self.msgErrorClass).addClass(self.msgErrorClass);
  260. }
  261. self.$errorContainer.hide();
  262. var content = self.initialPreview;
  263. self.initialPreviewCount = isArray(content) ? content.length : (content.length > 0 ? content.split(self.initialDelimiter).length : 0)
  264. self.initPreview();
  265. self.original = {
  266. preview: self.$preview.html(),
  267. caption: self.$caption.html()
  268. };
  269. self.options = options;
  270. self.$element.removeClass('file-loading');
  271. },
  272. getLayoutTemplate: function(t) {
  273. var self = this;
  274. return isSet(t, self.layoutTemplates) ? self.layoutTemplates[t] : defaultLayoutTemplates[t];
  275. },
  276. getPreviewTemplate: function(t) {
  277. var self = this;
  278. return isSet(t, self.previewTemplates) ? self.previewTemplates[t] : defaultPreviewTemplates[t];
  279. },
  280. listen: function () {
  281. var self = this, $el = self.$element, $cap = self.$captionContainer, $btnFile = self.$btnFile;
  282. $el.on('change', $.proxy(self.change, self));
  283. $btnFile.on('click', function (ev) {
  284. self.clear(false);
  285. $cap.focus();
  286. });
  287. $el.closest('form').on('reset', $.proxy(self.reset, self));
  288. self.$container.on('click', '.fileinput-remove:not([disabled])', $.proxy(self.clear, self));
  289. },
  290. refresh: function (options) {
  291. var self = this, params = (arguments.length) ? $.extend(self.options, options) : self.options;
  292. self.init(params);
  293. },
  294. initPreview: function () {
  295. var self = this, html = '', content = self.initialPreview, len = self.initialPreviewCount,
  296. cap = self.initialCaption.length, previewId = "preview-" + uniqId(),
  297. caption = (cap > 0) ? self.initialCaption : self.msgSelected.replace(/\{n\}/g, len),
  298. title = $(caption).text();
  299. if (isArray(content) && len > 0) {
  300. for (var i = 0; i < len; i++) {
  301. previewId += '-' + i;
  302. html += self.previewGenericTemplate.replace(/\{previewId\}/g, previewId).replace(/\{content\}/g,
  303. content[i]);
  304. }
  305. if (len > 1 && cap == 0) {
  306. caption = self.msgSelected.replace(/\{n\}/g, len);
  307. }
  308. } else {
  309. if (len > 0) {
  310. var fileList = content.split(self.initialDelimiter);
  311. for (var i = 0; i < len; i++) {
  312. previewId += '-' + i;
  313. html += self.previewGenericTemplate.replace(/\{previewId\}/g, previewId).replace(/\{content\}/g,
  314. fileList[i]);
  315. }
  316. if (len > 1 && cap == 0) {
  317. caption = self.msgSelected.replace(/\{n\}/g, len);
  318. }
  319. } else {
  320. if (cap > 0) {
  321. self.$caption.html(caption);
  322. self.$captionContainer.attr('title', title);
  323. return;
  324. } else {
  325. return;
  326. }
  327. }
  328. }
  329. self.initialPreviewContent = html;
  330. self.$preview.html(html);
  331. self.$caption.html(caption);
  332. self.$captionContainer.attr('title', title);
  333. self.$container.removeClass('file-input-new');
  334. },
  335. clearObjects: function() {
  336. var self = this, $preview = self.$preview;
  337. $preview.find('video audio').each(function() {
  338. this.pause();
  339. delete(this);
  340. $(this).remove();
  341. });
  342. $preview.find('img object div').each(function() {
  343. delete(this);
  344. $(this).remove();
  345. });
  346. },
  347. clearFileInput: function() {
  348. var self = this, $el = self.$element;
  349. if (isEmpty($el.val())) {
  350. return;
  351. }
  352. // Fix for IE ver < 11, that does not clear file inputs
  353. // Requires a sequence of steps to prevent IE crashing but
  354. // still allow clearing of the file input.
  355. if (/MSIE/.test(navigator.userAgent)) {
  356. var $frm1 = $el.closest('form');
  357. if ($frm1.length) {
  358. $el.wrap('<form>');
  359. var $frm2 = $el.closest('form'), $tmpEl = $(document.createElement('div'));
  360. $frm2.before($tmpEl).after($frm1).trigger('reset');
  361. $el.unwrap().appendTo($tmpEl).unwrap();
  362. } else {
  363. $el.wrap('<form>').closest('form').trigger('reset').unwrap();
  364. }
  365. } else { // normal input clear behavior for other sane browsers
  366. $el.val('');
  367. }
  368. },
  369. clear: function () {
  370. var self = this, e = arguments.length && arguments[0];
  371. if (e) {
  372. e.preventDefault();
  373. }
  374. if (self.reader instanceof FileReader) {
  375. self.reader.abort();
  376. }
  377. self.clearFileInput();
  378. self.resetErrors(true);
  379. if (e !== false) {
  380. self.$element.trigger('change');
  381. self.$element.trigger('fileclear');
  382. }
  383. if (self.overwriteInitial) {
  384. self.initialPreviewCount = 0;
  385. }
  386. if (!self.overwriteInitial && !isEmpty(self.initialPreviewContent)) {
  387. self.showFileIcon();
  388. self.$preview.html(self.original.preview);
  389. self.$caption.html(self.original.caption);
  390. self.$container.removeClass('file-input-new');
  391. } else {
  392. self.clearObjects();
  393. self.$preview.html('');
  394. var cap = (!self.overwriteInitial && self.initialCaption.length > 0) ?
  395. self.original.caption : '';
  396. self.$caption.html(cap);
  397. self.$captionContainer.attr('title', '');
  398. self.$container.removeClass('file-input-new').addClass('file-input-new');
  399. }
  400. self.hideFileIcon();
  401. self.$element.trigger('filecleared');
  402. self.$captionContainer.focus();
  403. },
  404. reset: function (e) {
  405. var self = this;
  406. self.clear(false);
  407. self.$preview.html(self.original.preview);
  408. self.$caption.html(self.original.caption);
  409. self.$container.find('.fileinput-filename').text('');
  410. self.$element.trigger('filereset');
  411. if (self.initialPreview.length > 0) {
  412. self.$container.removeClass('file-input-new');
  413. }
  414. },
  415. disable: function (e) {
  416. var self = this;
  417. self.isDisabled = true;
  418. self.$element.attr('disabled', 'disabled');
  419. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  420. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").attr("disabled", true);
  421. },
  422. enable: function (e) {
  423. var self = this;
  424. self.isDisabled = false;
  425. self.$element.removeAttr('disabled');
  426. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  427. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").removeAttr("disabled");
  428. },
  429. hideFileIcon: function () {
  430. if (this.overwriteInitial) {
  431. this.$captionContainer.find('.kv-caption-icon').hide();
  432. }
  433. },
  434. showFileIcon: function () {
  435. this.$captionContainer.find('.kv-caption-icon').show();
  436. },
  437. resetErrors: function (fade) {
  438. var self = this, $error = self.$errorContainer;
  439. self.isError = false;
  440. self.$container.removeClass('has-error');
  441. if (fade) {
  442. $error.fadeOut('slow');
  443. } else {
  444. $error.hide();
  445. }
  446. },
  447. showError: function (msg, file, previewId, index) {
  448. var self = this, $error = self.$errorContainer, $el = self.$element;
  449. $error.html(msg);
  450. $error.fadeIn(800);
  451. $el.trigger('fileerror', [file, previewId, index]);
  452. self.clearFileInput();
  453. self.$container.removeClass('has-error').addClass('has-error');
  454. return true;
  455. },
  456. errorHandler: function (evt, caption) {
  457. var self = this;
  458. switch (evt.target.error.code) {
  459. case evt.target.error.NOT_FOUND_ERR:
  460. self.addError(self.msgFileNotFound.replace(/\{name\}/g, caption));
  461. break;
  462. case evt.target.error.NOT_READABLE_ERR:
  463. self.addError(self.msgFileNotReadable.replace(/\{name\}/g, caption));
  464. break;
  465. case evt.target.error.ABORT_ERR:
  466. self.addError(self.msgFilePreviewAborted.replace(/\{name\}/g, caption));
  467. break;
  468. default:
  469. self.addError(self.msgFilePreviewError.replace(/\{name\}/g, caption));
  470. }
  471. },
  472. parseFileType: function(file) {
  473. var isValid, vType;
  474. for (var i = 0; i < defaultPreviewTypes.length; i++) {
  475. cat = defaultPreviewTypes[i];
  476. isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  477. vType = isValid(file.type, file.name) ? cat : '';
  478. if (vType != '') {
  479. return vType;
  480. }
  481. }
  482. return 'other';
  483. },
  484. previewDefault: function(file, previewId) {
  485. var self = this, data = vUrl.createObjectURL(file), $obj = $('#' + previewId),
  486. previewOtherTemplate = isSet('other', self.previewTemplates) ? self.previewTemplates['other'] : defaultPreviewTemplates['other'];
  487. self.$preview.append("\n" + previewOtherTemplate
  488. .replace(/\{previewId\}/g, previewId)
  489. .replace(/\{caption\}/g, self.slug(file.name))
  490. .replace(/\{type\}/g, file.type)
  491. .replace(/\{data\}/g, data));
  492. $obj.on('load', function(e) {
  493. vUrl.revokeObjectURL($obj.attr('data'));
  494. });
  495. },
  496. previewFile: function(file, theFile, previewId, data) {
  497. var self = this, i, cat = self.parseFileType(file), caption = self.slug(file.name), data, obj, content,
  498. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes, fType = file.type,
  499. template = isSet(cat, self.previewTemplates) ? self.previewTemplates[cat] : defaultPreviewTemplates[cat],
  500. config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat],
  501. wrapLen = parseInt(self.wrapTextLength), wrapInd = self.wrapIndicator, $preview = self.$preview,
  502. chkTypes = types.indexOf(cat) >=0, chkMimes = isEmpty(mimes) || (!isEmpty(mimes) && isSet(file.type, mimes));
  503. if (chkTypes && chkMimes) {
  504. if (cat == 'text') {
  505. var strText = htmlEncode(theFile.target.result);
  506. vUrl.revokeObjectURL(data);
  507. if (strText.length > wrapLen) {
  508. var id = 'text-' + uniqId(), height = window.innerHeight * .75,
  509. modal = self.getLayoutTemplate('modal')
  510. .replace(/\{id\}/g, id)
  511. .replace(/\{title\}/g, caption)
  512. .replace(/\{height\}/g, height)
  513. .replace(/\{body\}/g, strText);
  514. wrapInd = wrapInd
  515. .replace(/\{title\}/g, caption)
  516. .replace(/\{dialog\}/g, "$('#" + id + "').modal('show')");
  517. strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
  518. }
  519. content = template
  520. .replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption)
  521. .replace(/\{type\}/g, file.type).replace(/\{width\}/g, config.width)
  522. .replace(/\{height\}/g, config.height).replace(/\{data\}/g, strText) + modal;
  523. } else {
  524. content = template
  525. .replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption)
  526. .replace(/\{type\}/g, file.type).replace(/\{data\}/g, data)
  527. .replace(/\{width\}/g, config.width).replace(/\{height\}/g, config.height);
  528. }
  529. $preview.append("\n" + content);
  530. } else {
  531. self.previewDefault(file, previewId);
  532. }
  533. },
  534. readFiles: function (files) {
  535. this.reader = new FileReader();
  536. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  537. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  538. msgProgress = self.msgProgress, msgSelected = self.msgSelected, fileType = self.previewFileType,
  539. wrapLen = parseInt(self.wrapTextLength), wrapInd = self.wrapIndicator,
  540. previewInitId = "preview-" + uniqId(), numFiles = files.length, settings = self.fileTypeSettings,
  541. isText = isSet('text', settings) ? settings['text'] : defaultFileTypeSettings['text'];
  542. function readFile(i) {
  543. if (i >= numFiles) {
  544. $container.removeClass('loading');
  545. $status.html('');
  546. return;
  547. }
  548. var previewId = previewInitId + "-" + i, file = files[i], caption = self.slug(file.name),
  549. fileSize = (file.size ? file.size : 0) / 1000, checkFile,
  550. previewData = vUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk,
  551. fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '),
  552. fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', '),
  553. fileExtExpr = isEmpty(fileExt) ? '' : new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  554. fileSize = fileSize.toFixed(2);
  555. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  556. msg = self.msgSizeTooLarge.replace(/\{name\}/g, caption).replace(/\{size\}/g,
  557. fileSize).replace(/\{maxSize\}/g, self.maxFileSize);
  558. self.isError = self.showError(msg, file, previewId, i);
  559. return;
  560. }
  561. if (!isEmpty(fileTypes) && isArray(fileTypes)) {
  562. for (j = 0; j < fileTypes.length; j++) {
  563. typ = fileTypes[j];
  564. checkFile = settings[typ];
  565. chk = (checkFile !== undefined && checkFile(file.type, caption));
  566. fileCount += isEmpty(chk) ? 0 : chk.length;
  567. }
  568. if (fileCount == 0) {
  569. msg = self.msgInvalidFileType.replace(/\{name\}/g, caption).replace(/\{types\}/g, strTypes);
  570. self.isError = self.showError(msg, file, previewId, i);
  571. return;
  572. }
  573. }
  574. if (fileCount == 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) {
  575. chk = caption.match(fileExtExpr);
  576. fileCount += isEmpty(chk) ? 0 : chk.length;
  577. if (fileCount == 0) {
  578. msg = self.msgInvalidFileExtension.replace(/\{name\}/g, caption).replace(/\{extensions\}/g, strExt);
  579. self.isError = self.showError(msg, file, previewId, i);
  580. return;
  581. }
  582. }
  583. if (!self.showPreview) {
  584. setTimeout(readFile(i + 1), 1000);
  585. return;
  586. }
  587. if ($preview.length > 0 && typeof FileReader !== "undefined") {
  588. $status.html(msgLoading.replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles));
  589. $container.addClass('loading');
  590. reader.onerror = function (evt) {
  591. self.errorHandler(evt, caption);
  592. };
  593. reader.onload = function (theFile) {
  594. self.previewFile(file, theFile, previewId, previewData);
  595. };
  596. reader.onloadend = function (e) {
  597. var msg = msgProgress
  598. .replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles)
  599. .replace(/\{percent\}/g, 100).replace(/\{name\}/g, caption);
  600. setTimeout(function () {
  601. $status.html(msg);
  602. vUrl.revokeObjectURL(previewData);
  603. }, 1000);
  604. setTimeout(function () {
  605. readFile(i + 1);
  606. }, 1500);
  607. $el.trigger('fileloaded', [file, previewId, i]);
  608. };
  609. reader.onprogress = function (data) {
  610. if (data.lengthComputable) {
  611. var progress = parseInt(((data.loaded / data.total) * 100), 10);
  612. var msg = msgProgress
  613. .replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles)
  614. .replace(/\{percent\}/g, progress).replace(/\{name\}/g, caption);
  615. setTimeout(function () {
  616. $status.html(msg);
  617. }, 1000);
  618. }
  619. };
  620. if (isText(file.type, caption)) {
  621. reader.readAsText(file);
  622. } else {
  623. reader.readAsArrayBuffer(file);
  624. }
  625. } else {
  626. self.previewDefault(file, previewId);
  627. $el.trigger('fileloaded', [file, previewId, i]);
  628. setTimeout(readFile(i + 1), 1000);
  629. }
  630. }
  631. readFile(0);
  632. },
  633. slug: function (text) {
  634. return isEmpty(text) ? '' : text.split(/(\\|\/)/g).pop().replace(/[^\w-.\\\/ ]+/g,'');
  635. },
  636. change: function (e) {
  637. var self = this, $el = self.$element, label = self.slug($el.val()),
  638. total = 0, $preview = self.$preview, files = $el.get(0).files, msgSelected = self.msgSelected,
  639. numFiles = !isEmpty(files) ? (files.length + self.initialPreviewCount) : 1, tfiles;
  640. self.hideFileIcon();
  641. if (e.target.files === undefined) {
  642. tfiles = e.target && e.target.value ? [
  643. {name: e.target.value.replace(/^.+\\/, '')}
  644. ] : [];
  645. } else {
  646. tfiles = e.target.files;
  647. }
  648. if (tfiles.length === 0) {
  649. return;
  650. }
  651. self.resetErrors();
  652. $preview.html('');
  653. if (!self.overwriteInitial) {
  654. $preview.html(self.initialPreviewContent);
  655. }
  656. var total = tfiles.length;
  657. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  658. var msg = self.msgFilesTooMany.replace(/\{m\}/g, self.maxFileCount).replace(/\{n\}/g, total);
  659. self.isError = self.showError(msg, null, null, null);
  660. self.$captionContainer.find('.kv-caption-icon').hide();
  661. self.$caption.html(self.msgValidationError);
  662. self.$container.removeClass('file-input-new');
  663. return;
  664. }
  665. self.readFiles(files);
  666. self.reader = null;
  667. var log = numFiles > 1 ? msgSelected.replace(/\{n\}/g, numFiles) : label;
  668. if (self.isError) {
  669. self.$captionContainer.find('.kv-caption-icon').hide();
  670. log = self.msgValidationError;
  671. } else {
  672. self.showFileIcon();
  673. }
  674. self.$caption.html(log);
  675. self.$captionContainer.attr('title', $(log).text());
  676. self.$container.removeClass('file-input-new');
  677. $el.trigger('fileselect', [numFiles, label]);
  678. },
  679. initBrowse: function ($container) {
  680. var self = this;
  681. self.$btnFile = $container.find('.btn-file');
  682. self.$btnFile.append(self.$element);
  683. },
  684. createContainer: function () {
  685. var self = this;
  686. var $container = $(document.createElement("span")).attr({"class": 'file-input file-input-new'}).html(self.renderMain());
  687. self.$element.before($container);
  688. self.initBrowse($container);
  689. return $container;
  690. },
  691. refreshContainer: function () {
  692. var self = this, $container = self.$container;
  693. $container.before(self.$element);
  694. $container.html(self.renderMain());
  695. self.initBrowse($container);
  696. },
  697. renderMain: function () {
  698. var self = this;
  699. var preview = self.showPreview ? self.getLayoutTemplate('preview').replace(/\{class\}/g, self.previewClass) : '';
  700. var css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass;
  701. var caption = self.captionTemplate.replace(/\{class\}/g, css + ' kv-fileinput-caption');
  702. return self.mainTemplate.replace(/\{class\}/g, self.mainClass).
  703. replace(/\{preview\}/g, preview).
  704. replace(/\{caption\}/g, caption).
  705. replace(/\{upload\}/g, self.renderUpload()).
  706. replace(/\{remove\}/g, self.renderRemove()).
  707. replace(/\{browse\}/g, self.renderBrowse());
  708. },
  709. renderBrowse: function () {
  710. var self = this, css = self.browseClass + ' btn-file', status = '';
  711. if (self.isDisabled) {
  712. status = ' disabled ';
  713. }
  714. return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>';
  715. },
  716. renderRemove: function () {
  717. var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
  718. if (!self.showRemove) {
  719. return '';
  720. }
  721. if (self.isDisabled) {
  722. status = ' disabled ';
  723. }
  724. return '<button type="button" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
  725. },
  726. renderUpload: function () {
  727. var self = this, css = self.uploadClass + ' kv-fileinput-upload', content = '', status = '';
  728. if (!self.showUpload) {
  729. return '';
  730. }
  731. if (self.isDisabled) {
  732. status = ' disabled ';
  733. }
  734. if (isEmpty(self.uploadUrl)) {
  735. content = '<button type="submit" class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
  736. } else {
  737. content = '<a href="' + self.uploadUrl + '" class="' + self.uploadClass + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>';
  738. }
  739. return content;
  740. }
  741. }
  742. //FileInput plugin definition
  743. $.fn.fileinput = function (option) {
  744. if (!hasFileAPISupport()) {
  745. return;
  746. }
  747. var args = Array.apply(null, arguments);
  748. args.shift();
  749. return this.each(function () {
  750. var $this = $(this),
  751. data = $this.data('fileinput'),
  752. options = typeof option === 'object' && option;
  753. if (!data) {
  754. $this.data('fileinput',
  755. (data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data()))));
  756. }
  757. if (typeof option === 'string') {
  758. data[option].apply(data, args);
  759. }
  760. });
  761. };
  762. $.fn.fileinput.defaults = {
  763. showCaption: true,
  764. showPreview: true,
  765. showRemove: true,
  766. showUpload: true,
  767. mainClass: '',
  768. previewClass: '',
  769. captionClass: '',
  770. mainTemplate: null,
  771. initialDelimiter: '*$$*',
  772. initialPreview: '',
  773. initialCaption: '',
  774. initialPreviewCount: 0,
  775. initialPreviewContent: '',
  776. overwriteInitial: true,
  777. layoutTemplates: defaultLayoutTemplates,
  778. previewTemplates: defaultPreviewTemplates,
  779. allowedPreviewTypes: defaultPreviewTypes,
  780. allowedPreviewMimeTypes: null,
  781. allowedFileTypes: null,
  782. allowedFileExtensions: null,
  783. previewSettings: defaultPreviewSettings,
  784. fileTypeSettings: defaultFileTypeSettings,
  785. browseLabel: 'Browse &hellip;',
  786. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  787. browseClass: 'btn btn-primary',
  788. removeLabel: 'Remove',
  789. removeIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  790. removeClass: 'btn btn-default',
  791. uploadLabel: 'Upload',
  792. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  793. uploadClass: 'btn btn-default',
  794. uploadUrl: null,
  795. maxFileSize: 0,
  796. maxFileCount: 0,
  797. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>. Please retry your upload!',
  798. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>. Please retry your upload!',
  799. msgFileNotFound: 'File "{name}" not found!',
  800. msgFileNotReadable: 'File "{name}" is not readable.',
  801. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  802. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  803. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  804. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  805. msgValidationError: '<span class="text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i> File Upload Error</span>',
  806. msgErrorClass: 'file-error-message',
  807. msgLoading: 'Loading file {index} of {files} &hellip;',
  808. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  809. msgSelected: '{n} files selected',
  810. previewFileType: 'image',
  811. wrapTextLength: 250,
  812. wrapIndicator: ' <span class="wrap-indicator" title="{title}" onclick="{dialog}">[&hellip;]</span>',
  813. elCaptionContainer: null,
  814. elCaptionText: null,
  815. elPreviewContainer: null,
  816. elPreviewImage: null,
  817. elPreviewStatus: null,
  818. elErrorContainer: null
  819. };
  820. /**
  821. * Convert automatically file inputs with class 'file'
  822. * into a bootstrap fileinput control.
  823. */
  824. $(document).ready(function () {
  825. var $input = $('input.file[type=file]'), count = $input.attr('type') != null ? $input.length : 0;
  826. if (count > 0) {
  827. $input.fileinput();
  828. }
  829. });
  830. })(window.jQuery);