fileinput.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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 ? [
  161. {name: e.target.value.replace(/^.+\\/, '')}
  162. ] : [];
  163. }
  164. else {
  165. tfiles = e.target.files;
  166. }
  167. if (tfiles.length === 0) {
  168. return;
  169. }
  170. preview.html('');
  171. var total = tfiles.length, self = self;
  172. for (var i = 0; i < total; i++) {
  173. (function (file) {
  174. var caption = file.name;
  175. var isImg = isImageFile(file.type, file.name);
  176. var isTxt = isTextFile(file.type, file.name);
  177. if (preview.length > 0 && (fileType == "any" ? (isImg || isTxt) : (fileType == "text" ? isTxt : isImg)) && typeof FileReader !== "undefined") {
  178. var reader = new FileReader();
  179. status.html(msgLoading);
  180. container.addClass('loading');
  181. reader.onload = function (theFile) {
  182. var content = '';
  183. if (isTxt) {
  184. var strText = theFile.target.result;
  185. if (strText.length > wrapLen) {
  186. wrapInd = wrapInd.replace("{title}", strText);
  187. strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
  188. }
  189. content = '<div class="file-preview-frame"><div class="file-preview-text" title="' + caption + '">' + strText + '</div></div>';
  190. }
  191. else {
  192. content = '<div class="file-preview-frame"><img src="' + theFile.target.result + '" class="file-preview-image" title="' + caption + '" alt="' + caption + '"></div>';
  193. }
  194. preview.append("\n" + content);
  195. if (i >= total - 1) {
  196. container.removeClass('loading');
  197. status.html('');
  198. }
  199. };
  200. reader.onprogress = function (data) {
  201. if (data.lengthComputable) {
  202. var progress = parseInt(((data.loaded / data.total) * 100), 10);
  203. var msg = msgProgress.replace('{percent}', progress).replace('{file}', file.name);
  204. status.html(msg);
  205. }
  206. };
  207. if (isTxt) {
  208. reader.readAsText(file);
  209. }
  210. else {
  211. reader.readAsDataURL(file);
  212. }
  213. }
  214. else {
  215. preview.append("\n" + '<div class="file-preview-frame"><div class="file-preview-other"><h2><i class="glyphicon glyphicon-file"></i></h2>' + caption + '</div></div>');
  216. }
  217. })(tfiles[i]);
  218. }
  219. var log = numFiles > 1 ? msgSelected.replace('{n}', numFiles) : label;
  220. self.$caption.html(log);
  221. self.$container.removeClass('file-input-new');
  222. elem.trigger('fileselect', [numFiles, label]);
  223. },
  224. createContainer: function () {
  225. var self = this;
  226. var container = $(document.createElement("div")).attr({"class": 'file-input file-input-new'}).html(self.renderMain());
  227. self.$element.before(container);
  228. container.find('.btn-file').append(self.$element);
  229. return container;
  230. },
  231. renderMain: function () {
  232. var self = this;
  233. var preview = self.previewTemplate.replace('{class}', self.previewClass);
  234. var css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass;
  235. var caption = self.captionTemplate.replace('{class}', css);
  236. return self.mainTemplate.replace('{class}', self.mainClass).
  237. replace('{preview}', preview).
  238. replace('{caption}', caption).
  239. replace('{upload}', self.renderUpload()).
  240. replace('{remove}', self.renderRemove()).
  241. replace('{browse}', self.renderBrowse());
  242. },
  243. renderBrowse: function () {
  244. var self = this, css = self.browseClass + ' btn-file', status = '';
  245. if (self.isDisabled) {
  246. status = ' disabled ';
  247. }
  248. return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>';
  249. },
  250. renderRemove: function () {
  251. var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
  252. if (!self.showRemove) {
  253. return '';
  254. }
  255. if (self.isDisabled) {
  256. status = ' disabled ';
  257. }
  258. return '<button type="button" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
  259. },
  260. renderUpload: function () {
  261. var self = this, content = '', status = '';
  262. if (!self.showUpload) {
  263. return '';
  264. }
  265. if (self.isDisabled) {
  266. status = ' disabled ';
  267. }
  268. if (isEmpty(self.uploadUrl)) {
  269. content = '<button type="submit" class="' + self.uploadClass + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
  270. }
  271. else {
  272. content = '<a href="' + self.uploadUrl + '" class="' + self.uploadClass + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>';
  273. }
  274. return content;
  275. },
  276. }
  277. $.fn.fileinput = function (options) {
  278. return this.each(function () {
  279. var $this = $(this), data = $this.data('fileinput')
  280. if (!data) {
  281. $this.data('fileinput', (data = new FileInput(this, options)))
  282. }
  283. if (typeof options == 'string') {
  284. data[options]()
  285. }
  286. })
  287. };
  288. //FileInput plugin definition
  289. $.fn.fileinput = function (option) {
  290. var args = Array.apply(null, arguments);
  291. args.shift();
  292. return this.each(function () {
  293. var $this = $(this),
  294. data = $this.data('fileinput'),
  295. options = typeof option === 'object' && option;
  296. if (!data) {
  297. $this.data('fileinput', (data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data()))));
  298. }
  299. if (typeof option === 'string') {
  300. data[option].apply(data, args);
  301. }
  302. });
  303. };
  304. $.fn.fileinput.defaults = {
  305. showCaption: true,
  306. showPreview: true,
  307. showRemove: true,
  308. showUpload: true,
  309. captionClass: '',
  310. previewClass: '',
  311. mainClass: '',
  312. mainTemplate: null,
  313. previewTemplate: PREVIEW_TEMPLATE,
  314. captionTemplate: CAPTION_TEMPLATE,
  315. browseLabel: 'Browse &hellip;',
  316. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  317. browseClass: 'btn btn-primary',
  318. removeLabel: 'Remove',
  319. removeIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  320. removeClass: 'btn btn-default',
  321. uploadLabel: 'Upload',
  322. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  323. uploadClass: 'btn btn-default',
  324. uploadUrl: null,
  325. msgLoading: 'Loading &hellip;',
  326. msgProgress: 'Loaded {percent}% of {file}',
  327. msgSelected: '{n} files selected',
  328. previewFileType: 'image',
  329. wrapTextLength: 250,
  330. wrapIndicator: ' <span class="wrap-indicator" title="{title}">[&hellip;]</span>',
  331. elCaptionContainer: null,
  332. elCaptionText: null,
  333. elPreviewContainer: null,
  334. elPreviewImage: null,
  335. elPreviewStatus: null
  336. };
  337. /**
  338. * Convert automatically file inputs with class 'file'
  339. * into a bootstrap fileinput control.
  340. */
  341. $(function () {
  342. var $element = $('input.file[type=file]');
  343. if ($element.length > 0) {
  344. $element.fileinput();
  345. }
  346. });
  347. })(window.jQuery);