fileinput.js 18 KB

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