fileinput.js 19 KB

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