fileinput.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /*!
  2. * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014
  3. * @version 1.8.0
  4. *
  5. * File input styled for Bootstrap 3.0 that utilizes HTML5 File Input's advanced
  6. * features including the FileReader API. This plugin is inspired by the blog article at
  7. * http://www.abeautifulsite.net/blog/2013/08/whipping-file-inputs-into-shape-with-bootstrap-3/
  8. * and Jasny's File Input plugin http://jasny.github.io/bootstrap/javascript/#fileinput
  9. *
  10. * The plugin drastically enhances the file input to preview multiple files on the client before
  11. * upload. In addition it provides the ability to preview content of images and text files.
  12. *
  13. * Author: Kartik Visweswaran
  14. * Copyright: 2013, Kartik Visweswaran, Krajee.com
  15. * For more JQuery plugins visit http://plugins.krajee.com
  16. * For more Yii related demos visit http://demos.krajee.com
  17. */
  18. (function ($) {
  19. var MAIN_TEMPLATE_1 = '{preview}\n' +
  20. '<div class="input-group {class}">\n' +
  21. ' {caption}\n' +
  22. ' <div class="input-group-btn">\n' +
  23. ' {remove}\n' +
  24. ' {upload}\n' +
  25. ' {browse}\n' +
  26. ' </div>\n' +
  27. '</div>';
  28. var MAIN_TEMPLATE_2 = '{preview}\n{remove}\n{upload}\n{browse}\n';
  29. var PREVIEW_TEMPLATE = '<div class="file-preview {class}">\n' +
  30. ' <div class="file-preview-status text-center text-success"></div>\n' +
  31. ' <div class="close fileinput-remove text-right">&times;</div>\n' +
  32. ' <div class="file-preview-thumbnails"></div>\n' +
  33. ' <div class="clearfix"></div>' +
  34. '</div>';
  35. var CAPTION_TEMPLATE = '<div class="form-control file-caption {class}">\n' +
  36. ' <span class="glyphicon glyphicon-file kv-caption-icon"></span><div class="file-caption-name"></div>\n' +
  37. '</div>';
  38. var MODAL_TEMPLATE = '<div id="{id}" class="modal fade">\n' +
  39. ' <div class="modal-dialog modal-lg">\n' +
  40. ' <div class="modal-content">\n' +
  41. ' <div class="modal-header">\n' +
  42. ' <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>\n' +
  43. ' <h3 class="modal-title">Detailed Preview <small>{title}</small></h3>\n' +
  44. ' </div>\n' +
  45. ' <div class="modal-body">\n' +
  46. ' <textarea class="form-control" style="font-family:Monaco,Consolas,monospace; height: {height}px;" readonly>{body}</textarea>\n' +
  47. ' </div>\n' +
  48. ' </div>\n' +
  49. ' </div>\n' +
  50. '</div>\n';
  51. var isEmpty = function (value, trim) {
  52. return value === null || value === undefined || value == []
  53. || value === '' || trim && $.trim(value) === '';
  54. };
  55. var isArray = Array.isArray || function (a) {
  56. return Object.prototype.toString.call(a) === '[object Array]';
  57. };
  58. var getValue = function (options, param, value) {
  59. return (isEmpty(options) || isEmpty(options[param])) ? value : options[param];
  60. };
  61. var getElement = function (options, param, value) {
  62. return (isEmpty(options) || isEmpty(options[param])) ? value : $(options[param]);
  63. };
  64. var isImageFile = function (type, name) {
  65. return (typeof type !== "undefined") ? type.match('image.*') : name.match(/\.(gif|png|jpe?g)$/i);
  66. };
  67. var isTextFile = function (type, name) {
  68. return (typeof type !== "undefined") ? type.match('text.*') : name.match(/\.(txt|md|csv|htm|html|php|ini)$/i);
  69. };
  70. var uniqId = function () {
  71. return Math.round(new Date().getTime() + (Math.random() * 100));
  72. };
  73. var FileInput = function (element, options) {
  74. this.$element = $(element);
  75. this.init(options);
  76. this.listen();
  77. };
  78. FileInput.prototype = {
  79. constructor: FileInput,
  80. init: function (options) {
  81. var self = this;
  82. self.showCaption = options.showCaption;
  83. self.showPreview = options.showPreview;
  84. self.initialPreview = options.initialPreview;
  85. self.initialCaption = options.initialCaption;
  86. self.overwriteInitial = options.overwriteInitial;
  87. self.showRemove = options.showRemove;
  88. self.showUpload = options.showUpload;
  89. self.captionClass = options.captionClass;
  90. self.previewClass = options.previewClass;
  91. self.mainClass = options.mainClass;
  92. if (isEmpty(options.mainTemplate)) {
  93. self.mainTemplate = self.showCaption ? MAIN_TEMPLATE_1 : MAIN_TEMPLATE_2;
  94. }
  95. else {
  96. self.mainTemplate = options.mainTemplate;
  97. }
  98. self.previewTemplate = (self.showPreview) ? options.previewTemplate : '';
  99. self.captionTemplate = options.captionTemplate;
  100. self.browseLabel = options.browseLabel;
  101. self.browseIcon = options.browseIcon;
  102. self.browseClass = options.browseClass;
  103. self.removeLabel = options.removeLabel;
  104. self.removeIcon = options.removeIcon;
  105. self.removeClass = options.removeClass;
  106. self.uploadLabel = options.uploadLabel;
  107. self.uploadIcon = options.uploadIcon;
  108. self.uploadClass = options.uploadClass;
  109. self.uploadUrl = options.uploadUrl;
  110. self.msgLoading = options.msgLoading;
  111. self.msgProgress = options.msgProgress;
  112. self.msgSelected = options.msgSelected;
  113. self.previewFileType = options.previewFileType;
  114. self.wrapTextLength = options.wrapTextLength;
  115. self.wrapIndicator = options.wrapIndicator;
  116. self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly');
  117. if (isEmpty(self.$element.attr('id'))) {
  118. self.$element.attr('id', uniqId());
  119. }
  120. if (typeof self.$container == 'undefined') {
  121. self.$container = self.createContainer();
  122. }
  123. else {
  124. self.refreshContainer();
  125. }
  126. /* Initialize plugin option parameters */
  127. self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption'));
  128. self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name'));
  129. self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview'));
  130. self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails'));
  131. self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status'));
  132. self.initPreview();
  133. self.original = {
  134. preview: self.$preview.html(),
  135. caption: self.$caption.html()
  136. };
  137. this.options = options;
  138. self.$element.removeClass('file-loading');
  139. },
  140. listen: function () {
  141. var self = this;
  142. self.$element.on('change', $.proxy(self.change, self));
  143. $(self.$element[0].form).on('reset', $.proxy(self.reset, self));
  144. self.$container.find('.fileinput-remove').on('click', $.proxy(self.clear, self));
  145. },
  146. refresh: function (options) {
  147. var self = this, params = (arguments.length) ? $.extend(self.options, options) : self.options;
  148. self.init(params);
  149. },
  150. initPreview: function () {
  151. var self = this, html = '',
  152. content = self.initialPreview,
  153. len = self.initialPreview.length,
  154. cap = self.initialCaption.length,
  155. caption = (cap > 0) ? self.initialCaption : len + ' file selected';
  156. if (isArray(content) && len > 0) {
  157. for (var i = 0; i < len; i++) {
  158. html += '<div class="file-preview-frame">' + content[i] + "</div>\n";
  159. }
  160. if (len > 1 && cap == 0) {
  161. caption = len + ' files selected';
  162. }
  163. }
  164. else if (len > 0) {
  165. html = '<div class="file-preview-frame">' + content + '</div>';
  166. }
  167. else if (cap > 0) {
  168. self.$caption.html(caption);
  169. self.$captionContainer.attr('title', caption);
  170. self.$captionContainer.find('.kv-caption-icon').show();
  171. return;
  172. }
  173. else {
  174. return;
  175. }
  176. self.initialPreviewContent = html;
  177. self.$preview.html(html);
  178. self.$caption.html(caption);
  179. self.$captionContainer.attr('title', caption);
  180. self.$container.removeClass('file-input-new');
  181. },
  182. clear: function (e) {
  183. var self = this;
  184. if (e) {
  185. e.preventDefault();
  186. }
  187. self.$element.val('');
  188. if (e !== false) {
  189. self.$element.trigger('change');
  190. self.$element.trigger('fileclear');
  191. }
  192. if (!self.overwriteInitial && !isEmpty(self.initialPreviewContent)) {
  193. self.$preview.html(self.original.preview);
  194. self.$caption.html(self.original.caption);
  195. self.$container.removeClass('file-input-new');
  196. }
  197. else {
  198. self.$preview.html('');
  199. var cap = (!self.overwriteInitial && self.initialCaption.length > 0) ?
  200. self.original.caption : '';
  201. self.$caption.html(cap);
  202. self.$captionContainer.attr('title', '');
  203. self.$container.removeClass('file-input-new').addClass('file-input-new');
  204. }
  205. if (self.overwriteInitial) {
  206. self.$captionContainer.find('.kv-caption-icon').hide();
  207. }
  208. },
  209. reset: function (e) {
  210. var self = this;
  211. self.clear(false);
  212. self.$preview.html(self.original.preview);
  213. self.$caption.html(self.original.caption);
  214. self.$container.find('.fileinput-filename').text('');
  215. self.$element.trigger('filereset');
  216. if (self.initialPreview.length > 0) {
  217. self.$container.removeClass('file-input-new');
  218. }
  219. },
  220. change: function (e) {
  221. var self = this;
  222. var elem = self.$element, files = elem.get(0).files, numFiles = files ? files.length : 1,
  223. label = elem.val().replace(/\\/g, '/').replace(/.*\//, ''), $preview = self.$preview,
  224. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  225. msgProgress = self.msgProgress, msgSelected = self.msgSelected, tfiles,
  226. fileType = self.previewFileType, wrapLen = parseInt(self.wrapTextLength),
  227. wrapInd = self.wrapIndicator;
  228. if (e.target.files === undefined) {
  229. tfiles = e.target && e.target.value ? [
  230. {name: e.target.value.replace(/^.+\\/, '')}
  231. ] : [];
  232. }
  233. else {
  234. tfiles = e.target.files;
  235. }
  236. if (tfiles.length === 0) {
  237. return;
  238. }
  239. $preview.html('');
  240. if (!self.overwriteInitial) {
  241. $preview.html(self.initialPreviewContent);
  242. }
  243. var total = tfiles.length;
  244. for (var i = 0; i < total; i++) {
  245. (function (file) {
  246. var caption = file.name;
  247. var isImg = isImageFile(file.type, file.name);
  248. var isTxt = isTextFile(file.type, file.name);
  249. if ($preview.length > 0 && (fileType == "any" ? (isImg || isTxt) : (fileType == "text" ? isTxt : isImg)) && typeof FileReader !== "undefined") {
  250. var reader = new FileReader();
  251. $status.html(msgLoading);
  252. $container.addClass('loading');
  253. reader.onload = function (theFile) {
  254. var content = '', modal = '';
  255. if (isTxt) {
  256. var strText = theFile.target.result;
  257. if (strText.length > wrapLen) {
  258. var id = uniqId(), height = window.innerHeight * .75,
  259. modal = MODAL_TEMPLATE.replace("{id}", id).replace("{title}", caption).replace("{body}", strText).replace("{height}", height);
  260. wrapInd = wrapInd.replace("{title}", caption).replace("{dialog}", "$('#" + id + "').modal('show')");
  261. strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
  262. }
  263. content = '<div class="file-preview-frame"><div class="file-preview-text" title="' + caption + '">' + strText + '</div></div>' + modal;
  264. }
  265. else {
  266. content = '<div class="file-preview-frame"><img src="' + theFile.target.result + '" class="file-preview-image" title="' + caption + '" alt="' + caption + '"></div>';
  267. }
  268. $preview.append("\n" + content);
  269. if (i >= total - 1) {
  270. $container.removeClass('loading');
  271. $status.html('');
  272. }
  273. };
  274. reader.onprogress = function (data) {
  275. if (data.lengthComputable) {
  276. var progress = parseInt(((data.loaded / data.total) * 100), 10);
  277. var msg = msgProgress.replace('{percent}', progress).replace('{file}', file.name);
  278. $status.html(msg);
  279. }
  280. };
  281. if (isTxt) {
  282. reader.readAsText(file);
  283. }
  284. else {
  285. reader.readAsDataURL(file);
  286. }
  287. }
  288. else {
  289. $preview.append("\n" + '<div class="file-preview-frame"><div class="file-preview-other"><h2><i class="glyphicon glyphicon-file"></i></h2>' + caption + '</div></div>');
  290. }
  291. })(tfiles[i]);
  292. }
  293. var log = numFiles > 1 ? msgSelected.replace('{n}', numFiles) : label;
  294. self.$caption.html(log);
  295. self.$captionContainer.attr('title', log);
  296. self.$container.removeClass('file-input-new');
  297. elem.trigger('fileselect', [numFiles, label]);
  298. },
  299. createContainer: function () {
  300. var self = this;
  301. var container = $(document.createElement("div")).attr({"class": 'file-input file-input-new'}).html(self.renderMain());
  302. self.$element.before(container);
  303. container.find('.btn-file').append(self.$element);
  304. return container;
  305. },
  306. refreshContainer: function () {
  307. var self = this;
  308. self.$container.before(self.$element);
  309. self.$container.html(self.renderMain());
  310. self.$container.find('.btn-file').append(self.$element);
  311. },
  312. renderMain: function () {
  313. var self = this;
  314. var preview = self.previewTemplate.replace('{class}', self.previewClass);
  315. var css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass;
  316. var caption = self.captionTemplate.replace('{class}', css);
  317. return self.mainTemplate.replace('{class}', self.mainClass).
  318. replace('{preview}', preview).
  319. replace('{caption}', caption).
  320. replace('{upload}', self.renderUpload()).
  321. replace('{remove}', self.renderRemove()).
  322. replace('{browse}', self.renderBrowse());
  323. },
  324. renderBrowse: function () {
  325. var self = this, css = self.browseClass + ' btn-file', status = '';
  326. if (self.isDisabled) {
  327. status = ' disabled ';
  328. }
  329. return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>';
  330. },
  331. renderRemove: function () {
  332. var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
  333. if (!self.showRemove) {
  334. return '';
  335. }
  336. if (self.isDisabled) {
  337. status = ' disabled ';
  338. }
  339. return '<button type="button" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
  340. },
  341. renderUpload: function () {
  342. var self = this, content = '', status = '';
  343. if (!self.showUpload) {
  344. return '';
  345. }
  346. if (self.isDisabled) {
  347. status = ' disabled ';
  348. }
  349. if (isEmpty(self.uploadUrl)) {
  350. content = '<button type="submit" class="' + self.uploadClass + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
  351. }
  352. else {
  353. content = '<a href="' + self.uploadUrl + '" class="' + self.uploadClass + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>';
  354. }
  355. return content;
  356. },
  357. }
  358. $.fn.fileinput = function (options) {
  359. return this.each(function () {
  360. var $this = $(this), data = $this.data('fileinput')
  361. if (!data) {
  362. $this.data('fileinput', (data = new FileInput(this, options)))
  363. }
  364. if (typeof options == 'string') {
  365. data[options]()
  366. }
  367. })
  368. };
  369. //FileInput plugin definition
  370. $.fn.fileinput = function (option) {
  371. var args = Array.apply(null, arguments);
  372. args.shift();
  373. return this.each(function () {
  374. var $this = $(this),
  375. data = $this.data('fileinput'),
  376. options = typeof option === 'object' && option;
  377. if (!data) {
  378. $this.data('fileinput', (data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data()))));
  379. }
  380. if (typeof option === 'string') {
  381. data[option].apply(data, args);
  382. }
  383. });
  384. };
  385. $.fn.fileinput.defaults = {
  386. showCaption: true,
  387. showPreview: true,
  388. showRemove: true,
  389. showUpload: true,
  390. captionClass: '',
  391. previewClass: '',
  392. mainClass: '',
  393. mainTemplate: null,
  394. initialPreview: '',
  395. initialCaption: '',
  396. initialPreviewContent: '',
  397. overwriteInitial: true,
  398. previewTemplate: PREVIEW_TEMPLATE,
  399. captionTemplate: CAPTION_TEMPLATE,
  400. browseLabel: 'Browse &hellip;',
  401. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  402. browseClass: 'btn btn-primary',
  403. removeLabel: 'Remove',
  404. removeIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  405. removeClass: 'btn btn-default',
  406. uploadLabel: 'Upload',
  407. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  408. uploadClass: 'btn btn-default',
  409. uploadUrl: null,
  410. msgLoading: 'Loading &hellip;',
  411. msgProgress: 'Loaded {percent}% of {file}',
  412. msgSelected: '{n} files selected',
  413. previewFileType: 'image',
  414. wrapTextLength: 250,
  415. wrapIndicator: ' <span class="wrap-indicator" title="{title}" onclick="{dialog}">[&hellip;]</span>',
  416. elCaptionContainer: null,
  417. elCaptionText: null,
  418. elPreviewContainer: null,
  419. elPreviewImage: null,
  420. elPreviewStatus: null
  421. };
  422. /**
  423. * Convert automatically file inputs with class 'file'
  424. * into a bootstrap fileinput control.
  425. */
  426. $(document).ready(function () {
  427. var $input = $('input.file[type=file]'), count = Object.keys($input).length;
  428. if (count > 0) {
  429. $input.fileinput();
  430. }
  431. });
  432. })(window.jQuery);