fileinput.js 19 KB

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