fileinput.js 44 KB

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