fileinput.js 13 KB

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