fileinput.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. /*!
  2. * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014
  3. * @version 2.4.0
  4. *
  5. * File input styled for Bootstrap 3.0 that utilizes HTML5 File Input's advanced
  6. * features including the FileReader API.
  7. *
  8. * The plugin drastically enhances the HTML file input to preview multiple files on the client before
  9. * upload. In addition it provides the ability to preview content of images, text, videos, audio, html,
  10. * flash and other objects.
  11. *
  12. * Author: Kartik Visweswaran
  13. * Copyright: 2014, Kartik Visweswaran, Krajee.com
  14. * For more JQuery plugins visit http://plugins.krajee.com
  15. * For more Yii related demos visit http://demos.krajee.com
  16. */
  17. (function ($) {
  18. var STYLE_SETTING = 'style="width:{width};height:{height};"';
  19. var PREVIEW_LABEL = ' <div class="text-center"><small>{caption}</small></div>\n';
  20. var OBJECT_PARAMS = ' <param name="controller" value="true" />\n' +
  21. ' <param name="allowFullScreen" value="true" />\n' +
  22. ' <param name="allowScriptAccess" value="always" />\n' +
  23. ' <param name="autoPlay" value="false" />\n' +
  24. ' <param name="autoStart" value="false" />\n'+
  25. ' <param name="quality" value="high" />\n';
  26. var DEFAULT_PREVIEW = '<div class="file-preview-other" ' + STYLE_SETTING + '>\n' +
  27. ' <h2><i class="glyphicon glyphicon-file"></i></h2>\n' +
  28. ' </div>';
  29. var defaultLayoutTemplates = {
  30. main1: '{preview}\n' +
  31. '<div class="input-group {class}">\n' +
  32. ' {caption}\n' +
  33. ' <div class="input-group-btn">\n' +
  34. ' {remove}\n' +
  35. ' {upload}\n' +
  36. ' {browse}\n' +
  37. ' </div>\n' +
  38. '</div>',
  39. main2: '{preview}\n{remove}\n{upload}\n{browse}\n',
  40. preview: '<div class="file-preview {class}">\n' +
  41. ' <div class="close fileinput-remove text-right">&times;</div>\n' +
  42. ' <div class="file-preview-thumbnails"></div>\n' +
  43. ' <div class="clearfix"></div>' +
  44. ' <div class="file-preview-status text-center text-success"></div>\n' +
  45. '</div>',
  46. caption: '<div tabindex="-1" class="form-control file-caption {class}">\n' +
  47. ' <span class="glyphicon glyphicon-file kv-caption-icon"></span><div class="file-caption-name"></div>\n' +
  48. '</div>',
  49. modal: '<div id="{id}" class="modal fade">\n' +
  50. ' <div class="modal-dialog modal-lg">\n' +
  51. ' <div class="modal-content">\n' +
  52. ' <div class="modal-header">\n' +
  53. ' <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>\n' +
  54. ' <h3 class="modal-title">Detailed Preview <small>{title}</small></h3>\n' +
  55. ' </div>\n' +
  56. ' <div class="modal-body">\n' +
  57. ' <textarea class="form-control" style="font-family:Monaco,Consolas,monospace; height: {height}px;" readonly>{body}</textarea>\n' +
  58. ' </div>\n' +
  59. ' </div>\n' +
  60. ' </div>\n' +
  61. '</div>\n'
  62. };
  63. var defaultPreviewTypes = ['image', 'html', 'text', 'video', 'audio', 'flash', 'object'];
  64. var defaultPreviewTemplates = {
  65. generic: '<div class="file-preview-frame" id="{previewId}">\n' +
  66. ' {content}\n' +
  67. '</div>\n',
  68. html: '<div class="file-preview-frame" id="{previewId}">\n' +
  69. ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  70. ' ' + DEFAULT_PREVIEW + '\n' +
  71. ' </object>\n' + PREVIEW_LABEL +
  72. '</div>',
  73. image: '<div class="file-preview-frame" id="{previewId}">\n' +
  74. ' <img src="{data}" class="file-preview-image" title="{caption}" alt="{caption}" ' + STYLE_SETTING + '>\n' +
  75. '</div>\n',
  76. text: '<div class="file-preview-frame" id="{previewId}">\n' +
  77. ' <div class="file-preview-text" title="{caption}" ' + STYLE_SETTING + '>\n' +
  78. ' {data}\n' +
  79. ' </div>\n' +
  80. '</div>\n',
  81. video: '<div class="file-preview-frame" id="{previewId}" title="{caption}" ' + STYLE_SETTING + '>\n' +
  82. ' <video width="{width}" height="{height}" controls>\n' +
  83. ' <source src="{data}" type="{type}">\n' +
  84. ' ' + DEFAULT_PREVIEW + '\n' +
  85. ' </video>\n' + PREVIEW_LABEL +
  86. '</div>\n',
  87. audio: '<div class="file-preview-frame" id="{previewId}" title="{caption}" ' + STYLE_SETTING + '>\n' +
  88. ' <audio controls>\n' +
  89. ' <source src="{data}" type="{type}">\n' +
  90. ' ' + DEFAULT_PREVIEW + '\n' +
  91. ' </audio>\n' + PREVIEW_LABEL +
  92. '</div>\n',
  93. flash: '<div class="file-preview-frame" id="{previewId}" title="{caption}" ' + STYLE_SETTING + '>\n' +
  94. ' <object type="application/x-shockwave-flash" width="{width}" height="{height}" data="{data}">\n' +
  95. OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' +
  96. ' </object>\n' + PREVIEW_LABEL +
  97. '</div>\n',
  98. object: '<div class="file-preview-frame" id="{previewId}" title="{caption}" ' + STYLE_SETTING + '>\n' +
  99. ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  100. ' <param name="movie" value="{caption}" />\n' +
  101. OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' +
  102. ' </object>\n' + PREVIEW_LABEL +
  103. '</div>',
  104. other: '<div class="file-preview-frame" id="{previewId}" title="{caption}" ' + STYLE_SETTING + '>\n' +
  105. ' ' + DEFAULT_PREVIEW + '\n' + PREVIEW_LABEL +
  106. '</div>',
  107. };
  108. var defaultPreviewSettings = {
  109. image: {width: "auto", height: "160px"},
  110. html: {width: "320px", height: "180px"},
  111. text: {width: "160px", height: "160px"},
  112. video: {width: "320px", height: "240px"},
  113. audio: {width: "320px", height: "80px"},
  114. flash: {width: "320px", height: "240px"},
  115. object: {width: "320px", height: "300px"},
  116. other: {width: "160px", height: "120px"}
  117. };
  118. var defaultFileTypeSettings = {
  119. image: function(vType, vName) {
  120. return (typeof vType !== "undefined") ? vType.match('image.*') : vName.match(/\.(gif|png|jpe?g)$/i);
  121. },
  122. html: function(vType, vName) {
  123. return (typeof vType !== "undefined") ? vType == 'text/html' : vName.match(/\.(htm|html)$/i);
  124. },
  125. text: function(vType, vName) {
  126. return typeof vType !== "undefined" && vType.match('text.*') || vName.match(/\.(txt|md|csv|nfo|php|ini)$/i);
  127. },
  128. video: function (vType, vName) {
  129. return typeof vType !== "undefined" && vType.match(/\.video\/(ogg|mp4|webm)$/i) || vName.match(/\.(og?|mp4|webm)$/i);
  130. },
  131. audio: function (vType, vName) {
  132. return typeof vType !== "undefined" && vType.match(/\.audio\/(ogg|mp3|wav)$/i) || vName.match(/\.(ogg|mp3|wav)$/i);
  133. },
  134. flash: function (vType, vName) {
  135. return typeof vType !== "undefined" && vType == 'application/x-shockwave-flash' || vName.match(/\.(swf)$/i);
  136. },
  137. object: function (vType, vName) {
  138. return true;
  139. },
  140. other: function (vType, vName) {
  141. return true;
  142. },
  143. };
  144. var isEmpty = function (value, trim) {
  145. return value === null || value === undefined || value == []
  146. || value === '' || trim && $.trim(value) === '';
  147. },
  148. isArray = function (a) {
  149. return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]';
  150. },
  151. isSet = function (needle, haystack) {
  152. return (typeof haystack == 'object' && needle in haystack);
  153. },
  154. getValue = function (options, param, value) {
  155. return (isEmpty(options) || isEmpty(options[param])) ? value : options[param];
  156. },
  157. getElement = function (options, param, value) {
  158. return (isEmpty(options) || isEmpty(options[param])) ? value : $(options[param]);
  159. },
  160. uniqId = function () {
  161. return Math.round(new Date().getTime() + (Math.random() * 100));
  162. },
  163. hasFileAPISupport = function () {
  164. return window.File && window.FileReader && window.FileList && window.Blob;
  165. },
  166. vUrl = window.URL || window.webkitURL;
  167. var FileInput = function (element, options) {
  168. this.$element = $(element);
  169. if (hasFileAPISupport()) {
  170. this.init(options);
  171. this.listen();
  172. } else {
  173. this.$element.removeClass('file-loading');
  174. }
  175. };
  176. FileInput.prototype = {
  177. constructor: FileInput,
  178. init: function (options) {
  179. var self = this;
  180. self.reader = null;
  181. self.showCaption = options.showCaption;
  182. self.showPreview = options.showPreview;
  183. self.maxFileSize = options.maxFileSize;
  184. self.maxFileCount = options.maxFileCount;
  185. self.msgSizeTooLarge = options.msgSizeTooLarge;
  186. self.msgFilesTooMany = options.msgFilesTooMany;
  187. self.msgFileNotFound = options.msgFileNotFound;
  188. self.msgFileNotReadable = options.msgFileNotReadable;
  189. self.msgFilePreviewAborted = options.msgFilePreviewAborted;
  190. self.msgFilePreviewError = options.msgFilePreviewError;
  191. self.msgValidationError = options.msgValidationError;
  192. self.msgErrorClass = options.msgErrorClass;
  193. self.initialDelimiter = options.initialDelimiter;
  194. self.initialPreview = options.initialPreview;
  195. self.initialCaption = options.initialCaption;
  196. self.initialPreviewCount = options.initialPreviewCount;
  197. self.initialPreviewContent = options.initialPreviewContent;
  198. self.overwriteInitial = options.overwriteInitial;
  199. self.layoutTemplates = options.layoutTemplates;
  200. self.previewTemplates = options.previewTemplates;
  201. self.allowedPreviewTypes = isEmpty(options.allowedPreviewTypes) ? defaultPreviewTypes : options.allowedPreviewTypes;
  202. self.allowedPreviewMimeTypes = options.allowedPreviewMimeTypes;
  203. self.previewSettings = options.previewSettings;
  204. self.fileTypeSettings = options.fileTypeSettings;
  205. self.showRemove = options.showRemove;
  206. self.showUpload = options.showUpload;
  207. self.captionClass = options.captionClass;
  208. self.previewClass = options.previewClass;
  209. self.mainClass = options.mainClass;
  210. self.mainTemplate = self.showCaption ? self.getLayoutTemplate('main1') : self.getLayoutTemplate('main2');
  211. self.captionTemplate = self.getLayoutTemplate('caption');
  212. self.previewGenericTemplate = self.getPreviewTemplate('generic');
  213. self.browseLabel = options.browseLabel;
  214. self.browseIcon = options.browseIcon;
  215. self.browseClass = options.browseClass;
  216. self.removeLabel = options.removeLabel;
  217. self.removeIcon = options.removeIcon;
  218. self.removeClass = options.removeClass;
  219. self.uploadLabel = options.uploadLabel;
  220. self.uploadIcon = options.uploadIcon;
  221. self.uploadClass = options.uploadClass;
  222. self.uploadUrl = options.uploadUrl;
  223. self.msgLoading = options.msgLoading;
  224. self.msgProgress = options.msgProgress;
  225. self.msgSelected = options.msgSelected;
  226. self.previewFileType = options.previewFileType;
  227. self.wrapTextLength = options.wrapTextLength;
  228. self.wrapIndicator = options.wrapIndicator;
  229. self.isError = false;
  230. self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly');
  231. if (isEmpty(self.$element.attr('id'))) {
  232. self.$element.attr('id', uniqId());
  233. }
  234. if (typeof self.$container == 'undefined') {
  235. self.$container = self.createContainer();
  236. } else {
  237. self.refreshContainer();
  238. }
  239. self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption'));
  240. self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name'));
  241. self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview'));
  242. self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails'));
  243. self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status'));
  244. var content = self.initialPreview;
  245. self.initialPreviewCount = isArray(content) ? content.length : (content.length > 0 ? content.split(self.initialDelimiter).length : 0)
  246. self.initPreview();
  247. self.original = {
  248. preview: self.$preview.html(),
  249. caption: self.$caption.html()
  250. };
  251. self.options = options;
  252. self.$element.removeClass('file-loading');
  253. },
  254. getLayoutTemplate: function(t) {
  255. var self = this;
  256. return isSet(t, self.layoutTemplates) ? self.layoutTemplates[t] : defaultLayoutTemplates[t];
  257. },
  258. getPreviewTemplate: function(t) {
  259. var self = this;
  260. return isSet(t, self.previewTemplates) ? self.previewTemplates[t] : defaultPreviewTemplates[t];
  261. },
  262. listen: function () {
  263. var self = this, $el = self.$element, $cap = self.$captionContainer, $btnFile = self.$btnFile;
  264. $el.on('change', $.proxy(self.change, self));
  265. $btnFile.on('click', function (ev) {
  266. self.clear(false);
  267. $cap.focus();
  268. });
  269. $($el[0].form).on('reset', $.proxy(self.reset, self));
  270. self.$container.on('click', '.fileinput-remove:not([disabled])', $.proxy(self.clear, self));
  271. },
  272. refresh: function (options) {
  273. var self = this, params = (arguments.length) ? $.extend(self.options, options) : self.options;
  274. self.init(params);
  275. },
  276. initPreview: function () {
  277. var self = this, html = '', content = self.initialPreview, len = self.initialPreviewCount,
  278. cap = self.initialCaption.length, previewId = "preview-" + uniqId(),
  279. caption = (cap > 0) ? self.initialCaption : self.msgSelected.replace(/\{n\}/g, len);
  280. if (isArray(content) && len > 0) {
  281. for (var i = 0; i < len; i++) {
  282. previewId += '-' + i;
  283. html += self.previewGenericTemplate.replace(/\{previewId\}/g, previewId).replace(/\{content\}/g,
  284. content[i]);
  285. }
  286. if (len > 1 && cap == 0) {
  287. caption = self.msgSelected.replace(/\{n\}/g, len);
  288. }
  289. } else {
  290. if (len > 0) {
  291. var fileList = content.split(self.initialDelimiter);
  292. for (var i = 0; i < len; i++) {
  293. previewId += '-' + i;
  294. html += self.previewGenericTemplate.replace(/\{previewId\}/g, previewId).replace(/\{content\}/g,
  295. fileList[i]);
  296. }
  297. if (len > 1 && cap == 0) {
  298. caption = self.msgSelected.replace(/\{n\}/g, len);
  299. }
  300. } else {
  301. if (cap > 0) {
  302. self.$caption.html(caption);
  303. self.$captionContainer.attr('title', caption);
  304. return;
  305. } else {
  306. return;
  307. }
  308. }
  309. }
  310. self.initialPreviewContent = html;
  311. self.$preview.html(html);
  312. self.$caption.html(caption);
  313. self.$captionContainer.attr('title', caption);
  314. self.$container.removeClass('file-input-new');
  315. },
  316. clearObjects: function() {
  317. var self = this, $preview = self.$preview;
  318. $preview.find('video audio').each(function() {
  319. this.pause();
  320. delete(this);
  321. $(this).remove();
  322. });
  323. $preview.find('img object div').each(function() {
  324. delete(this);
  325. $(this).remove();
  326. });
  327. },
  328. clear: function (e) {
  329. var self = this;
  330. if (e) {
  331. e.preventDefault();
  332. }
  333. if (self.reader instanceof FileReader) {
  334. self.reader.abort();
  335. }
  336. self.$element.val('');
  337. self.resetErrors(true);
  338. if (e !== false) {
  339. self.$element.trigger('change');
  340. self.$element.trigger('fileclear');
  341. }
  342. if (self.overwriteInitial) {
  343. self.initialPreviewCount = 0;
  344. }
  345. if (!self.overwriteInitial && !isEmpty(self.initialPreviewContent)) {
  346. self.showFileIcon();
  347. self.$preview.html(self.original.preview);
  348. self.$caption.html(self.original.caption);
  349. self.$container.removeClass('file-input-new');
  350. } else {
  351. self.clearObjects();
  352. self.$preview.html('');
  353. var cap = (!self.overwriteInitial && self.initialCaption.length > 0) ?
  354. self.original.caption : '';
  355. self.$caption.html(cap);
  356. self.$captionContainer.attr('title', '');
  357. self.$container.removeClass('file-input-new').addClass('file-input-new');
  358. }
  359. self.hideFileIcon();
  360. self.$element.trigger('filecleared');
  361. self.$captionContainer.focus();
  362. },
  363. reset: function (e) {
  364. var self = this;
  365. self.clear(false);
  366. self.$preview.html(self.original.preview);
  367. self.$caption.html(self.original.caption);
  368. self.$container.find('.fileinput-filename').text('');
  369. self.$element.trigger('filereset');
  370. if (self.initialPreview.length > 0) {
  371. self.$container.removeClass('file-input-new');
  372. }
  373. },
  374. disable: function (e) {
  375. var self = this;
  376. self.isDisabled = true;
  377. self.$element.attr('disabled', 'disabled');
  378. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  379. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").attr("disabled", true);
  380. },
  381. enable: function (e) {
  382. var self = this;
  383. self.isDisabled = false;
  384. self.$element.removeAttr('disabled');
  385. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  386. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").removeAttr("disabled");
  387. },
  388. hideFileIcon: function () {
  389. if (this.overwriteInitial) {
  390. this.$captionContainer.find('.kv-caption-icon').hide();
  391. }
  392. },
  393. showFileIcon: function () {
  394. this.$captionContainer.find('.kv-caption-icon').show();
  395. },
  396. resetErrors: function (fade) {
  397. var self = this, $error = self.$previewContainer.find('.kv-fileinput-error');
  398. self.isError = false;
  399. if (fade) {
  400. $error.fadeOut('slow');
  401. } else {
  402. $error.remove();
  403. }
  404. },
  405. showError: function (msg, file, previewId, index) {
  406. var self = this, $error = self.$previewContainer.find('.kv-fileinput-error');
  407. if (isEmpty($error.attr('class'))) {
  408. self.$previewContainer.append(
  409. '<div class="kv-fileinput-error ' + self.msgErrorClass + '">' + msg + '</div>'
  410. );
  411. } else {
  412. $error.html(msg);
  413. }
  414. $error.hide();
  415. $error.fadeIn(800);
  416. self.$element.trigger('fileerror', [file, previewId, index]);
  417. self.$element.val('');
  418. return true;
  419. },
  420. errorHandler: function (evt, caption) {
  421. var self = this;
  422. switch (evt.target.error.code) {
  423. case evt.target.error.NOT_FOUND_ERR:
  424. self.addError(self.msgFileNotFound.replace(/\{name\}/g, caption));
  425. break;
  426. case evt.target.error.NOT_READABLE_ERR:
  427. self.addError(self.msgFileNotReadable.replace(/\{name\}/g, caption));
  428. break;
  429. case evt.target.error.ABORT_ERR:
  430. self.addError(self.msgFilePreviewAborted.replace(/\{name\}/g, caption));
  431. break;
  432. default:
  433. self.addError(self.msgFilePreviewError.replace(/\{name\}/g, caption));
  434. }
  435. },
  436. parseFileType: function(file) {
  437. var isValid, vType;
  438. for (var i = 0; i < defaultPreviewTypes.length; i++) {
  439. cat = defaultPreviewTypes[i];
  440. isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  441. vType = isValid(file.type, file.name) ? cat : '';
  442. if (vType != '') {
  443. return vType;
  444. }
  445. }
  446. return 'other';
  447. },
  448. previewDefault: function(file, previewId) {
  449. var self = this, data = vUrl.createObjectURL(file), $obj = $('#' + previewId),
  450. previewOtherTemplate = isSet('other', self.previewTemplates) ? self.previewTemplates['other'] : defaultPreviewTemplates['other'];
  451. self.$preview.append("\n" + previewOtherTemplate
  452. .replace(/\{previewId\}/g, previewId)
  453. .replace(/\{caption\}/g, file.name)
  454. .replace(/\{type\}/g, file.type)
  455. .replace(/\{data\}/g, data));
  456. $obj.on('load', function(e) {
  457. vUrl.revokeObjectURL($obj.attr('data'));
  458. });
  459. },
  460. previewFile: function(file, theFile, previewId, data) {
  461. var self = this, i, cat = self.parseFileType(file), caption = file.name, data, obj, content,
  462. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes, fType = file.type,
  463. template = isSet(cat, self.previewTemplates) ? self.previewTemplates[cat] : defaultPreviewTemplates[cat],
  464. config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat],
  465. wrapLen = parseInt(self.wrapTextLength), wrapInd = self.wrapIndicator, $preview = self.$preview,
  466. chkTypes = types.indexOf(cat) >=0, chkMimes = isEmpty(mimes) || (!isEmpty(mimes) && isSet(file.type, mimes));
  467. if (chkTypes && chkMimes) {
  468. if (cat == 'text') {
  469. var strText = theFile.target.result;
  470. vUrl.revokeObjectURL(data);
  471. if (strText.length > wrapLen) {
  472. var id = 'text-' + uniqId(), height = window.innerHeight * .75,
  473. modal = self.getLayoutTemplate('modal').replace(/\{id\}/g, id).replace(/\{title\}/g,
  474. caption).replace(/\{body\}/g, strText).replace(/\{height\}/g, height);
  475. wrapInd = wrapInd.replace(/\{title\}/g, caption).replace(/\{dialog\}/g,
  476. "$('#" + id + "').modal('show')");
  477. strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
  478. }
  479. content = template
  480. .replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption)
  481. .replace(/\{type\}/g, file.type).replace(/\{data\}/g, strText)
  482. .replace(/\{width\}/g, config.width).replace(/\{height\}/g, config.height) + modal;
  483. } else {
  484. content = template
  485. .replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption)
  486. .replace(/\{type\}/g, file.type).replace(/\{data\}/g, data)
  487. .replace(/\{width\}/g, config.width).replace(/\{height\}/g, config.height);
  488. }
  489. $preview.append("\n" + content);
  490. } else {
  491. self.previewDefault(file, previewId);
  492. }
  493. },
  494. readFiles: function (files) {
  495. this.reader = new FileReader();
  496. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  497. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  498. msgProgress = self.msgProgress, msgSelected = self.msgSelected, fileType = self.previewFileType,
  499. wrapLen = parseInt(self.wrapTextLength), wrapInd = self.wrapIndicator,
  500. previewInitId = "preview-" + uniqId(), numFiles = files.length,
  501. isText = isSet('text', self.fileTypeSettings) ? self.fileTypeSettings['text'] : defaultFileTypeSettings['text'];
  502. function readFile(i) {
  503. if (i >= numFiles) {
  504. $container.removeClass('loading');
  505. $status.html('');
  506. return;
  507. }
  508. var previewId = previewInitId + "-" + i, file = files[i], caption = file.name,
  509. fileSize = (file.size ? file.size : 0) / 1000, previewData = vUrl.createObjectURL(file);
  510. fileSize = fileSize.toFixed(2);
  511. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  512. var msg = self.msgSizeTooLarge.replace(/\{name\}/g, caption).replace(/\{size\}/g,
  513. fileSize).replace(/\{maxSize\}/g, self.maxFileSize);
  514. self.isError = self.showError(msg, file, previewId, i);
  515. return;
  516. }
  517. if (!self.showPreview) {
  518. setTimeout(readFile(i + 1), 1000);
  519. return;
  520. }
  521. if ($preview.length > 0 && typeof FileReader !== "undefined") {
  522. $status.html(msgLoading.replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles));
  523. $container.addClass('loading');
  524. reader.onerror = function (evt) {
  525. self.errorHandler(evt, caption);
  526. };
  527. reader.onload = function (theFile) {
  528. self.previewFile(file, theFile, previewId, previewData);
  529. };
  530. reader.onloadend = function (e) {
  531. var msg = msgProgress
  532. .replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles)
  533. .replace(/\{percent\}/g, 100).replace(/\{name\}/g, caption);
  534. setTimeout(function () {
  535. $status.html(msg);
  536. vUrl.revokeObjectURL(previewData);
  537. }, 1000);
  538. setTimeout(function () {
  539. readFile(i + 1);
  540. }, 1500);
  541. $el.trigger('fileloaded', [file, previewId, i]);
  542. };
  543. reader.onprogress = function (data) {
  544. if (data.lengthComputable) {
  545. var progress = parseInt(((data.loaded / data.total) * 100), 10);
  546. var msg = msgProgress
  547. .replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles)
  548. .replace(/\{percent\}/g, progress).replace(/\{name\}/g, caption);
  549. setTimeout(function () {
  550. $status.html(msg);
  551. }, 1000);
  552. }
  553. };
  554. if (isText(file.type, caption)) {
  555. reader.readAsText(file);
  556. } else {
  557. reader.readAsArrayBuffer(file);
  558. }
  559. } else {
  560. self.previewDefault(file, previewId);
  561. $el.trigger('fileloaded', [file, previewId, i]);
  562. setTimeout(readFile(i + 1), 1000);
  563. }
  564. }
  565. readFile(0);
  566. },
  567. change: function (e) {
  568. var self = this, $el = self.$element, label = $el.val().replace(/\\/g, '/').replace(/.*\//, ''),
  569. total = 0, $preview = self.$preview, files = $el.get(0).files, msgSelected = self.msgSelected,
  570. numFiles = !isEmpty(files) ? (files.length + self.initialPreviewCount) : 1, tfiles;
  571. self.hideFileIcon();
  572. if (e.target.files === undefined) {
  573. tfiles = e.target && e.target.value ? [
  574. {name: e.target.value.replace(/^.+\\/, '')}
  575. ] : [];
  576. } else {
  577. tfiles = e.target.files;
  578. }
  579. if (tfiles.length === 0) {
  580. return;
  581. }
  582. self.resetErrors();
  583. $preview.html('');
  584. if (!self.overwriteInitial) {
  585. $preview.html(self.initialPreviewContent);
  586. }
  587. var total = tfiles.length;
  588. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  589. var msg = self.msgFilesTooMany.replace(/\{m\}/g, self.maxFileCount).replace(/\{n\}/g, total);
  590. self.isError = self.showError(msg, null, null, null);
  591. self.$captionContainer.find('.kv-caption-icon').hide();
  592. self.$caption.html(self.msgValidationError);
  593. self.$container.removeClass('file-input-new');
  594. return;
  595. }
  596. self.readFiles(files);
  597. self.reader = null;
  598. var log = numFiles > 1 ? msgSelected.replace(/\{n\}/g, numFiles) : label;
  599. if (self.isError) {
  600. self.$captionContainer.find('.kv-caption-icon').hide();
  601. log = self.msgValidationError;
  602. } else {
  603. self.showFileIcon();
  604. }
  605. self.$caption.html(log);
  606. self.$captionContainer.attr('title', log);
  607. self.$container.removeClass('file-input-new');
  608. $el.trigger('fileselect', [numFiles, label]);
  609. },
  610. initBrowse: function ($container) {
  611. var self = this;
  612. self.$btnFile = $container.find('.btn-file');
  613. self.$btnFile.append(self.$element);
  614. },
  615. createContainer: function () {
  616. var self = this;
  617. var $container = $(document.createElement("span")).attr({"class": 'file-input file-input-new'}).html(self.renderMain());
  618. self.$element.before($container);
  619. self.initBrowse($container);
  620. return $container;
  621. },
  622. refreshContainer: function () {
  623. var self = this, $container = self.$container;
  624. $container.before(self.$element);
  625. $container.html(self.renderMain());
  626. self.initBrowse($container);
  627. },
  628. renderMain: function () {
  629. var self = this;
  630. var preview = self.showPreview ? self.getLayoutTemplate('preview').replace(/\{class\}/g, self.previewClass) : '';
  631. var css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass;
  632. var caption = self.captionTemplate.replace(/\{class\}/g, css + ' kv-fileinput-caption');
  633. return self.mainTemplate.replace(/\{class\}/g, self.mainClass).
  634. replace(/\{preview\}/g, preview).
  635. replace(/\{caption\}/g, caption).
  636. replace(/\{upload\}/g, self.renderUpload()).
  637. replace(/\{remove\}/g, self.renderRemove()).
  638. replace(/\{browse\}/g, self.renderBrowse());
  639. },
  640. renderBrowse: function () {
  641. var self = this, css = self.browseClass + ' btn-file', status = '';
  642. if (self.isDisabled) {
  643. status = ' disabled ';
  644. }
  645. return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>';
  646. },
  647. renderRemove: function () {
  648. var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
  649. if (!self.showRemove) {
  650. return '';
  651. }
  652. if (self.isDisabled) {
  653. status = ' disabled ';
  654. }
  655. return '<button type="button" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
  656. },
  657. renderUpload: function () {
  658. var self = this, css = self.uploadClass + ' kv-fileinput-upload', content = '', status = '';
  659. if (!self.showUpload) {
  660. return '';
  661. }
  662. if (self.isDisabled) {
  663. status = ' disabled ';
  664. }
  665. if (isEmpty(self.uploadUrl)) {
  666. content = '<button type="submit" class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
  667. } else {
  668. content = '<a href="' + self.uploadUrl + '" class="' + self.uploadClass + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>';
  669. }
  670. return content;
  671. }
  672. }
  673. //FileInput plugin definition
  674. $.fn.fileinput = function (option) {
  675. if (!hasFileAPISupport()) {
  676. return;
  677. }
  678. var args = Array.apply(null, arguments);
  679. args.shift();
  680. return this.each(function () {
  681. var $this = $(this),
  682. data = $this.data('fileinput'),
  683. options = typeof option === 'object' && option;
  684. if (!data) {
  685. $this.data('fileinput',
  686. (data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data()))));
  687. }
  688. if (typeof option === 'string') {
  689. data[option].apply(data, args);
  690. }
  691. });
  692. };
  693. $.fn.fileinput.defaults = {
  694. showCaption: true,
  695. showPreview: true,
  696. showRemove: true,
  697. showUpload: true,
  698. mainClass: '',
  699. previewClass: '',
  700. captionClass: '',
  701. mainTemplate: null,
  702. initialDelimiter: '*$$*',
  703. initialPreview: '',
  704. initialCaption: '',
  705. initialPreviewCount: 0,
  706. initialPreviewContent: '',
  707. overwriteInitial: true,
  708. layoutTemplates: defaultLayoutTemplates,
  709. previewTemplates: defaultPreviewTemplates,
  710. allowedPreviewTypes: defaultPreviewTypes,
  711. allowedPreviewMimeTypes: null,
  712. previewSettings: defaultPreviewSettings,
  713. fileTypeSettings: defaultFileTypeSettings,
  714. browseLabel: 'Browse &hellip;',
  715. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  716. browseClass: 'btn btn-primary',
  717. removeLabel: 'Remove',
  718. removeIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  719. removeClass: 'btn btn-default',
  720. uploadLabel: 'Upload',
  721. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  722. uploadClass: 'btn btn-default',
  723. uploadUrl: null,
  724. maxFileSize: 0,
  725. maxFileCount: 0,
  726. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>. Please retry your upload!',
  727. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>. Please retry your upload!',
  728. msgFileNotFound: 'File "{name}" not found!',
  729. msgFileNotReadable: 'File "{name}" is not readable.',
  730. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  731. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  732. msgValidationError: '<span class="text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i> File Upload Error</span>',
  733. msgErrorClass: 'file-error-message',
  734. msgLoading: 'Loading file {index} of {files} &hellip;',
  735. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  736. msgSelected: '{n} files selected',
  737. previewFileType: 'image',
  738. wrapTextLength: 250,
  739. wrapIndicator: ' <span class="wrap-indicator" title="{title}" onclick="{dialog}">[&hellip;]</span>',
  740. elCaptionContainer: null,
  741. elCaptionText: null,
  742. elPreviewContainer: null,
  743. elPreviewImage: null,
  744. elPreviewStatus: null
  745. };
  746. /**
  747. * Convert automatically file inputs with class 'file'
  748. * into a bootstrap fileinput control.
  749. */
  750. $(document).ready(function () {
  751. var $input = $('input.file[type=file]'), count = $input.attr('type') != null ? $input.length : 0;
  752. if (count > 0) {
  753. $input.fileinput();
  754. }
  755. });
  756. })(window.jQuery);