fileinput.js 43 KB

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