fileinput.js 40 KB

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