fileinput.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. /*!
  2. * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014
  3. * @version 2.1.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. MAIN_TEMPLATE_2 = '{preview}\n{remove}\n{upload}\n{browse}\n',
  29. 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. CAPTION_TEMPLATE = '<div class="form-control file-caption {class}">\n' +
  36. ' <span class="glyphicon glyphicon-file kv-caption-icon"></span><div class="file-caption-name"></div>\n' +
  37. '</div>',
  38. 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. IMAGE_TEMPLATE = '<div class="file-preview-frame" id="{previewId}">\n' +
  52. ' {content}\n' +
  53. '</div>\n',
  54. TEXT_TEMPLATE = '<div class="file-preview-frame" id="{previewId}">\n' +
  55. ' <div class="file-preview-text" title="{caption}">\n' +
  56. ' {strText}\n' +
  57. ' </div>\n' +
  58. '</div>\n',
  59. OTHER_TEMPLATE = '<div class="file-preview-frame" id="{previewId}">\n' +
  60. ' <div class="file-preview-other">\n' +
  61. ' <h2><i class="glyphicon glyphicon-file"></i></h2>\n' +
  62. ' {caption}\n' +
  63. ' </div>\n' +
  64. '</div>',
  65. isEmpty = function (value, trim) {
  66. return value === null || value === undefined || value == []
  67. || value === '' || trim && $.trim(value) === '';
  68. },
  69. isArray = Array.isArray || function (a) {
  70. return Object.prototype.toString.call(a) === '[object Array]';
  71. },
  72. getValue = function (options, param, value) {
  73. return (isEmpty(options) || isEmpty(options[param])) ? value : options[param];
  74. },
  75. getElement = function (options, param, value) {
  76. return (isEmpty(options) || isEmpty(options[param])) ? value : $(options[param]);
  77. },
  78. isImageFile = function (type, name) {
  79. return (typeof type !== "undefined") ? type.match('image.*') : name.match(/\.(gif|png|jpe?g)$/i);
  80. },
  81. isTextFile = function (type, name) {
  82. return (typeof type !== "undefined") ? type.match('text.*') : name.match(/\.(txt|md|csv|htm|html|php|ini)$/i);
  83. },
  84. uniqId = function () {
  85. return Math.round(new Date().getTime() + (Math.random() * 100));
  86. },
  87. hasFileAPISupport = function () {
  88. return window.File && window.FileReader && window.FileList && window.Blob;
  89. },
  90. vUrl = window.URL || window.webkitURL;
  91. var FileInput = function (element, options) {
  92. this.$element = $(element);
  93. if (hasFileAPISupport) {
  94. this.init(options);
  95. this.listen();
  96. } else {
  97. this.$element.removeClass('file-loading');
  98. }
  99. };
  100. FileInput.prototype = {
  101. constructor: FileInput,
  102. init: function (options) {
  103. var self = this;
  104. self.reader = null;
  105. self.showCaption = options.showCaption;
  106. self.showPreview = options.showPreview;
  107. self.maxFileSize = options.maxFileSize;
  108. self.maxFilesCount = options.maxFilesCount;
  109. self.msgSizeTooLarge = options.msgSizeTooLarge;
  110. self.msgFilesTooMany = options.msgFilesTooMany;
  111. self.msgFileNotFound = options.msgFileNotFound;
  112. self.msgFileNotReadable = options.msgFileNotReadable;
  113. self.msgFilePreviewAborted = options.msgFilePreviewAborted;
  114. self.msgFilePreviewError = options.msgFilePreviewError;
  115. self.msgErrorClass = options.msgErrorClass;
  116. self.initialDelimiter = options.initialDelimiter;
  117. self.initialPreview = options.initialPreview;
  118. self.initialCaption = options.initialCaption;
  119. self.initialPreviewCount = options.initialPreviewCount;
  120. self.initialPreviewContent = options.initialPreviewContent;
  121. self.overwriteInitial = options.overwriteInitial;
  122. self.showRemove = options.showRemove;
  123. self.showUpload = options.showUpload;
  124. self.captionClass = options.captionClass;
  125. self.previewClass = options.previewClass;
  126. self.mainClass = options.mainClass;
  127. if (isEmpty(options.mainTemplate)) {
  128. self.mainTemplate = self.showCaption ? MAIN_TEMPLATE_1 : MAIN_TEMPLATE_2;
  129. } else {
  130. self.mainTemplate = options.mainTemplate;
  131. }
  132. self.previewTemplate = (self.showPreview) ? options.previewTemplate : '';
  133. self.previewGenericTemplate = options.previewGenericTemplate;
  134. self.previewImageTemplate = options.previewImageTemplate;
  135. self.previewTextTemplate = options.previewTextTemplate;
  136. self.previewOtherTemplate = options.previewOtherTemplate;
  137. self.captionTemplate = options.captionTemplate;
  138. self.browseLabel = options.browseLabel;
  139. self.browseIcon = options.browseIcon;
  140. self.browseClass = options.browseClass;
  141. self.removeLabel = options.removeLabel;
  142. self.removeIcon = options.removeIcon;
  143. self.removeClass = options.removeClass;
  144. self.uploadLabel = options.uploadLabel;
  145. self.uploadIcon = options.uploadIcon;
  146. self.uploadClass = options.uploadClass;
  147. self.uploadUrl = options.uploadUrl;
  148. self.msgLoading = options.msgLoading;
  149. self.msgProgress = options.msgProgress;
  150. self.msgSelected = options.msgSelected;
  151. self.previewFileType = options.previewFileType;
  152. self.wrapTextLength = options.wrapTextLength;
  153. self.wrapIndicator = options.wrapIndicator;
  154. self.isError = false;
  155. self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly');
  156. if (isEmpty(self.$element.attr('id'))) {
  157. self.$element.attr('id', uniqId());
  158. }
  159. if (typeof self.$container == 'undefined') {
  160. self.$container = self.createContainer();
  161. } else {
  162. self.refreshContainer();
  163. }
  164. self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption'));
  165. self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name'));
  166. self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview'));
  167. self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails'));
  168. self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status'));
  169. self.initPreview();
  170. self.original = {
  171. preview: self.$preview.html(),
  172. caption: self.$caption.html()
  173. };
  174. self.options = options;
  175. self.$element.removeClass('file-loading');
  176. },
  177. listen: function () {
  178. var self = this;
  179. self.$element.on('change', $.proxy(self.change, self));
  180. $(self.$element[0].form).on('reset', $.proxy(self.reset, self));
  181. self.$container.on('click', '.fileinput-remove:not([disabled])', $.proxy(self.clear, self));
  182. },
  183. refresh: function (options) {
  184. var self = this, params = (arguments.length) ? $.extend(self.options, options) : self.options;
  185. self.init(params);
  186. },
  187. initPreview: function () {
  188. var self = this, html = '',
  189. content = self.initialPreview,
  190. len = isArray(content) ? content.length : (content.length > 0 ? content.split(self.initialDelimiter).length : 0),
  191. cap = self.initialCaption.length, previewId = "preview-" + uniqId(),
  192. caption = (cap > 0) ? self.initialCaption : self.msgSelected.replace("{n}", len);
  193. if (isArray(content) && len > 0) {
  194. for (var i = 0; i < len; i++) {
  195. previewId += '-' + i;
  196. html += self.previewGenericTemplate.replace("{previewId}", previewId).replace("{content}", content[i]);
  197. }
  198. if (len > 1 && cap == 0) {
  199. caption = self.msgSelected.replace("{n}", len);
  200. }
  201. } else if (len > 0) {
  202. var fileList = content.split(self.initialDelimiter);
  203. for (var i = 0; i < len; i++) {
  204. previewId += '-' + i;
  205. html += self.previewGenericTemplate.replace("{previewId}", previewId).replace("{content}", fileList[i]);
  206. }
  207. if (len > 1 && cap == 0) {
  208. caption = self.msgSelected.replace("{n}", len);
  209. }
  210. } else if (cap > 0) {
  211. self.$caption.html(caption);
  212. self.$captionContainer.attr('title', caption);
  213. return;
  214. } else {
  215. return;
  216. }
  217. self.initialPreviewCount = len;
  218. self.initialPreviewContent = html;
  219. self.$preview.html(html);
  220. self.$caption.html(caption);
  221. self.$captionContainer.attr('title', caption);
  222. self.$container.removeClass('file-input-new');
  223. },
  224. clear: function (e) {
  225. var self = this;
  226. if (e) {
  227. e.preventDefault();
  228. }
  229. if (self.reader instanceof FileReader) {
  230. self.reader.abort();
  231. }
  232. self.$element.val('');
  233. self.resetErrors(true);
  234. if (e !== false) {
  235. self.$element.trigger('change');
  236. self.$element.trigger('fileclear');
  237. }
  238. if (!self.overwriteInitial && !isEmpty(self.initialPreviewContent)) {
  239. self.$preview.html(self.original.preview);
  240. self.$caption.html(self.original.caption);
  241. self.$container.removeClass('file-input-new');
  242. } else {
  243. self.$preview.html('');
  244. var cap = (!self.overwriteInitial && self.initialCaption.length > 0) ?
  245. self.original.caption : '';
  246. self.$caption.html(cap);
  247. self.$captionContainer.attr('title', '');
  248. self.$container.removeClass('file-input-new').addClass('file-input-new');
  249. }
  250. self.hideFileIcon();
  251. self.$btnFile.focus();
  252. self.$element.trigger('filecleared');
  253. $.scrollTo('#' + self.$element.attr('id'));
  254. },
  255. reset: function (e) {
  256. var self = this;
  257. self.clear(false);
  258. self.$preview.html(self.original.preview);
  259. self.$caption.html(self.original.caption);
  260. self.$container.find('.fileinput-filename').text('');
  261. self.$element.trigger('filereset');
  262. if (self.initialPreview.length > 0) {
  263. self.$container.removeClass('file-input-new');
  264. }
  265. },
  266. disable: function (e) {
  267. var self = this;
  268. self.isDisabled = true;
  269. self.$element.attr('disabled', 'disabled');
  270. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  271. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").attr("disabled", true);
  272. },
  273. enable: function (e) {
  274. var self = this;
  275. self.isDisabled = false;
  276. self.$element.removeAttr('disabled');
  277. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  278. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").removeAttr("disabled");
  279. },
  280. hideFileIcon: function() {
  281. if (this.overwriteInitial) {
  282. this.$captionContainer.find('.kv-caption-icon').hide();
  283. }
  284. },
  285. showFileIcon: function() {
  286. this.$captionContainer.find('.kv-caption-icon').show();
  287. },
  288. resetErrors: function (fade) {
  289. var self = this, $error = self.$previewContainer.find('.kv-fileinput-error');
  290. if (fade) {
  291. $error.fadeOut('slow');
  292. } else {
  293. $error.remove();
  294. }
  295. },
  296. showError: function (msg, file, previewId) {
  297. var self = this, $error = self.$previewContainer.find('.kv-fileinput-error');
  298. if (isEmpty($error.attr('class'))) {
  299. self.$previewContainer.append(
  300. '<div class="kv-fileinput-error ' + self.msgErrorClass + '">' + msg + '</div>'
  301. );
  302. } else {
  303. $error.html(msg);
  304. }
  305. $error.hide();
  306. $error.fadeIn(800);
  307. self.$element.trigger('fileerror', [file, previewId]);
  308. self.$element.val('');
  309. return true;
  310. },
  311. errorHandler: function (evt, caption) {
  312. var self = this;
  313. switch (evt.target.error.code) {
  314. case evt.target.error.NOT_FOUND_ERR:
  315. self.addError(self.msgFileNotFound.replace('{name}', caption));
  316. break;
  317. case evt.target.error.NOT_READABLE_ERR:
  318. self.addError(self.msgFileNotReadable.replace('{name}', caption));
  319. break;
  320. case evt.target.error.ABORT_ERR:
  321. self.addError(self.msgFilePreviewAborted.replace('{name}', caption));
  322. break;
  323. default:
  324. self.addError(self.msgFilePreviewError.replace('{name}', caption));
  325. }
  326. },
  327. loadImage: function (file, caption) {
  328. var self = this, $img = $(document.createElement("img"));
  329. $img.attr({
  330. src: vUrl.createObjectURL(file),
  331. class: 'file-preview-image',
  332. title: caption,
  333. alt: caption,
  334. onload: function (e) {
  335. vUrl.revokeObjectURL($img.src);
  336. }
  337. });
  338. // autosize if image width exceeds preview width
  339. if ($img.width() >= self.$preview.width()) {
  340. $img.attr({width: "100%", height: "auto"});
  341. }
  342. var $imgContent = $(document.createElement("div")).append($img);
  343. return $imgContent.html();
  344. },
  345. readFiles: function (files) {
  346. this.reader = new FileReader();
  347. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  348. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  349. msgProgress = self.msgProgress, msgSelected = self.msgSelected, fileType = self.previewFileType,
  350. wrapLen = parseInt(self.wrapTextLength), wrapInd = self.wrapIndicator,
  351. previewId = "preview-" + uniqId();
  352. function readFile(i) {
  353. if (i >= files.length) {
  354. $container.removeClass('loading');
  355. $status.html('');
  356. return;
  357. }
  358. previewId += "-" + i;
  359. var file = files[i], caption = file.name, isImg = isImageFile(file.type, file.name),
  360. isTxt = isTextFile(file.type, file.name), fileSize = (file.size ? file.size : 0) / 1000;
  361. fileSize = fileSize.toFixed(2);
  362. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  363. var msg = self.msgSizeTooLarge.replace('{name}', caption).replace('{size}', fileSize).replace('{maxSize}', self.maxFileSize);
  364. self.isError = self.showError(msg, file, previewId);
  365. return;
  366. }
  367. if ($preview.length > 0 && (fileType == "any" ? (isImg || isTxt) : (fileType == "text" ? isTxt : isImg)) && typeof FileReader !== "undefined") {
  368. $status.html(msgLoading);
  369. $container.addClass('loading');
  370. reader.onerror = function (evt) {
  371. self.errorHandler(evt, caption);
  372. };
  373. reader.onload = function (theFile) {
  374. var content = '', modal = '';
  375. if (isTxt) {
  376. var strText = theFile.target.result;
  377. if (strText.length > wrapLen) {
  378. var id = uniqId(), height = window.innerHeight * .75,
  379. modal = MODAL_TEMPLATE.replace("{id}", id).replace("{title}", caption).replace("{body}", strText).replace("{height}", height);
  380. wrapInd = wrapInd.replace("{title}", caption).replace("{dialog}", "$('#" + id + "').modal('show')");
  381. strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
  382. }
  383. content = self.previewTextTemplate.replace("{previewId}", previewId).replace("{caption}", caption).replace("{strText}", strText) + modal;
  384. } else {
  385. content = self.previewImageTemplate.replace("{previewId}", previewId).replace("{content}", self.loadImage(file, caption));
  386. }
  387. $preview.append("\n" + content);
  388. };
  389. reader.onloadend = function (e) {
  390. setTimeout(readFile(i + 1), 1000);
  391. $el.trigger('fileloaded', [file, previewId]);
  392. };
  393. reader.onprogress = function (data) {
  394. if (data.lengthComputable) {
  395. var progress = parseInt(((data.loaded / data.total) * 100), 10);
  396. var msg = msgProgress.replace('{percent}', progress).replace('{file}', file.name);
  397. $status.html(msg);
  398. }
  399. };
  400. if (isTxt) {
  401. reader.readAsText(file);
  402. } else {
  403. reader.readAsBinaryString(file);
  404. }
  405. } else {
  406. $preview.append("\n" + self.previewOtherTemplate.replace("{previewId}", previewId).replace("{caption}", caption));
  407. $el.trigger('fileloaded', [file, previewId]);
  408. setTimeout(readFile(i + 1), 1000);
  409. }
  410. }
  411. readFile(0);
  412. },
  413. change: function (e) {
  414. var self = this, $el = self.$element, label = $el.val().replace(/\\/g, '/').replace(/.*\//, ''),
  415. total = 0, $preview = self.$preview, files = $el.get(0).files, msgSelected = self.msgSelected,
  416. numFiles = !isEmpty(files) ? (files.length + self.initialPreviewCount) : 1, tfiles;
  417. self.hideFileIcon();
  418. if (e.target.files === undefined) {
  419. tfiles = e.target && e.target.value ? [
  420. {name: e.target.value.replace(/^.+\\/, '')}
  421. ] : [];
  422. } else {
  423. tfiles = e.target.files;
  424. }
  425. if (tfiles.length === 0) {
  426. return;
  427. }
  428. self.resetErrors();
  429. $preview.html('');
  430. if (!self.overwriteInitial) {
  431. $preview.html(self.initialPreviewContent);
  432. }
  433. var total = tfiles.length;
  434. if (self.maxFilesCount > 0 && total > self.maxFilesCount) {
  435. var msg = self.msgFilesTooMany.replace('{m}', self.maxFilesCount).replace('{n}', total);
  436. self.isError = self.showError(msg, null, null);
  437. self.$container.removeClass('file-input-new');
  438. return;
  439. }
  440. self.showFileIcon();
  441. self.readFiles(files);
  442. self.reader = null;
  443. var log = numFiles > 1 ? msgSelected.replace('{n}', numFiles) : label;
  444. if (self.isError) {
  445. log = numFiles > 1 ? msgSelected.replace('{n}', numFiles - 1) : '&nbsp;';
  446. }
  447. self.$caption.html(log);
  448. self.$captionContainer.attr('title', log);
  449. self.$container.removeClass('file-input-new');
  450. $el.trigger('fileselect', [numFiles, label]);
  451. },
  452. initBrowse: function($container) {
  453. var self = this;
  454. self.$btnFile = $container.find('.btn-file');
  455. self.$btnFile.append(self.$element);
  456. },
  457. createContainer: function () {
  458. var self = this;
  459. var $container = $(document.createElement("div")).attr({"class": 'file-input file-input-new', tabindex: 10000}).html(self.renderMain());
  460. self.$element.before($container);
  461. self.initBrowse($container);
  462. return $container;
  463. },
  464. refreshContainer: function () {
  465. var self = this, $container = self.$container;
  466. $container.before(self.$element);
  467. $container.html(self.renderMain());
  468. self.initBrowse($container);
  469. },
  470. renderMain: function () {
  471. var self = this;
  472. var preview = self.previewTemplate.replace('{class}', self.previewClass);
  473. var css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass;
  474. var caption = self.captionTemplate.replace('{class}', css + ' kv-fileinput-caption');
  475. return self.mainTemplate.replace('{class}', self.mainClass).
  476. replace('{preview}', preview).
  477. replace('{caption}', caption).
  478. replace('{upload}', self.renderUpload()).
  479. replace('{remove}', self.renderRemove()).
  480. replace('{browse}', self.renderBrowse());
  481. },
  482. renderBrowse: function () {
  483. var self = this, css = self.browseClass + ' btn-file', status = '';
  484. if (self.isDisabled) {
  485. status = ' disabled ';
  486. }
  487. return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>';
  488. },
  489. renderRemove: function () {
  490. var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
  491. if (!self.showRemove) {
  492. return '';
  493. }
  494. if (self.isDisabled) {
  495. status = ' disabled ';
  496. }
  497. return '<button type="button" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
  498. },
  499. renderUpload: function () {
  500. var self = this, css = self.uploadClass + ' kv-fileinput-upload', content = '', status = '';
  501. if (!self.showUpload) {
  502. return '';
  503. }
  504. if (self.isDisabled) {
  505. status = ' disabled ';
  506. }
  507. if (isEmpty(self.uploadUrl)) {
  508. content = '<button type="submit" class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
  509. } else {
  510. content = '<a href="' + self.uploadUrl + '" class="' + self.uploadClass + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>';
  511. }
  512. return content;
  513. }
  514. }
  515. $.fn.fileinput = function (options) {
  516. return this.each(function () {
  517. var $this = $(this), data = $this.data('fileinput')
  518. if (!data) {
  519. $this.data('fileinput', (data = new FileInput(this, options)))
  520. }
  521. if (typeof options == 'string') {
  522. data[options]()
  523. }
  524. })
  525. };
  526. //FileInput plugin definition
  527. $.fn.fileinput = function (option) {
  528. var args = Array.apply(null, arguments);
  529. args.shift();
  530. return this.each(function () {
  531. var $this = $(this),
  532. data = $this.data('fileinput'),
  533. options = typeof option === 'object' && option;
  534. if (!data) {
  535. $this.data('fileinput', (data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data()))));
  536. }
  537. if (typeof option === 'string') {
  538. data[option].apply(data, args);
  539. }
  540. });
  541. };
  542. $.fn.fileinput.defaults = {
  543. showCaption: true,
  544. showPreview: true,
  545. showRemove: true,
  546. showUpload: true,
  547. captionClass: '',
  548. previewClass: '',
  549. mainClass: '',
  550. mainTemplate: null,
  551. initialDelimiter: '*$$*',
  552. initialPreview: '',
  553. initialCaption: '',
  554. initialPreviewCount: 0,
  555. initialPreviewContent: '',
  556. overwriteInitial: true,
  557. previewTemplate: PREVIEW_TEMPLATE,
  558. previewGenericTemplate: IMAGE_TEMPLATE,
  559. previewImageTemplate: IMAGE_TEMPLATE,
  560. previewTextTemplate: TEXT_TEMPLATE,
  561. previewOtherTemplate: OTHER_TEMPLATE,
  562. captionTemplate: CAPTION_TEMPLATE,
  563. browseLabel: 'Browse &hellip;',
  564. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  565. browseClass: 'btn btn-primary',
  566. removeLabel: 'Remove',
  567. removeIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  568. removeClass: 'btn btn-default',
  569. uploadLabel: 'Upload',
  570. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  571. uploadClass: 'btn btn-default',
  572. uploadUrl: null,
  573. maxFileSize: 0,
  574. maxFilesCount: 0,
  575. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>. Please retry your upload!',
  576. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>. Please retry your upload!',
  577. msgFileNotFound: 'File "{name}" not found!',
  578. msgFileNotReadable: 'File "{name}" is not readable.',
  579. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  580. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  581. msgErrorClass: 'file-error-message',
  582. msgLoading: 'Loading &hellip;',
  583. msgProgress: 'Loaded {percent}% of {file}',
  584. msgSelected: '{n} files selected',
  585. previewFileType: 'image',
  586. wrapTextLength: 250,
  587. wrapIndicator: ' <span class="wrap-indicator" title="{title}" onclick="{dialog}">[&hellip;]</span>',
  588. elCaptionContainer: null,
  589. elCaptionText: null,
  590. elPreviewContainer: null,
  591. elPreviewImage: null,
  592. elPreviewStatus: null
  593. };
  594. /**
  595. * Convert automatically file inputs with class 'file'
  596. * into a bootstrap fileinput control.
  597. */
  598. $(document).ready(function () {
  599. var $input = $('input.file[type=file]'), count = Object.keys($input).length;
  600. if (count > 0) {
  601. $input.fileinput();
  602. }
  603. });
  604. })(window.jQuery);