fileinput.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. /*!
  2. * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2013
  3. * @version 1.0.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 =
  20. '{preview}\n' +
  21. '<div class="input-group {class}">\n' +
  22. ' {caption}\n' +
  23. ' <div class="input-group-btn">\n' +
  24. ' {remove}\n' +
  25. ' {upload}\n' +
  26. ' {browse}\n' +
  27. ' </div>\n' +
  28. '</div>';
  29. var MAIN_TEMPLATE_2 = '{preview}\n{remove}\n{upload}\n{browse}\n';
  30. var PREVIEW_TEMPLATE =
  31. '<div class="file-preview {class}">\n' +
  32. ' <div class="file-preview-status text-center text-success"></div>\n' +
  33. ' <div class="close fileinput-remove text-right">&times;</div>\n' +
  34. ' <div class="file-preview-thumbnails"></div>\n' +
  35. ' <div class="clearfix"></div>' +
  36. '</div>';
  37. var CAPTION_TEMPLATE =
  38. '<div class="form-control file-caption {class}">\n' +
  39. ' <span class="glyphicon glyphicon-file"></span> <span class="file-caption-name"></span>\n' +
  40. '</div>';
  41. var isEmpty = function(value, trim) {
  42. return value === null || value === undefined || value == []
  43. || value === '' || trim && $.trim(value) === '';
  44. };
  45. var getValue = function(options, param, value) {
  46. return (isEmpty(options) || isEmpty(options[param])) ? value : options[param];
  47. };
  48. var isImageFile = function(type, name) {
  49. return (typeof type !== "undefined") ? type.match('image.*') : name.match(/\.(gif|png|jpe?g)$/i);
  50. };
  51. var isTextFile = function(type, name) {
  52. return (typeof type !== "undefined") ? type.match('text.*') : name.match(/\.(txt|md|csv|htm|html|php|ini)$/i);
  53. };
  54. var uniqId = function() {
  55. return Math.round(new Date().getTime() + (Math.random() * 100));
  56. };
  57. var FileInput = function(element, options) {
  58. this.$element = $(element);
  59. this.showCaption = options.showCaption;
  60. this.showPreview = options.showPreview;
  61. this.showRemove = options.showRemove;
  62. this.showUpload = options.showUpload;
  63. this.captionClass = options.captionClass;
  64. this.previewClass = options.previewClass;
  65. this.mainClass = options.mainClass;
  66. if (isEmpty(options.mainTemplate)) {
  67. this.mainTemplate = this.showCaption ? MAIN_TEMPLATE_1 : MAIN_TEMPLATE_2;
  68. }
  69. else {
  70. this.mainTemplate = options.mainTemplate;
  71. }
  72. this.previewTemplate = options.previewTemplate;
  73. this.captionTemplate = options.captionTemplate;
  74. this.browseLabel = options.browseLabel;
  75. this.browseIcon = options.browseIcon;
  76. this.browseClass = options.browseClass;
  77. this.removeLabel = options.removeLabel;
  78. this.removeIcon = options.removeIcon;
  79. this.removeClass = options.removeClass;
  80. this.uploadLabel = options.uploadLabel;
  81. this.uploadIcon = options.uploadIcon;
  82. this.uploadClass = options.uploadClass;
  83. this.uploadUrl = options.uploadUrl;
  84. this.msgLoading = options.msgLoading;
  85. this.msgProgress = options.msgProgress;
  86. this.msgSelected = options.msgSelected;
  87. this.previewFileType = options.previewFileType;
  88. this.wrapTextLength = options.wrapTextLength;
  89. this.wrapIndicator = options.wrapIndicator;
  90. this.isDisabled = this.$element.attr('disabled') || this.$element.attr('readonly');
  91. if (isEmpty(this.$element.attr('id'))) {
  92. this.$element.attr('id', uniqId());
  93. }
  94. this.$container = this.createContainer();
  95. /* Initialize plugin option parameters */
  96. this.$captionContainer = getValue(options, 'elCaptionContainer', this.$container.find('.file-caption'));
  97. this.$caption = getValue(options, 'elCaptionText', this.$container.find('.file-caption-name'));
  98. this.$previewContainer = getValue(options, 'elPreviewContainer', this.$container.find('.file-preview'));
  99. this.$preview = getValue(options, 'elPreviewImage', this.$container.find('.file-preview-thumbnails'));
  100. this.$previewStatus = getValue(options, 'elPreviewStatus', this.$container.find('.file-preview-status'));
  101. this.$name = this.$element.attr('name') || options.name;
  102. this.$hidden = this.$container.find('input[type=hidden][name="' + this.$name + '"]');
  103. if (this.$hidden.length === 0) {
  104. this.$hidden = $('<input type="hidden" />');
  105. this.$container.prepend(this.$hidden);
  106. }
  107. this.original = {
  108. preview: this.$preview.html(),
  109. hiddenVal: this.$hidden.val()
  110. };
  111. this.listen()
  112. };
  113. FileInput.prototype = {
  114. constructor: FileInput,
  115. listen: function() {
  116. var self = this;
  117. self.$element.on('change', $.proxy(self.change, self));
  118. $(self.$element[0].form).on('reset', $.proxy(self.reset, self));
  119. self.$container.find('.fileinput-remove').on('click', $.proxy(self.clear, self));
  120. },
  121. trigger: function(e) {
  122. var self = this;
  123. self.$element.trigger('click');
  124. e.preventDefault();
  125. },
  126. clear: function(e) {
  127. var self = this;
  128. if (e) {
  129. e.preventDefault();
  130. }
  131. self.$hidden.val('');
  132. self.$hidden.attr('name', self.name);
  133. self.$element.attr('name', '');
  134. self.$element.val('');
  135. if (e !== false) {
  136. self.$element.trigger('change');
  137. self.$element.trigger('fileclear');
  138. }
  139. self.$preview.html('');
  140. self.$caption.html('');
  141. self.$container.removeClass('file-input-new').addClass('file-input-new');
  142. },
  143. reset: function(e) {
  144. var self = this;
  145. self.clear(false);
  146. self.$hidden.val(self.original.hiddenVal);
  147. self.$preview.html(self.original.preview);
  148. self.$container.find('.fileinput-filename').text('');
  149. self.$element.trigger('filereset');
  150. },
  151. change: function(e) {
  152. var self = this;
  153. var elem = self.$element, files = elem.get(0).files, numFiles = files ? files.length : 1,
  154. label = elem.val().replace(/\\/g, '/').replace(/.*\//, ''), preview = self.$preview,
  155. container = self.$previewContainer, status = self.$previewStatus, msgLoading = self.msgLoading,
  156. msgProgress = self.msgProgress, msgSelected = self.msgSelected, tfiles,
  157. fileType = self.previewFileType, wrapLen = parseInt(self.wrapTextLength),
  158. wrapInd = self.wrapIndicator;
  159. if (e.target.files === undefined) {
  160. tfiles = e.target && e.target.value ? [{name: e.target.value.replace(/^.+\\/, '')}] : [];
  161. }
  162. else {
  163. tfiles = e.target.files;
  164. }
  165. if (tfiles.length === 0) {
  166. return;
  167. }
  168. preview.html('');
  169. var total = tfiles.length, self = self;
  170. for (var i = 0; i < total; i++) {
  171. (function(file) {
  172. var caption = file.name;
  173. var isImg = isImageFile(file.type, file.name);
  174. var isTxt = isTextFile(file.type, file.name);
  175. if (preview.length > 0 && (fileType == "any" ? (isImg || isTxt) : (fileType == "text" ? isTxt : isImg)) && typeof FileReader !== "undefined") {
  176. var reader = new FileReader();
  177. status.html(msgLoading);
  178. container.addClass('loading');
  179. reader.onload = function(theFile) {
  180. var content = '';
  181. if (isTxt) {
  182. var strText = theFile.target.result;
  183. if (strText.length > wrapLen) {
  184. wrapInd = wrapInd.replace("{title}", strText);
  185. strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
  186. }
  187. content = '<div class="file-preview-frame"><div class="file-preview-text" title="' + caption + '">' + strText + '</div></div>';
  188. }
  189. else {
  190. content = '<div class="file-preview-frame"><img src="' + theFile.target.result + '" class="file-preview-image" title="' + caption + '" alt="' + caption + '"></div>';
  191. }
  192. preview.append("\n" + content);
  193. if (i >= total - 1) {
  194. container.removeClass('loading');
  195. status.html('');
  196. }
  197. };
  198. reader.onprogress = function(data) {
  199. if (data.lengthComputable) {
  200. var progress = parseInt(((data.loaded / data.total) * 100), 10);
  201. var msg = msgProgress.replace('{percent}', progress).replace('{file}', file.name);
  202. status.html(msg);
  203. }
  204. };
  205. if (isTxt) {
  206. reader.readAsText(file);
  207. }
  208. else {
  209. reader.readAsDataURL(file);
  210. }
  211. }
  212. else {
  213. preview.append("\n" + '<div class="file-preview-frame"><div class="file-preview-other"><h2><i class="glyphicon glyphicon-file"></i></h2>' + caption + '</div></div>');
  214. }
  215. })(tfiles[i]);
  216. }
  217. var log = numFiles > 1 ? msgSelected.replace('{n}', numFiles) : label;
  218. self.$caption.html(log);
  219. self.$container.removeClass('file-input-new');
  220. elem.trigger('fileselect', [numFiles, label]);
  221. },
  222. createContainer: function() {
  223. var self = this;
  224. var container = $(document.createElement("div")).attr({"class": 'file-input file-input-new'}).html(self.renderMain());
  225. self.$element.before(container);
  226. container.find('.btn-file').append(self.$element);
  227. return container;
  228. },
  229. renderMain: function() {
  230. var self = this;
  231. var preview = self.previewTemplate.replace('{class}', self.previewClass);
  232. var css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass;
  233. var caption = self.captionTemplate.replace('{class}', css);
  234. return self.mainTemplate.replace('{class}', self.mainClass).
  235. replace('{preview}', preview).
  236. replace('{caption}', caption).
  237. replace('{upload}', self.renderUpload()).
  238. replace('{remove}', self.renderRemove()).
  239. replace('{browse}', self.renderBrowse());
  240. },
  241. renderBrowse: function() {
  242. var self = this, css = self.browseClass + ' btn-file', status = '';
  243. if (self.isDisabled) {
  244. status = ' disabled ';
  245. }
  246. return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>';
  247. },
  248. renderRemove: function() {
  249. var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
  250. if (self.isDisabled) {
  251. status = ' disabled ';
  252. }
  253. return '<button type="button" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
  254. },
  255. renderUpload: function() {
  256. var self = this, content = '', status = '';
  257. if (self.isDisabled) {
  258. status = ' disabled ';
  259. }
  260. if (isEmpty(self.uploadUrl)) {
  261. content = '<button type="submit" class="' + self.uploadClass + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
  262. }
  263. else {
  264. content = '<a href="' + self.uploadUrl + '" class="' + self.uploadClass + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>';
  265. }
  266. return content;
  267. },
  268. }
  269. $.fn.fileinput = function(options) {
  270. return this.each(function() {
  271. var $this = $(this), data = $this.data('fileinput')
  272. if (!data) {
  273. $this.data('fileinput', (data = new FileInput(this, options)))
  274. }
  275. if (typeof options == 'string') {
  276. data[options]()
  277. }
  278. })
  279. };
  280. //FileInput plugin definition
  281. $.fn.fileinput = function(option) {
  282. var args = Array.apply(null, arguments);
  283. args.shift();
  284. return this.each(function() {
  285. var $this = $(this),
  286. data = $this.data('fileinput'),
  287. options = typeof option === 'object' && option;
  288. if (!data) {
  289. $this.data('fileinput', (data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data()))));
  290. }
  291. if (typeof option === 'string') {
  292. data[option].apply(data, args);
  293. }
  294. });
  295. };
  296. $.fn.fileinput.defaults = {
  297. showCaption: true,
  298. showPreview: true,
  299. showRemove: true,
  300. showUpload: true,
  301. captionClass: '',
  302. previewClass: '',
  303. mainClass: '',
  304. mainTemplate: null,
  305. previewTemplate: PREVIEW_TEMPLATE,
  306. captionTemplate: CAPTION_TEMPLATE,
  307. browseLabel: 'Browse &hellip;',
  308. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  309. browseClass: 'btn btn-primary',
  310. removeLabel: 'Remove',
  311. removeIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  312. removeClass: 'btn btn-default',
  313. uploadLabel: 'Upload',
  314. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  315. uploadClass: 'btn btn-default',
  316. uploadUrl: null,
  317. msgLoading: 'Loading &hellip;',
  318. msgProgress: 'Loaded {percent}% of {file}',
  319. msgSelected: '{n} files selected',
  320. previewFileType: 'image',
  321. wrapTextLength: 250,
  322. wrapIndicator: ' <span class="wrap-indicator" title="{title}">[&hellip;]</span>',
  323. elCaptionContainer: null,
  324. elCaptionText: null,
  325. elPreviewContainer: null,
  326. elPreviewImage: null,
  327. elPreviewStatus: null
  328. };
  329. /**
  330. * Convert automatically file inputs with class 'file'
  331. * into a bootstrap fileinput control.
  332. */
  333. $(function() {
  334. var $element = $('input.file[type=file]');
  335. if ($element.length > 0) {
  336. $element.fileinput();
  337. }
  338. });
  339. })(window.jQuery);