fileinput.js 16 KB

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