fileinput.js 41 KB

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