fileinput.js 43 KB

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