fileinput.js 14 KB

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