fileinput.js 19 KB

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