fileinput.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  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' && typeof haystack[needle] !== 'undefined');
  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. return isSet(t, self.layoutTemplates) ? self.layoutTemplates[t] : defaultLayoutTemplates[t];
  256. },
  257. getPreviewTemplate: function(t) {
  258. return isSet(t, self.previewTemplates) ? self.previewTemplates[t] : defaultPreviewTemplates[t];
  259. },
  260. listen: function () {
  261. var self = this, $el = self.$element, $cap = self.$captionContainer, $btnFile = self.$btnFile;
  262. $el.on('change', $.proxy(self.change, self));
  263. $btnFile.on('click', function (ev) {
  264. self.clear(false);
  265. $cap.focus();
  266. });
  267. $($el[0].form).on('reset', $.proxy(self.reset, self));
  268. self.$container.on('click', '.fileinput-remove:not([disabled])', $.proxy(self.clear, self));
  269. },
  270. refresh: function (options) {
  271. var self = this, params = (arguments.length) ? $.extend(self.options, options) : self.options;
  272. self.init(params);
  273. },
  274. initPreview: function () {
  275. var self = this, html = '', content = self.initialPreview, len = self.initialPreviewCount,
  276. cap = self.initialCaption.length, previewId = "preview-" + uniqId(),
  277. caption = (cap > 0) ? self.initialCaption : self.msgSelected.replace(/\{n\}/g, len);
  278. if (isArray(content) && len > 0) {
  279. for (var i = 0; i < len; i++) {
  280. previewId += '-' + i;
  281. html += self.previewGenericTemplate.replace(/\{previewId\}/g, previewId).replace(/\{content\}/g,
  282. content[i]);
  283. }
  284. if (len > 1 && cap == 0) {
  285. caption = self.msgSelected.replace(/\{n\}/g, len);
  286. }
  287. } else {
  288. if (len > 0) {
  289. var fileList = content.split(self.initialDelimiter);
  290. for (var i = 0; i < len; i++) {
  291. previewId += '-' + i;
  292. html += self.previewGenericTemplate.replace(/\{previewId\}/g, previewId).replace(/\{content\}/g,
  293. fileList[i]);
  294. }
  295. if (len > 1 && cap == 0) {
  296. caption = self.msgSelected.replace(/\{n\}/g, len);
  297. }
  298. } else {
  299. if (cap > 0) {
  300. self.$caption.html(caption);
  301. self.$captionContainer.attr('title', caption);
  302. return;
  303. } else {
  304. return;
  305. }
  306. }
  307. }
  308. self.initialPreviewContent = html;
  309. self.$preview.html(html);
  310. self.$caption.html(caption);
  311. self.$captionContainer.attr('title', caption);
  312. self.$container.removeClass('file-input-new');
  313. },
  314. clearObjects: function() {
  315. var self = this, $preview = self.$preview;
  316. $preview.find('video audio').each(function() {
  317. this.pause();
  318. delete(this);
  319. $(this).remove();
  320. });
  321. $preview.find('img object div').each(function() {
  322. delete(this);
  323. $(this).remove();
  324. });
  325. },
  326. clear: function (e) {
  327. var self = this;
  328. if (e) {
  329. e.preventDefault();
  330. }
  331. if (self.reader instanceof FileReader) {
  332. self.reader.abort();
  333. }
  334. self.$element.val('');
  335. self.resetErrors(true);
  336. if (e !== false) {
  337. self.$element.trigger('change');
  338. self.$element.trigger('fileclear');
  339. }
  340. if (self.overwriteInitial) {
  341. self.initialPreviewCount = 0;
  342. }
  343. if (!self.overwriteInitial && !isEmpty(self.initialPreviewContent)) {
  344. self.showFileIcon();
  345. self.$preview.html(self.original.preview);
  346. self.$caption.html(self.original.caption);
  347. self.$container.removeClass('file-input-new');
  348. } else {
  349. self.clearObjects();
  350. self.$preview.html('');
  351. var cap = (!self.overwriteInitial && self.initialCaption.length > 0) ?
  352. self.original.caption : '';
  353. self.$caption.html(cap);
  354. self.$captionContainer.attr('title', '');
  355. self.$container.removeClass('file-input-new').addClass('file-input-new');
  356. }
  357. self.hideFileIcon();
  358. self.$element.trigger('filecleared');
  359. self.$captionContainer.focus();
  360. },
  361. reset: function (e) {
  362. var self = this;
  363. self.clear(false);
  364. self.$preview.html(self.original.preview);
  365. self.$caption.html(self.original.caption);
  366. self.$container.find('.fileinput-filename').text('');
  367. self.$element.trigger('filereset');
  368. if (self.initialPreview.length > 0) {
  369. self.$container.removeClass('file-input-new');
  370. }
  371. },
  372. disable: function (e) {
  373. var self = this;
  374. self.isDisabled = true;
  375. self.$element.attr('disabled', 'disabled');
  376. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  377. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").attr("disabled", true);
  378. },
  379. enable: function (e) {
  380. var self = this;
  381. self.isDisabled = false;
  382. self.$element.removeAttr('disabled');
  383. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  384. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").removeAttr("disabled");
  385. },
  386. hideFileIcon: function () {
  387. if (this.overwriteInitial) {
  388. this.$captionContainer.find('.kv-caption-icon').hide();
  389. }
  390. },
  391. showFileIcon: function () {
  392. this.$captionContainer.find('.kv-caption-icon').show();
  393. },
  394. resetErrors: function (fade) {
  395. var self = this, $error = self.$previewContainer.find('.kv-fileinput-error');
  396. self.isError = false;
  397. if (fade) {
  398. $error.fadeOut('slow');
  399. } else {
  400. $error.remove();
  401. }
  402. },
  403. showError: function (msg, file, previewId, index) {
  404. var self = this, $error = self.$previewContainer.find('.kv-fileinput-error');
  405. if (isEmpty($error.attr('class'))) {
  406. self.$previewContainer.append(
  407. '<div class="kv-fileinput-error ' + self.msgErrorClass + '">' + msg + '</div>'
  408. );
  409. } else {
  410. $error.html(msg);
  411. }
  412. $error.hide();
  413. $error.fadeIn(800);
  414. self.$element.trigger('fileerror', [file, previewId, index]);
  415. self.$element.val('');
  416. return true;
  417. },
  418. errorHandler: function (evt, caption) {
  419. var self = this;
  420. switch (evt.target.error.code) {
  421. case evt.target.error.NOT_FOUND_ERR:
  422. self.addError(self.msgFileNotFound.replace(/\{name\}/g, caption));
  423. break;
  424. case evt.target.error.NOT_READABLE_ERR:
  425. self.addError(self.msgFileNotReadable.replace(/\{name\}/g, caption));
  426. break;
  427. case evt.target.error.ABORT_ERR:
  428. self.addError(self.msgFilePreviewAborted.replace(/\{name\}/g, caption));
  429. break;
  430. default:
  431. self.addError(self.msgFilePreviewError.replace(/\{name\}/g, caption));
  432. }
  433. },
  434. parseFileType: function(file) {
  435. var isValid, vType;
  436. for (var i = 0; i < defaultPreviewTypes.length; i++) {
  437. cat = defaultPreviewTypes[i];
  438. isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  439. vType = isValid(file.type, file.name) ? cat : '';
  440. if (vType != '') {
  441. return vType;
  442. }
  443. }
  444. return 'other';
  445. },
  446. previewDefault: function(file, previewId) {
  447. var self = this, data = vUrl.createObjectURL(file), $obj = $('#' + previewId),
  448. previewOtherTemplate = isSet('other', self.previewTemplates) ? self.previewTemplates['other'] : defaultPreviewTemplates['other'];
  449. self.$preview.append("\n" + previewOtherTemplate
  450. .replace(/\{previewId\}/g, previewId)
  451. .replace(/\{caption\}/g, file.name)
  452. .replace(/\{type\}/g, file.type)
  453. .replace(/\{data\}/g, data));
  454. $obj.on('load', function(e) {
  455. vUrl.revokeObjectURL($obj.attr('data'));
  456. });
  457. },
  458. previewFile: function(file, theFile, previewId, data) {
  459. var self = this, i, cat = self.parseFileType(file), caption = file.name, data, obj, content,
  460. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes, fType = file.type,
  461. template = isSet(cat, self.previewTemplates) ? self.previewTemplates[cat] : defaultPreviewTemplates[cat],
  462. config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat],
  463. wrapLen = parseInt(self.wrapTextLength), wrapInd = self.wrapIndicator, $preview = self.$preview,
  464. chkTypes = types.indexOf(cat) >=0, chkMimes = isEmpty(mimes) || (!isEmpty(mimes) && isSet(file.type, mimes));
  465. if (chkTypes && chkMimes) {
  466. if (cat == 'text') {
  467. var strText = theFile.target.result;
  468. vUrl.revokeObjectURL(data);
  469. if (strText.length > wrapLen) {
  470. var id = uniqId(), height = window.innerHeight * .75,
  471. modal = self.getLayoutTemplate('modal').replace(/\{id\}/g, id).replace(/\{title\}/g,
  472. caption).replace(/\{body\}/g, strText).replace(/\{height\}/g, height);
  473. wrapInd = wrapInd.replace(/\{title\}/g, caption).replace(/\{dialog\}/g,
  474. "$('#" + id + "').modal('show')");
  475. strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
  476. }
  477. content = template
  478. .replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption)
  479. .replace(/\{type\}/g, file.type).replace(/\{data\}/g, strText)
  480. .replace(/\{width\}/g, config.width).replace(/\{height\}/g, config.height);
  481. } else {
  482. content = template
  483. .replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption)
  484. .replace(/\{type\}/g, file.type).replace(/\{data\}/g, data)
  485. .replace(/\{width\}/g, config.width).replace(/\{height\}/g, config.height);
  486. }
  487. $preview.append("\n" + content);
  488. } else {
  489. self.previewDefault(file, previewId);
  490. }
  491. },
  492. readFiles: function (files) {
  493. this.reader = new FileReader();
  494. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  495. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  496. msgProgress = self.msgProgress, msgSelected = self.msgSelected, fileType = self.previewFileType,
  497. wrapLen = parseInt(self.wrapTextLength), wrapInd = self.wrapIndicator,
  498. previewInitId = "preview-" + uniqId(), numFiles = files.length,
  499. isText = isSet('text', self.fileTypeSettings) ? self.fileTypeSettings['text'] : defaultFileTypeSettings['text'];
  500. function readFile(i) {
  501. if (i >= numFiles) {
  502. $container.removeClass('loading');
  503. $status.html('');
  504. return;
  505. }
  506. var previewId = previewInitId + "-" + i, file = files[i], caption = file.name,
  507. fileSize = (file.size ? file.size : 0) / 1000, previewData = vUrl.createObjectURL(file);
  508. fileSize = fileSize.toFixed(2);
  509. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  510. var msg = self.msgSizeTooLarge.replace(/\{name\}/g, caption).replace(/\{size\}/g,
  511. fileSize).replace(/\{maxSize\}/g, self.maxFileSize);
  512. self.isError = self.showError(msg, file, previewId, i);
  513. return;
  514. }
  515. if (!self.showPreview) {
  516. setTimeout(readFile(i + 1), 1000);
  517. return;
  518. }
  519. if ($preview.length > 0 && typeof FileReader !== "undefined") {
  520. $status.html(msgLoading.replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles));
  521. $container.addClass('loading');
  522. reader.onerror = function (evt) {
  523. self.errorHandler(evt, caption);
  524. };
  525. reader.onload = function (theFile) {
  526. self.previewFile(file, theFile, previewId, previewData);
  527. };
  528. reader.onloadend = function (e) {
  529. var msg = msgProgress
  530. .replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles)
  531. .replace(/\{percent\}/g, 100).replace(/\{name\}/g, caption);
  532. setTimeout(function () {
  533. $status.html(msg);
  534. vUrl.revokeObjectURL(previewData);
  535. }, 1000);
  536. setTimeout(function () {
  537. readFile(i + 1);
  538. }, 1500);
  539. $el.trigger('fileloaded', [file, previewId, i]);
  540. };
  541. reader.onprogress = function (data) {
  542. if (data.lengthComputable) {
  543. var progress = parseInt(((data.loaded / data.total) * 100), 10);
  544. var msg = msgProgress
  545. .replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles)
  546. .replace(/\{percent\}/g, progress).replace(/\{name\}/g, caption);
  547. setTimeout(function () {
  548. $status.html(msg);
  549. }, 1000);
  550. }
  551. };
  552. if (isText(file.type, caption)) {
  553. reader.readAsText(file);
  554. } else {
  555. reader.readAsArrayBuffer(file);
  556. }
  557. } else {
  558. self.previewDefault(file, previewId);
  559. $el.trigger('fileloaded', [file, previewId, i]);
  560. setTimeout(readFile(i + 1), 1000);
  561. }
  562. }
  563. readFile(0);
  564. },
  565. change: function (e) {
  566. var self = this, $el = self.$element, label = $el.val().replace(/\\/g, '/').replace(/.*\//, ''),
  567. total = 0, $preview = self.$preview, files = $el.get(0).files, msgSelected = self.msgSelected,
  568. numFiles = !isEmpty(files) ? (files.length + self.initialPreviewCount) : 1, tfiles;
  569. self.hideFileIcon();
  570. if (e.target.files === undefined) {
  571. tfiles = e.target && e.target.value ? [
  572. {name: e.target.value.replace(/^.+\\/, '')}
  573. ] : [];
  574. } else {
  575. tfiles = e.target.files;
  576. }
  577. if (tfiles.length === 0) {
  578. return;
  579. }
  580. self.resetErrors();
  581. $preview.html('');
  582. if (!self.overwriteInitial) {
  583. $preview.html(self.initialPreviewContent);
  584. }
  585. var total = tfiles.length;
  586. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  587. var msg = self.msgFilesTooMany.replace(/\{m\}/g, self.maxFileCount).replace(/\{n\}/g, total);
  588. self.isError = self.showError(msg, null, null, null);
  589. self.$captionContainer.find('.kv-caption-icon').hide();
  590. self.$caption.html(self.msgValidationError);
  591. self.$container.removeClass('file-input-new');
  592. return;
  593. }
  594. self.readFiles(files);
  595. self.reader = null;
  596. var log = numFiles > 1 ? msgSelected.replace(/\{n\}/g, numFiles) : label;
  597. if (self.isError) {
  598. self.$captionContainer.find('.kv-caption-icon').hide();
  599. log = self.msgValidationError;
  600. } else {
  601. self.showFileIcon();
  602. }
  603. self.$caption.html(log);
  604. self.$captionContainer.attr('title', log);
  605. self.$container.removeClass('file-input-new');
  606. $el.trigger('fileselect', [numFiles, label]);
  607. },
  608. initBrowse: function ($container) {
  609. var self = this;
  610. self.$btnFile = $container.find('.btn-file');
  611. self.$btnFile.append(self.$element);
  612. },
  613. createContainer: function () {
  614. var self = this;
  615. var $container = $(document.createElement("span")).attr({"class": 'file-input file-input-new'}).html(self.renderMain());
  616. self.$element.before($container);
  617. self.initBrowse($container);
  618. return $container;
  619. },
  620. refreshContainer: function () {
  621. var self = this, $container = self.$container;
  622. $container.before(self.$element);
  623. $container.html(self.renderMain());
  624. self.initBrowse($container);
  625. },
  626. renderMain: function () {
  627. var self = this;
  628. var preview = self.showPreview ? self.getLayoutTemplate('preview').replace(/\{class\}/g, self.previewClass) : '';
  629. var css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass;
  630. var caption = self.captionTemplate.replace(/\{class\}/g, css + ' kv-fileinput-caption');
  631. return self.mainTemplate.replace(/\{class\}/g, self.mainClass).
  632. replace(/\{preview\}/g, preview).
  633. replace(/\{caption\}/g, caption).
  634. replace(/\{upload\}/g, self.renderUpload()).
  635. replace(/\{remove\}/g, self.renderRemove()).
  636. replace(/\{browse\}/g, self.renderBrowse());
  637. },
  638. renderBrowse: function () {
  639. var self = this, css = self.browseClass + ' btn-file', status = '';
  640. if (self.isDisabled) {
  641. status = ' disabled ';
  642. }
  643. return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>';
  644. },
  645. renderRemove: function () {
  646. var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
  647. if (!self.showRemove) {
  648. return '';
  649. }
  650. if (self.isDisabled) {
  651. status = ' disabled ';
  652. }
  653. return '<button type="button" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
  654. },
  655. renderUpload: function () {
  656. var self = this, css = self.uploadClass + ' kv-fileinput-upload', content = '', status = '';
  657. if (!self.showUpload) {
  658. return '';
  659. }
  660. if (self.isDisabled) {
  661. status = ' disabled ';
  662. }
  663. if (isEmpty(self.uploadUrl)) {
  664. content = '<button type="submit" class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
  665. } else {
  666. content = '<a href="' + self.uploadUrl + '" class="' + self.uploadClass + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>';
  667. }
  668. return content;
  669. }
  670. }
  671. $.fn.fileinput = function (options) {
  672. if (!hasFileAPISupport()) {
  673. return;
  674. }
  675. return this.each(function () {
  676. var $this = $(this), data = $this.data('fileinput')
  677. if (!data) {
  678. $this.data('fileinput', (data = new FileInput(this, options)))
  679. }
  680. if (typeof options == 'string') {
  681. data[options]()
  682. }
  683. })
  684. };
  685. //FileInput plugin definition
  686. $.fn.fileinput = function (option) {
  687. if (!hasFileAPISupport()) {
  688. return;
  689. }
  690. var args = Array.apply(null, arguments);
  691. args.shift();
  692. return this.each(function () {
  693. var $this = $(this),
  694. data = $this.data('fileinput'),
  695. options = typeof option === 'object' && option;
  696. if (!data) {
  697. $this.data('fileinput',
  698. (data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data()))));
  699. }
  700. if (typeof option === 'string') {
  701. data[option].apply(data, args);
  702. }
  703. });
  704. };
  705. $.fn.fileinput.defaults = {
  706. showCaption: true,
  707. showPreview: true,
  708. showRemove: true,
  709. showUpload: true,
  710. mainClass: '',
  711. previewClass: '',
  712. captionClass: '',
  713. mainTemplate: null,
  714. initialDelimiter: '*$$*',
  715. initialPreview: '',
  716. initialCaption: '',
  717. initialPreviewCount: 0,
  718. initialPreviewContent: '',
  719. overwriteInitial: true,
  720. layoutTemplates: defaultLayoutTemplates,
  721. previewTemplates: defaultPreviewTemplates,
  722. allowedPreviewTypes: defaultPreviewTypes,
  723. allowedPreviewMimeTypes: null,
  724. previewSettings: defaultPreviewSettings,
  725. fileTypeSettings: defaultFileTypeSettings,
  726. browseLabel: 'Browse &hellip;',
  727. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  728. browseClass: 'btn btn-primary',
  729. removeLabel: 'Remove',
  730. removeIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  731. removeClass: 'btn btn-default',
  732. uploadLabel: 'Upload',
  733. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  734. uploadClass: 'btn btn-default',
  735. uploadUrl: null,
  736. maxFileSize: 0,
  737. maxFileCount: 0,
  738. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>. Please retry your upload!',
  739. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>. Please retry your upload!',
  740. msgFileNotFound: 'File "{name}" not found!',
  741. msgFileNotReadable: 'File "{name}" is not readable.',
  742. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  743. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  744. msgValidationError: '<span class="text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i> File Upload Error</span>',
  745. msgErrorClass: 'file-error-message',
  746. msgLoading: 'Loading file {index} of {files} &hellip;',
  747. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  748. msgSelected: '{n} files selected',
  749. previewFileType: 'image',
  750. wrapTextLength: 250,
  751. wrapIndicator: ' <span class="wrap-indicator" title="{title}" onclick="{dialog}">[&hellip;]</span>',
  752. elCaptionContainer: null,
  753. elCaptionText: null,
  754. elPreviewContainer: null,
  755. elPreviewImage: null,
  756. elPreviewStatus: null
  757. };
  758. /**
  759. * Convert automatically file inputs with class 'file'
  760. * into a bootstrap fileinput control.
  761. */
  762. $(document).ready(function () {
  763. var $input = $('input.file[type=file]'), count = $input.attr('type') != null ? $input.length : 0;
  764. if (count > 0) {
  765. $input.fileinput();
  766. }
  767. });
  768. })(window.jQuery);