fileinput.js 33 KB

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