fileinput.js 30 KB

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