fileinput.js 40 KB

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