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