fileinput.js 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684
  1. /*!
  2. * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2015
  3. * @version 4.1.6
  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. It also offers the ability to upload and delete files using AJAX, and add
  11. * files in batches (i.e. preview, append, or remove before upload).
  12. *
  13. * Author: Kartik Visweswaran
  14. * Copyright: 2015, 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 isIE = function (ver) {
  20. var div = document.createElement("div"), status;
  21. div.innerHTML = "<!--[if IE " + ver + "]><i></i><![endif]-->";
  22. status = (div.getElementsByTagName("i").length == 1);
  23. document.body.appendChild(div);
  24. div.parentNode.removeChild(div);
  25. return status;
  26. },
  27. hasFileAPISupport = function () {
  28. return window.File && window.FileReader;
  29. },
  30. hasDragDropSupport = function () {
  31. var $div = document.createElement('div');
  32. return !isIE(9) && (('draggable' in $div) || ('ondragstart' in $div && 'ondrop' in $div));
  33. },
  34. hasFileUploadSupport = function () {
  35. return hasFileAPISupport && window.FormData;
  36. },
  37. addCss = function ($el, css) {
  38. $el.removeClass(css).addClass(css);
  39. },
  40. STYLE_SETTING = 'style="width:{width};height:{height};"',
  41. OBJECT_PARAMS = ' <param name="controller" value="true" />\n' +
  42. ' <param name="allowFullScreen" value="true" />\n' +
  43. ' <param name="allowScriptAccess" value="always" />\n' +
  44. ' <param name="autoPlay" value="false" />\n' +
  45. ' <param name="autoStart" value="false" />\n' +
  46. ' <param name="quality" value="high" />\n',
  47. DEFAULT_PREVIEW = '<div class="file-preview-other">\n' +
  48. ' <i class="glyphicon glyphicon-file"></i>\n' +
  49. ' </div>';
  50. var defaultFileActionSettings = {
  51. removeIcon: '<i class="glyphicon glyphicon-trash text-danger"></i>',
  52. removeClass: 'btn btn-xs btn-default',
  53. removeTitle: 'Remove file',
  54. uploadIcon: '<i class="glyphicon glyphicon-upload text-info"></i>',
  55. uploadClass: 'btn btn-xs btn-default',
  56. uploadTitle: 'Upload file',
  57. indicatorNew: '<i class="glyphicon glyphicon-hand-down text-warning"></i>',
  58. indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign file-icon-large text-success"></i>',
  59. indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>',
  60. indicatorLoading: '<i class="glyphicon glyphicon-hand-up text-muted"></i>',
  61. indicatorNewTitle: 'Not uploaded yet',
  62. indicatorSuccessTitle: 'Uploaded',
  63. indicatorErrorTitle: 'Upload Error',
  64. indicatorLoadingTitle: 'Uploading ...'
  65. };
  66. var defaultLayoutTemplates = {
  67. main1: '{preview}\n' +
  68. '<div class="kv-upload-progress hide"></div>\n' +
  69. '<div class="input-group {class}">\n' +
  70. ' {caption}\n' +
  71. ' <div class="input-group-btn">\n' +
  72. ' {remove}\n' +
  73. ' {cancel}\n' +
  74. ' {upload}\n' +
  75. ' {browse}\n' +
  76. ' </div>\n' +
  77. '</div>',
  78. main2: '{preview}\n<div class="kv-upload-progress hide"></div>\n{remove}\n{cancel}\n{upload}\n{browse}\n',
  79. preview: '<div class="file-preview {class}">\n' +
  80. ' <div class="close fileinput-remove">&times;</div>\n' +
  81. ' <div class="{dropClass}">\n' +
  82. ' <div class="file-preview-thumbnails">\n' +
  83. ' </div>\n' +
  84. ' <div class="clearfix"></div>' +
  85. ' <div class="file-preview-status text-center text-success"></div>\n' +
  86. ' <div class="kv-fileinput-error"></div>\n' +
  87. ' </div>\n' +
  88. '</div>',
  89. icon: '<span class="glyphicon glyphicon-file kv-caption-icon"></span>',
  90. caption: '<div tabindex="-1" class="form-control file-caption {class}">\n' +
  91. ' <span class="file-caption-ellipsis">&hellip;</span>\n' +
  92. ' <div class="file-caption-name"></div>\n' +
  93. '</div>',
  94. modal: '<div id="{id}" class="modal fade">\n' +
  95. ' <div class="modal-dialog modal-lg">\n' +
  96. ' <div class="modal-content">\n' +
  97. ' <div class="modal-header">\n' +
  98. ' <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>\n' +
  99. ' <h3 class="modal-title">Detailed Preview <small>{title}</small></h3>\n' +
  100. ' </div>\n' +
  101. ' <div class="modal-body">\n' +
  102. ' <textarea class="form-control" style="font-family:Monaco,Consolas,monospace; height: {height}px;" readonly>{body}</textarea>\n' +
  103. ' </div>\n' +
  104. ' </div>\n' +
  105. ' </div>\n' +
  106. '</div>',
  107. progress: '<div class="progress">\n' +
  108. ' <div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' +
  109. ' {percent}%\n' +
  110. ' </div>\n' +
  111. '</div>',
  112. footer: '<div class="file-thumbnail-footer">\n' +
  113. ' <div class="file-caption-name">{caption}</div>\n' +
  114. ' {actions}\n' +
  115. '</div>',
  116. actions: '<div class="file-actions">\n' +
  117. ' <div class="file-footer-buttons">\n' +
  118. ' {upload}{delete}{other}' +
  119. ' </div>\n' +
  120. ' <div class="file-upload-indicator" tabindex="-1" title="{indicatorTitle}">{indicator}</div>\n' +
  121. ' <div class="clearfix"></div>\n' +
  122. '</div>',
  123. actionDelete: '<button type="button" class="kv-file-remove {removeClass}" title="{removeTitle}"{dataUrl}{dataKey}>{removeIcon}</button>\n',
  124. actionUpload: '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">{uploadIcon}</button>\n'
  125. };
  126. var defaultPreviewTypes = ['image', 'html', 'text', 'video', 'audio', 'flash', 'object'];
  127. var defaultPreviewTemplates = {
  128. generic: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  129. ' {content}\n' +
  130. ' {footer}\n' +
  131. '</div>\n',
  132. html: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  133. ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  134. ' ' + DEFAULT_PREVIEW + '\n' +
  135. ' </object>\n' +
  136. ' {footer}\n' +
  137. '</div>',
  138. image: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  139. ' <img src="{data}" class="file-preview-image" title="{caption}" alt="{caption}" ' + STYLE_SETTING + '>\n' +
  140. ' {footer}\n' +
  141. '</div>\n',
  142. text: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  143. ' <div class="file-preview-text" title="{caption}" ' + STYLE_SETTING + '>\n' +
  144. ' {data}\n' +
  145. ' </div>\n' +
  146. ' {footer}\n' +
  147. '</div>\n',
  148. video: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}" title="{caption}" ' + STYLE_SETTING + '>\n' +
  149. ' <video width="{width}" height="{height}" controls>\n' +
  150. ' <source src="{data}" type="{type}">\n' +
  151. ' ' + DEFAULT_PREVIEW + '\n' +
  152. ' </video>\n' +
  153. ' {footer}\n' +
  154. '</div>\n',
  155. audio: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}" title="{caption}" ' + STYLE_SETTING + '>\n' +
  156. ' <audio controls>\n' +
  157. ' <source src="{data}" type="{type}">\n' +
  158. ' ' + DEFAULT_PREVIEW + '\n' +
  159. ' </audio>\n' +
  160. ' {footer}\n' +
  161. '</div>\n',
  162. flash: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}" title="{caption}" ' + STYLE_SETTING + '>\n' +
  163. ' <object type="application/x-shockwave-flash" width="{width}" height="{height}" data="{data}">\n' +
  164. OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' +
  165. ' </object>\n' +
  166. ' {footer}\n' +
  167. '</div>\n',
  168. object: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}" title="{caption}" ' + STYLE_SETTING + '>\n' +
  169. ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  170. ' <param name="movie" value="{caption}" />\n' +
  171. OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' +
  172. ' </object>\n' +
  173. ' {footer}\n' +
  174. '</div>',
  175. other: '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}" title="{caption}" ' + STYLE_SETTING + '>\n' +
  176. ' ' + DEFAULT_PREVIEW + '\n' +
  177. ' {footer}\n' +
  178. '</div>',
  179. };
  180. var defaultPreviewSettings = {
  181. image: {width: "auto", height: "160px"},
  182. html: {width: "213px", height: "160px"},
  183. text: {width: "160px", height: "160px"},
  184. video: {width: "213px", height: "160px"},
  185. audio: {width: "213px", height: "80px"},
  186. flash: {width: "213px", height: "160px"},
  187. object: {width: "160px", height: "160px"},
  188. other: {width: "160px", height: "160px"}
  189. };
  190. var defaultFileTypeSettings = {
  191. image: function (vType, vName) {
  192. return (typeof vType !== "undefined") ? vType.match('image.*') : vName.match(/\.(gif|png|jpe?g)$/i);
  193. },
  194. html: function (vType, vName) {
  195. return (typeof vType !== "undefined") ? vType == 'text/html' : vName.match(/\.(htm|html)$/i);
  196. },
  197. text: function (vType, vName) {
  198. return typeof vType !== "undefined" && vType.match('text.*') || vName.match(/\.(txt|md|csv|nfo|php|ini)$/i);
  199. },
  200. video: function (vType, vName) {
  201. return typeof vType !== "undefined" && vType.match(/\.video\/(ogg|mp4|webm)$/i) || vName.match(/\.(og?|mp4|webm)$/i);
  202. },
  203. audio: function (vType, vName) {
  204. return typeof vType !== "undefined" && vType.match(/\.audio\/(ogg|mp3|wav)$/i) || vName.match(/\.(ogg|mp3|wav)$/i);
  205. },
  206. flash: function (vType, vName) {
  207. return typeof vType !== "undefined" && vType == 'application/x-shockwave-flash' || vName.match(/\.(swf)$/i);
  208. },
  209. object: function (vType, vName) {
  210. return true;
  211. },
  212. other: function (vType, vName) {
  213. return true;
  214. },
  215. };
  216. var isEmpty = function (value, trim) {
  217. return value === null || value === undefined || value == []
  218. || value === '' || trim && $.trim(value) === '';
  219. },
  220. isArray = function (a) {
  221. return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]';
  222. },
  223. isSet = function (needle, haystack) {
  224. return (typeof haystack == 'object' && needle in haystack);
  225. },
  226. getValue = function (options, param, value) {
  227. return (isEmpty(options) || isEmpty(options[param])) ? value : options[param];
  228. },
  229. getElement = function (options, param, value) {
  230. return (isEmpty(options) || isEmpty(options[param])) ? value : $(options[param]);
  231. },
  232. uniqId = function () {
  233. return Math.round(new Date().getTime() + (Math.random() * 100));
  234. },
  235. htmlEncode = function (str) {
  236. return String(str)
  237. .replace(/&/g, '&amp;')
  238. .replace(/"/g, '&quot;')
  239. .replace(/'/g, '&#39;')
  240. .replace(/</g, '&lt;')
  241. .replace(/>/g, '&gt;');
  242. },
  243. vUrl = window.URL || window.webkitURL;
  244. var FileInput = function (element, options) {
  245. this.$element = $(element);
  246. if (hasFileAPISupport() || isIE(9)) {
  247. this.init(options);
  248. this.listen();
  249. } else {
  250. this.$element.removeClass('file-loading');
  251. }
  252. };
  253. FileInput.prototype = {
  254. constructor: FileInput,
  255. init: function (options) {
  256. var self = this, $el = self.$element;
  257. for (key in options) {
  258. self[key] = options[key];
  259. }
  260. if (isEmpty(self.allowedPreviewTypes)) {
  261. self.allowedPreviewTypes = defaultPreviewTypes;
  262. }
  263. self.uploadFileAttr = !isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data';
  264. self.reader = null;
  265. self.formdata = {};
  266. self.isIE9 = isIE(9);
  267. self.isIE10 = isIE(10);
  268. self.filestack = [];
  269. self.ajaxRequests = [];
  270. self.isError = false;
  271. self.dropZoneEnabled = hasDragDropSupport() && self.dropZoneEnabled;
  272. self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly');
  273. self.isUploadable = hasFileUploadSupport && !isEmpty(self.uploadUrl);
  274. self.slug = typeof options.slugCallback == "function" ? options.slugCallback : self.slugDefault;
  275. self.mainTemplate = self.showCaption ? self.getLayoutTemplate('main1') : self.getLayoutTemplate('main2');
  276. self.captionTemplate = self.getLayoutTemplate('caption');
  277. self.previewGenericTemplate = self.getPreviewTemplate('generic');
  278. if (isEmpty(self.$element.attr('id'))) {
  279. self.$element.attr('id', uniqId());
  280. }
  281. if (typeof self.$container == 'undefined') {
  282. self.$container = self.createContainer();
  283. } else {
  284. self.refreshContainer();
  285. }
  286. self.$progress = self.$container.find('.kv-upload-progress');
  287. self.$btnUpload = self.$container.find('.kv-fileinput-upload')
  288. self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption'));
  289. self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name'));
  290. self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview'));
  291. self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails'));
  292. self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status'));
  293. self.$errorContainer = getElement(options, 'elErrorContainer',
  294. self.$previewContainer.find('.kv-fileinput-error'));
  295. if (!isEmpty(self.msgErrorClass)) {
  296. addCss(self.$errorContainer, self.msgErrorClass);
  297. }
  298. self.$errorContainer.hide();
  299. self.initialPreviewContent = '';
  300. var content = self.initialPreview;
  301. self.initialPreviewCount = isArray(content) ? content.length : (content.length > 0 ? content.split(self.initialPreviewDelimiter).length : 0);
  302. self.fileActionSettings = $.extend(defaultFileActionSettings, options.fileActionSettings);
  303. self.previewInitId = "preview-" + uniqId();
  304. self.initPreview();
  305. self.initPreviewDeletes();
  306. self.original = {
  307. preview: self.$preview.html(),
  308. caption: self.$caption.html()
  309. };
  310. self.options = options;
  311. self.setFileDropZoneTitle();
  312. self.uploadCount = 0;
  313. self.uploadPercent = 0;
  314. self.$element.removeClass('file-loading');
  315. self.setEllipsis();
  316. },
  317. raise: function (event) {
  318. var self = this;
  319. if (arguments.length > 1) {
  320. self.$element.trigger(event, arguments[1]);
  321. } else {
  322. self.$element.trigger(event);
  323. }
  324. },
  325. getLayoutTemplate: function (t) {
  326. var self = this;
  327. return isSet(t, self.layoutTemplates) ? self.layoutTemplates[t] : defaultLayoutTemplates[t];
  328. },
  329. getPreviewTemplate: function (t) {
  330. var self = this;
  331. return isSet(t, self.previewTemplates) ? self.previewTemplates[t] : defaultPreviewTemplates[t];
  332. },
  333. getOutData: function () {
  334. var self = this, jqXHR = arguments.length > 0 ? arguments[0] : {},
  335. responsedata = arguments.length > 1 ? arguments[1] : {},
  336. filesdata = arguments.length > 2 ? arguments[2] : self.filestack;
  337. return {
  338. form: self.formdata,
  339. files: filesdata,
  340. extra: self.getExtraData(),
  341. response: responsedata,
  342. reader: self.reader,
  343. jqXHR: jqXHR
  344. };
  345. },
  346. setEllipsis: function () {
  347. var self = this, $ellipsis = self.$captionContainer.find('.file-caption-ellipsis'), $cap = self.$caption,
  348. $div = $cap.clone().css('height', 'auto').hide();
  349. self.$captionContainer.parent().before($div);
  350. if ($div.outerWidth() > $cap.outerWidth()) {
  351. $ellipsis.show();
  352. } else {
  353. $ellipsis.hide();
  354. }
  355. $div.remove();
  356. },
  357. listen: function () {
  358. var self = this, $el = self.$element, $cap = self.$captionContainer, $btnFile = self.$btnFile;
  359. $el.on('change', $.proxy(self.change, self));
  360. $(window).on('resize', function () {
  361. self.setEllipsis();
  362. });
  363. $btnFile.off('click').on('click', function (ev) {
  364. self.raise('filebrowse');
  365. if (self.isError && !self.isUploadable) {
  366. self.clear(false);
  367. }
  368. $cap.focus();
  369. });
  370. $el.closest('form').off('reset').on('reset', $.proxy(self.reset, self));
  371. self.$container.off('click')
  372. .on('click', '.fileinput-remove:not([disabled])', $.proxy(self.clear, self))
  373. .on('click', '.fileinput-cancel', $.proxy(self.cancel, self));
  374. if (self.isUploadable && self.dropZoneEnabled && self.showPreview) {
  375. self.initDragDrop();
  376. }
  377. if (!self.isUploadable) {
  378. return;
  379. }
  380. self.$container.find('.kv-fileinput-upload').off('click').on('click', function (e) {
  381. if (!self.isUploadable) {
  382. return;
  383. }
  384. e.preventDefault();
  385. if (!$(this).hasClass('disabled') && isEmpty($(this).attr('disabled'))) {
  386. self.upload();
  387. }
  388. });
  389. },
  390. setProgress: function (percent) {
  391. var self = this, template = self.getLayoutTemplate('progress'), pct = Math.min(percent, 100);
  392. self.$progress.html(template.replace(/\{percent\}/g, pct));
  393. },
  394. upload: function () {
  395. var self = this, totLen = self.getFileStack().length;
  396. if (!self.isUploadable || self.isDisabled || totLen == 0) {
  397. return;
  398. }
  399. self.resetUpload();
  400. self.$progress.removeClass('hide');
  401. self.uploadCount = 0;
  402. self.uploadPercent = 0;
  403. var i, len = self.filestack.length, template = self.getLayoutTemplate('progress');
  404. self.lock();
  405. self.setProgress(0);
  406. if ((self.uploadAsync || totLen == 1) && self.showPreview) {
  407. var outData = self.getOutData();
  408. self.raise('filebatchpreupload', [outData]);
  409. for (i = 0; i < len; i++) {
  410. if (self.filestack[i] !== undefined) {
  411. self.uploadSingle(i, self.filestack, true);
  412. }
  413. }
  414. setTimeout(function () {
  415. $(document).ajaxStop(function () {
  416. self.setProgress(100);
  417. self.$preview.find('file-preview-frame').removeClass('file-loading');
  418. self.unlock();
  419. self.clearFileInput();
  420. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  421. });
  422. }, 100);
  423. return;
  424. }
  425. self.uploadBatch();
  426. },
  427. lock: function () {
  428. var self = this;
  429. self.resetErrors();
  430. self.disable();
  431. if (self.showRemove) {
  432. addCss(self.$container.find('.fileinput-remove'), 'hide');
  433. }
  434. if (self.showCancel) {
  435. self.$container.find('.fileinput-cancel').removeClass('hide');
  436. }
  437. self.raise('filelock', [self.filestack, self.getExtraData()]);
  438. },
  439. unlock: function () {
  440. var self = this;
  441. self.enable();
  442. if (self.showCancel) {
  443. addCss(self.$container.find('.fileinput-cancel'), 'hide');
  444. }
  445. if (self.showRemove) {
  446. self.$container.find('.fileinput-remove').removeClass('hide');
  447. }
  448. self.raise('fileunlock', [self.filestack, self.getExtraData()]);
  449. },
  450. refresh: function (options) {
  451. var self = this, $el = self.$element,
  452. params = (arguments.length) ? $.extend(self.options, options) : self.options;
  453. $el.off();
  454. self.init(params);
  455. var $zone = self.$container.find('.file-drop-zone');
  456. $zone.off('dragenter dragover drop');
  457. $(document).off('dragenter dragover drop');
  458. self.listen();
  459. self.setFileDropZoneTitle();
  460. },
  461. initDragDrop: function () {
  462. var self = this, $zone = self.$container.find('.file-drop-zone');
  463. $zone.off('dragenter dragover drop');
  464. $(document).off('dragenter dragover drop');
  465. $zone.on('dragenter dragover', function (e) {
  466. e.stopPropagation();
  467. e.preventDefault();
  468. if (self.isDisabled) {
  469. return;
  470. }
  471. addCss($(this), 'highlighted');
  472. });
  473. $zone.on('dragleave', function (e) {
  474. e.stopPropagation();
  475. e.preventDefault();
  476. if (self.isDisabled) {
  477. return;
  478. }
  479. $(this).removeClass('highlighted');
  480. });
  481. $zone.on('drop', function (e) {
  482. e.preventDefault();
  483. if (self.isDisabled) {
  484. return;
  485. }
  486. self.change(e, 'dragdrop');
  487. $(this).removeClass('highlighted');
  488. });
  489. $(document).on('dragenter dragover drop', function (e) {
  490. e.stopPropagation();
  491. e.preventDefault();
  492. });
  493. },
  494. setFileDropZoneTitle: function () {
  495. var self = this, $zone = self.$container.find('.file-drop-zone');
  496. $zone.find('.' + self.dropZoneTitleClass).remove();
  497. if (!self.isUploadable || !self.showPreview ||
  498. $zone.length == 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled) {
  499. return;
  500. }
  501. if ($zone.find('.file-preview-frame').length == 0) {
  502. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + self.dropZoneTitle + '</div>');
  503. }
  504. self.$container.removeClass('file-input-new');
  505. addCss(self.$container, 'file-input-ajax-new');
  506. },
  507. initFileActions: function () {
  508. var self = this;
  509. self.$preview.find('.kv-file-remove').each(function () {
  510. var $el = $(this), $frame = $el.closest('.file-preview-frame'),
  511. ind = $frame.attr('data-fileindex');
  512. $el.off('click').on('click', function () {
  513. $frame.fadeOut('slow', function () {
  514. self.filestack[ind] = undefined;
  515. self.clearObjects($frame);
  516. $frame.remove();
  517. var filestack = self.getFileStack(), len = filestack.length,
  518. chk = self.$container.find('.file-preview-initial').length;
  519. if (len == 0 && chk == 0) {
  520. self.original.preview = '';
  521. self.reset();
  522. } else {
  523. var n = self.initialPreviewCount + len,
  524. cap = n > 1 ? self.msgSelected.replace(/\{n\}/g, n) : filestack[0].name;
  525. self.setCaption(cap);
  526. }
  527. });
  528. });
  529. });
  530. self.$preview.find('.kv-file-upload').each(function () {
  531. var $el = $(this);
  532. $el.off('click').on('click', function () {
  533. var $frame = $el.closest('.file-preview-frame'),
  534. ind = $frame.attr('data-fileindex');
  535. self.uploadSingle(ind, self.filestack);
  536. });
  537. });
  538. },
  539. renderInitFileFooter: function (i) {
  540. var self = this, hasConfig = self.initialPreviewConfig.length > 0,
  541. template = self.getLayoutTemplate('footer');
  542. if (hasConfig && !isEmpty(self.initialPreviewConfig[i])) {
  543. var config = self.initialPreviewConfig[i],
  544. caption = ('caption' in config) ? config.caption : '',
  545. width = ('width' in config) ? config.width : 'auto',
  546. url = ('url' in config) ? config.url : false,
  547. key = ('key' in config) ? config.key : null,
  548. disabled = url === false ? true : false,
  549. actions = self.initialPreviewShowDelete ? self.renderFileActions(false, true, disabled, url,
  550. key) : '',
  551. footer = template.replace(/\{actions\}/g, actions);
  552. return footer.replace(/\{caption\}/g, caption).replace(/\{width\}/g, width)
  553. .replace(/\{indicator\}/g, '').replace(/\{indicatorTitle\}/g, '');
  554. }
  555. return '';
  556. },
  557. renderFileFooter: function (caption, width) {
  558. var self = this, config = self.fileActionSettings,
  559. template = self.getLayoutTemplate('footer');
  560. if (self.isUploadable) {
  561. var footer = template.replace(/\{actions\}/g, self.renderFileActions(true, true, false, false, false));
  562. return footer.replace(/\{caption\}/g, caption).replace(/\{width\}/g, width)
  563. .replace(/\{indicator\}/g, config.indicatorNew).replace(/\{indicatorTitle\}/g,
  564. config.indicatorNewTitle);
  565. } else {
  566. return template.replace(/\{actions\}/g, '').replace(/\{caption\}/g, caption).replace(/\{width\}/g,
  567. width)
  568. .replace(/\{indicator\}/g, '').replace(/\{indicatorTitle\}/g, '');
  569. }
  570. return '';
  571. },
  572. renderFileActions: function (showUpload, showDelete, disabled, url, key) {
  573. if (!showUpload && !showDelete) {
  574. return '';
  575. }
  576. var self = this,
  577. vUrl = url == false ? '' : ' data-url="' + url + '"',
  578. vKey = key == false ? '' : ' data-key="' + key + '"',
  579. btnDelete = self.getLayoutTemplate('actionDelete'),
  580. btnUpload = '',
  581. template = self.getLayoutTemplate('actions'),
  582. otherActionButtons = self.otherActionButtons.replace(/\{dataKey\}/g, vKey),
  583. config = self.fileActionSettings,
  584. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  585. btnDelete = btnDelete
  586. .replace(/\{removeClass\}/g, removeClass)
  587. .replace(/\{removeIcon\}/g, config.removeIcon)
  588. .replace(/\{removeTitle\}/g, config.removeTitle)
  589. .replace(/\{dataUrl\}/g, vUrl)
  590. .replace(/\{dataKey\}/g, vKey);
  591. if (showUpload) {
  592. btnUpload = self.getLayoutTemplate('actionUpload')
  593. .replace(/\{uploadClass\}/g, config.uploadClass)
  594. .replace(/\{uploadIcon\}/g, config.uploadIcon)
  595. .replace(/\{uploadTitle\}/g, config.uploadTitle);
  596. }
  597. return template
  598. .replace(/\{delete\}/g, btnDelete)
  599. .replace(/\{upload\}/g, btnUpload)
  600. .replace(/\{other\}/g, otherActionButtons);
  601. },
  602. getInitialPreview: function (template, content, i) {
  603. var self = this, ind = 'init_' + i,
  604. previewId = self.previewInitId + '-' + ind;
  605. footer = self.renderInitFileFooter(i, false);
  606. return template
  607. .replace(/\{previewId\}/g, previewId)
  608. .replace(/\{frameClass\}/g, ' file-preview-initial')
  609. .replace(/\{fileindex\}/g, ind)
  610. .replace(/\{content\}/g, content)
  611. .replace(/\{footer\}/g, footer);
  612. },
  613. initPreview: function () {
  614. var self = this, html = '', content = self.initialPreview, len = self.initialPreviewCount,
  615. cap = self.initialCaption.length, previewId = self.previewInitId + '-init_' + i;
  616. caption = (cap > 0) ? self.initialCaption : self.msgSelected.replace(/\{n\}/g, len);
  617. if (isArray(content) && len > 0) {
  618. for (var i = 0; i < len; i++) {
  619. html += self.getInitialPreview(self.previewGenericTemplate, content[i], i);
  620. }
  621. if (len > 1 && cap == 0) {
  622. caption = self.msgSelected.replace(/\{n\}/g, len);
  623. }
  624. } else {
  625. if (len > 0) {
  626. var fileList = content.split(self.initialPreviewDelimiter);
  627. for (var i = 0; i < len; i++) {
  628. html += self.getInitialPreview(self.previewGenericTemplate, content[i], i);
  629. }
  630. if (len > 1 && cap == 0) {
  631. caption = self.msgSelected.replace(/\{n\}/g, len);
  632. }
  633. } else {
  634. if (cap > 0) {
  635. self.setCaption(caption);
  636. return;
  637. } else {
  638. return;
  639. }
  640. }
  641. }
  642. self.initialPreviewContent = html;
  643. self.$preview.html(html);
  644. self.setCaption(caption);
  645. self.$container.removeClass('file-input-new');
  646. },
  647. initPreviewDeletes: function () {
  648. var self = this,
  649. resetProgress = function () {
  650. if (self.$preview.find('.kv-file-remove').length == 0) {
  651. self.reset();
  652. }
  653. };
  654. self.$preview.find('.kv-file-remove').each(function () {
  655. var $el = $(this), $frame = $el.closest('.file-preview-frame'),
  656. vUrl = $el.attr('data-url'), vKey = $el.attr('data-key'),
  657. $content = $(self.initialPreviewContent);
  658. if (vUrl === undefined || vKey === undefined) {
  659. return;
  660. }
  661. $el.off('click').on('click', function () {
  662. $.ajax({
  663. url: vUrl,
  664. type: 'POST',
  665. dataType: 'json',
  666. data: {key: vKey},
  667. beforeSend: function (jqXHR) {
  668. addCss($frame, 'file-uploading');
  669. addCss($el, 'disabled');
  670. self.raise('filepredelete', [vKey, jqXHR]);
  671. },
  672. success: function (data, textStatus, jqXHR) {
  673. if (typeof data.error === 'undefined') {
  674. self.raise('filedeleted', [vKey, jqXHR]);
  675. } else {
  676. self.showError(data.error, null, $el.attr('id'), key, 'filedeleteerror', jqXHR);
  677. resetProgress();
  678. }
  679. $frame.removeClass('file-uploading').addClass('file-deleted');
  680. $frame.fadeOut('slow', function () {
  681. self.clearObjects($frame);
  682. $frame.remove();
  683. var $content = $(document.createElement('div')).html(self.original.preview);
  684. $content.find('.file-preview-frame').each(function () {
  685. var $el = $(this);
  686. if ($el.find('.kv-file-remove').attr('data-key') == vKey) {
  687. $el.remove();
  688. }
  689. });
  690. self.initialPreviewContent = $content.html();
  691. if (self.initialPreviewCount > 0) {
  692. self.initialPreviewCount--;
  693. }
  694. var caption = (self.initialCaption.length > 0) ?
  695. self.initialCaption :
  696. self.msgSelected.replace(/\{n\}/g, self.initialPreviewCount);
  697. self.original.preview = $content.html();
  698. self.setCaption(caption);
  699. self.original.caption = self.$caption.html();
  700. $content.remove();
  701. resetProgress();
  702. });
  703. },
  704. error: function (jqXHR, textStatus, errorThrown) {
  705. self.showError(errorThrown, null, $el.attr('id'), key, 'filedeleteerror', jqXHR);
  706. $frame.removeClass('file-uploading');
  707. resetProgress();
  708. }
  709. });
  710. });
  711. });
  712. },
  713. clearObjects: function ($el) {
  714. $el.find('video audio').each(function () {
  715. this.pause();
  716. delete(this);
  717. $(this).remove();
  718. });
  719. $el.find('img object div').each(function () {
  720. delete(this);
  721. $(this).remove();
  722. });
  723. },
  724. clearFileInput: function () {
  725. var self = this, $el = self.$element;
  726. if (isEmpty($el.val())) {
  727. return;
  728. }
  729. // Fix for IE ver < 11, that does not clear file inputs
  730. // Requires a sequence of steps to prevent IE crashing but
  731. // still allow clearing of the file input.
  732. if (self.isIE9 || self.isIE10) {
  733. var $srcFrm = $el.closest('form'),
  734. $tmpFrm = $(document.createElement('form')),
  735. $tmpEl = $(document.createElement('div'));
  736. $el.before($tmpEl);
  737. if ($srcFrm.length) {
  738. $srcFrm.after($tmpFrm);
  739. } else {
  740. $tmpEl.after($tmpFrm);
  741. }
  742. $tmpFrm.append($el).trigger('reset');
  743. $tmpEl.before($el).remove();
  744. $tmpFrm.remove();
  745. } else { // normal input clear behavior for other sane browsers
  746. $el.val('');
  747. }
  748. },
  749. resetUpload: function () {
  750. var self = this;
  751. self.uploadCount = 0;
  752. self.uploadPercent = 0;
  753. self.$btnUpload.removeAttr('disabled');
  754. self.setProgress(0);
  755. addCss(self.$progress, 'hide');
  756. self.resetErrors(false);
  757. self.ajaxRequests = [];
  758. },
  759. cancel: function () {
  760. var self = this, xhr = self.ajaxRequests, len = xhr.length;
  761. if (len > 0) {
  762. for (i = 0; i < len; i++) {
  763. xhr[i].abort();
  764. }
  765. self.$preview.find('file-preview-frame').each(function () {
  766. $thumb = $(this), ind = $thumb.attr('data-fileindex');
  767. $thumb.removeClass('file-uploading');
  768. if (self.filestack[ind] !== undefined) {
  769. $thumb.find('.kv-file-upload').removeClass('disabled');
  770. $thumb.find('.kv-file-upload').removeClass('disabled');
  771. }
  772. });
  773. self.unlock();
  774. }
  775. },
  776. clear: function () {
  777. var self = this, e = arguments.length > 0 && arguments[0];
  778. if (!self.isIE9 && self.reader instanceof FileReader) {
  779. self.reader.abort();
  780. }
  781. self.$btnUpload.removeAttr('disabled');
  782. self.resetUpload();
  783. self.filestack = [];
  784. self.clearFileInput();
  785. self.resetErrors(true);
  786. if (e !== false) {
  787. self.raise('change');
  788. self.raise('fileclear');
  789. }
  790. if (self.overwriteInitial) {
  791. self.initialPreviewCount = 0;
  792. self.initialPreviewContent = '';
  793. }
  794. if (!self.overwriteInitial && self.initialPreviewContent.length > 0) {
  795. self.showFileIcon();
  796. self.$preview.html(self.original.preview);
  797. self.$caption.html(self.original.caption);
  798. self.setEllipsis();
  799. self.initPreviewDeletes();
  800. self.$container.removeClass('file-input-new');
  801. } else {
  802. self.$preview.find('.file-preview-frame').each(function () {
  803. self.clearObjects($(this));
  804. });
  805. self.$preview.html('');
  806. var cap = (!self.overwriteInitial && self.initialCaption.length > 0) ?
  807. self.original.caption : '';
  808. self.$caption.html(cap);
  809. self.setEllipsis();
  810. self.$caption.attr('title', '');
  811. addCss(self.$container, 'file-input-new');
  812. }
  813. if (self.$container.find('.file-preview-frame').length == 0) {
  814. self.initialCaption = '';
  815. self.original.caption = '';
  816. self.$caption.html('');
  817. self.setEllipsis();
  818. self.$captionContainer.find('.kv-caption-icon').hide();
  819. }
  820. self.hideFileIcon();
  821. self.raise('filecleared');
  822. self.$captionContainer.focus();
  823. self.setFileDropZoneTitle();
  824. },
  825. reset: function () {
  826. var self = this;
  827. self.clear(false);
  828. self.$preview.html(self.original.preview);
  829. self.$caption.html(self.original.caption);
  830. self.setEllipsis();
  831. self.$container.find('.fileinput-filename').text('');
  832. self.raise('filereset');
  833. if (self.initialPreview.length > 0) {
  834. self.$container.removeClass('file-input-new');
  835. }
  836. self.setFileDropZoneTitle();
  837. if (self.isUploadable) {
  838. self.resetUpload();
  839. }
  840. self.filestack = [];
  841. self.formdata = {};
  842. },
  843. disable: function () {
  844. var self = this;
  845. self.isDisabled = true;
  846. self.raise('filedisabled');
  847. self.$element.attr('disabled', 'disabled');
  848. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  849. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").attr("disabled", true);
  850. self.initDragDrop();
  851. },
  852. enable: function () {
  853. var self = this;
  854. self.isDisabled = false;
  855. self.raise('fileenabled');
  856. self.$element.removeAttr('disabled');
  857. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  858. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").removeAttr("disabled");
  859. self.initDragDrop();
  860. },
  861. getExtraData: function () {
  862. var self = this, data = self.uploadExtraData;
  863. if (typeof(self.uploadExtraData) == "function") {
  864. data = self.uploadExtraData();
  865. }
  866. return data;
  867. },
  868. uploadExtra: function () {
  869. var self = this, data = self.getExtraData();
  870. if (data.length == 0) {
  871. return;
  872. }
  873. $.each(data, function (key, value) {
  874. self.formdata.append(key, value);
  875. });
  876. },
  877. initXhr: function (xhrobj, factor) {
  878. var self = this;
  879. if (xhrobj.upload) {
  880. xhrobj.upload.addEventListener('progress', function (event) {
  881. var pct = 0, position = event.loaded || event.position, total = event.total;
  882. if (event.lengthComputable) {
  883. pct = Math.ceil(position / total * factor);
  884. }
  885. self.uploadPercent = Math.max(pct, self.uploadPercent);
  886. self.setProgress(self.uploadPercent);
  887. }, false);
  888. }
  889. return xhrobj;
  890. },
  891. ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError) {
  892. var self = this;
  893. self.uploadExtra();
  894. self.ajaxRequests.push($.ajax({
  895. xhr: function () {
  896. var xhrobj = $.ajaxSettings.xhr();
  897. return self.initXhr(xhrobj, 98);
  898. },
  899. url: self.uploadUrl,
  900. type: 'POST',
  901. dataType: 'json',
  902. data: self.formdata,
  903. cache: false,
  904. processData: false,
  905. contentType: false,
  906. beforeSend: fnBefore,
  907. success: fnSuccess,
  908. complete: fnComplete,
  909. error: fnError
  910. }));
  911. },
  912. uploadSingle: function (i, files) {
  913. var self = this, total = self.getFileStack().length, formdata = new FormData(),
  914. previewId = self.previewInitId + "-" + i, $thumb = $('#' + previewId),
  915. $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove'),
  916. $indicator = $thumb.find('.file-upload-indicator'), config = self.fileActionSettings,
  917. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData);
  918. self.formdata = formdata;
  919. if (total == 0 || !hasPostData || $btnUpload.hasClass('disabled')) {
  920. return;
  921. }
  922. var percent,
  923. allFiles = arguments.length > 2,
  924. setIndicator = function (icon, msg) {
  925. $indicator.html(config[icon]);
  926. $indicator.attr('title', config[msg]);
  927. },
  928. updateProgress = function () {
  929. if (!allFiles || total == 0 || self.uploadPercent >= 100) {
  930. return;
  931. }
  932. self.uploadCount++;
  933. var pct = 80 + Math.ceil(self.uploadCount * 20 / total);
  934. self.uploadPercent = Math.max(pct, self.uploadPercent);
  935. self.setProgress(self.uploadPercent);
  936. self.initPreviewDeletes();
  937. },
  938. resetActions = function () {
  939. $btnUpload.removeAttr('disabled');
  940. $btnDelete.removeAttr('disabled');
  941. $thumb.removeClass('file-uploading');
  942. },
  943. fnBefore = function (jqXHR) {
  944. var outData = self.getOutData(jqXHR);
  945. setIndicator('indicatorLoading', 'indicatorLoadingTitle');
  946. addCss($thumb, 'file-uploading');
  947. $btnUpload.attr('disabled', true);
  948. $btnDelete.attr('disabled', true);
  949. if (!allFiles) {
  950. self.lock();
  951. }
  952. self.raise('filepreupload', [outData, previewId, i])
  953. },
  954. fnSuccess = function (data, textStatus, jqXHR) {
  955. var outData = self.getOutData(jqXHR, data);
  956. setTimeout(function () {
  957. if (typeof data.error === 'undefined') {
  958. setIndicator('indicatorSuccess', 'indicatorSuccessTitle');
  959. $btnUpload.hide();
  960. $btnDelete.hide();
  961. self.filestack[i] = undefined;
  962. self.raise('fileuploaded', [outData, previewId, i]);
  963. } else {
  964. setIndicator('indicatorError', 'indicatorErrorTitle');
  965. self.showUploadError(data.error, outData, previewId, i);
  966. }
  967. }, 100);
  968. },
  969. fnComplete = function () {
  970. setTimeout(function () {
  971. updateProgress();
  972. resetActions();
  973. }, 100);
  974. if (!allFiles) {
  975. self.unlock();
  976. }
  977. },
  978. fnError = function (jqXHR, textStatus, errorThrown) {
  979. setIndicator('indicatorError', 'indicatorErrorTitle');
  980. var outData = self.getOutData(jqXHR);
  981. if (allFiles) {
  982. var cap = files[i].name;
  983. self.showUploadError('<b>' + cap + '</b>: ' + errorThrown, outData, previewId, i);
  984. } else {
  985. self.showUploadError(errorThrown, outData, previewId, i);
  986. }
  987. };
  988. formdata.append(self.uploadFileAttr, files[i]);
  989. formdata.append('file_id', i);
  990. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  991. },
  992. uploadBatch: function () {
  993. var self = this, files = self.filestack, total = files.length, formdata = new FormData(),
  994. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData);
  995. self.formdata = formdata;
  996. if (total == 0 || !hasPostData) {
  997. return;
  998. }
  999. var config = self.fileActionSettings,
  1000. setIndicator = function (i, icon, msg) {
  1001. var $indicator = $('#' + self.previewInitId + "-" + i).find('.file-upload-indicator');
  1002. $indicator.html(config[icon]);
  1003. $indicator.attr('title', config[msg]);
  1004. },
  1005. enableActions = function (i, disabled) {
  1006. var $thumb = $('#' + self.previewInitId + "-" + i),
  1007. $btnUpload = $thumb.find('.kv-file-upload'),
  1008. $btnDelete = $thumb.find('.kv-file-delete');
  1009. $thumb.removeClass('file-uploading');
  1010. $btnUpload.removeAttr('disabled');
  1011. $btnDelete.removeAttr('disabled');
  1012. },
  1013. setAllUploaded = function () {
  1014. $.each(files, function (key, data) {
  1015. self.filestack[key] = undefined;
  1016. });
  1017. self.clearFileInput();
  1018. },
  1019. fnBefore = function (jqXHR) {
  1020. self.lock();
  1021. var outData = self.getOutData(jqXHR);
  1022. if (!self.showPreview) {
  1023. return;
  1024. }
  1025. self.$preview.find('.file-preview-frame').each(function () {
  1026. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove');
  1027. addCss($thumb, 'file-uploading');
  1028. $btnUpload.attr('disabled', true);
  1029. $btnDelete.attr('disabled', true);
  1030. });
  1031. self.raise('filebatchpreupload', [outData]);
  1032. },
  1033. fnSuccess = function (data, textStatus, jqXHR) {
  1034. var outData = self.getOutData(jqXHR, data);
  1035. var keys = isEmpty(data.errorkeys) ? [] : data.errorkeys;
  1036. if (typeof data.error === 'undefined' || isEmpty(data.error)) {
  1037. self.raise('filebatchuploadsuccess', [outData]);
  1038. setAllUploaded();
  1039. if (self.showPreview) {
  1040. self.$preview.find('.kv-file-upload').hide();
  1041. self.$preview.find('.kv-file-remove').hide();
  1042. self.$preview.find('.file-preview-frame').each(function () {
  1043. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1044. setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle');
  1045. enableActions(key);
  1046. });
  1047. } else {
  1048. self.reset();
  1049. }
  1050. } else {
  1051. self.$preview.find('.file-preview-frame').each(function () {
  1052. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1053. enableActions(key);
  1054. if (keys.length == 0) {
  1055. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1056. return;
  1057. }
  1058. if ($.inArray(key, keys)) {
  1059. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1060. } else {
  1061. $thumb.find('.kv-file-upload').hide();
  1062. $thumb.find('.kv-file-remove').hide();
  1063. setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle');
  1064. self.filestack[key] = undefined;
  1065. }
  1066. });
  1067. self.showUploadError(data.error, outData, null, null, 'filebatchuploaderror');
  1068. }
  1069. },
  1070. fnComplete = function () {
  1071. self.setProgress(100);
  1072. self.unlock();
  1073. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1074. self.clearFileInput();
  1075. },
  1076. fnError = function (jqXHR, textStatus, errorThrown) {
  1077. var outData = self.getOutData(jqXHR);
  1078. self.showUploadError(errorThrown, outData, null, null, 'filebatchuploaderror');
  1079. self.uploadFileCount = total - 1;
  1080. self.$preview.find('.file-preview-frame').removeClass('file-uploading');
  1081. self.$preview.find('.file-preview-frame kv-file-upload').removeAttr('disabled');
  1082. self.$preview.find('.file-preview-frame kv-file-delete').removeAttr('disabled');
  1083. };
  1084. $.each(files, function (key, data) {
  1085. if (files[key] !== undefined) {
  1086. self.formdata.append(self.uploadFileAttr, files[key]);
  1087. }
  1088. });
  1089. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1090. },
  1091. hideFileIcon: function () {
  1092. if (this.overwriteInitial) {
  1093. this.$captionContainer.find('.kv-caption-icon').hide();
  1094. }
  1095. },
  1096. showFileIcon: function () {
  1097. this.$captionContainer.find('.kv-caption-icon').show();
  1098. },
  1099. resetErrors: function (fade) {
  1100. var self = this, $error = self.$errorContainer;
  1101. self.isError = false;
  1102. self.$container.removeClass('has-error');
  1103. $error.html('');
  1104. if (fade) {
  1105. $error.fadeOut('slow');
  1106. } else {
  1107. $error.hide();
  1108. }
  1109. },
  1110. showUploadError: function (msg, data, previewId, index) {
  1111. var self = this, $error = self.$errorContainer,
  1112. ev = arguments.length > 4 ? arguments[4] : 'fileuploaderror';
  1113. if ($error.find('ul').length == 0) {
  1114. $error.html('<ul class="text-left"><li>' + msg + '</li></ul>');
  1115. } else {
  1116. $error.find('ul').append('<li>' + msg + '</li>');
  1117. }
  1118. $error.fadeIn(800);
  1119. self.raise(ev, [data, previewId, index, self.reader]);
  1120. addCss(self.$container, 'has-error');
  1121. return true;
  1122. },
  1123. showError: function (msg, file, previewId, index) {
  1124. var self = this, $error = self.$errorContainer,
  1125. ev = arguments.length > 4 ? arguments[4] : 'fileerror',
  1126. jqXHR = arguments.length > 5 ? arguments[5] : {};
  1127. $error.html(msg);
  1128. $error.fadeIn(800);
  1129. self.raise(ev, [file, previewId, index, self.reader, jqXHR]);
  1130. if (!self.isUploadable) {
  1131. self.clearFileInput();
  1132. }
  1133. addCss(self.$container, 'has-error');
  1134. self.$btnUpload.attr('disabled', true);
  1135. return true;
  1136. },
  1137. errorHandler: function (evt, caption) {
  1138. var self = this;
  1139. switch (evt.target.error.code) {
  1140. case evt.target.error.NOT_FOUND_ERR:
  1141. self.addError(self.msgFileNotFound.replace(/\{name\}/g, caption));
  1142. break;
  1143. case evt.target.error.NOT_READABLE_ERR:
  1144. self.addError(self.msgFileNotReadable.replace(/\{name\}/g, caption));
  1145. break;
  1146. case evt.target.error.ABORT_ERR:
  1147. self.addError(self.msgFilePreviewAborted.replace(/\{name\}/g, caption));
  1148. break;
  1149. default:
  1150. self.addError(self.msgFilePreviewError.replace(/\{name\}/g, caption));
  1151. }
  1152. },
  1153. parseFileType: function (file) {
  1154. var isValid, vType;
  1155. for (var i = 0; i < defaultPreviewTypes.length; i++) {
  1156. cat = defaultPreviewTypes[i];
  1157. isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  1158. vType = isValid(file.type, file.name) ? cat : '';
  1159. if (vType != '') {
  1160. return vType;
  1161. }
  1162. }
  1163. return 'other';
  1164. },
  1165. previewDefault: function (file, previewId) {
  1166. var self = this;
  1167. if (!self.showPreview) {
  1168. return;
  1169. }
  1170. var data = vUrl.createObjectURL(file), $obj = $('#' + previewId),
  1171. config = self.previewSettings.other,
  1172. footer = self.isUploadable ?
  1173. self.renderFileFooter(file.name, config.width) :
  1174. self.renderFileFooter(file.name, config.width, false),
  1175. previewOtherTemplate = self.getPreviewTemplate('other'),
  1176. ind = previewId.slice(previewId.lastIndexOf('-') + 1),
  1177. frameClass = '';
  1178. if (arguments.length > 2) {
  1179. var $err = $(self.msgValidationError);
  1180. frameClass = ' btn disabled';
  1181. footer += '<div class="file-other-error text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i></div>';
  1182. }
  1183. self.$preview.append("\n" + previewOtherTemplate
  1184. .replace(/\{previewId\}/g, previewId)
  1185. .replace(/\{frameClass\}/g, frameClass)
  1186. .replace(/\{fileindex\}/g, ind)
  1187. .replace(/\{caption\}/g, self.slug(file.name))
  1188. .replace(/\{width\}/g, config.width)
  1189. .replace(/\{height\}/g, config.height)
  1190. .replace(/\{type\}/g, file.type)
  1191. .replace(/\{data\}/g, data)
  1192. .replace(/\{footer\}/g, footer));
  1193. $obj.on('load', function (e) {
  1194. vUrl.revokeObjectURL($obj.attr('data'));
  1195. });
  1196. },
  1197. previewFile: function (file, theFile, previewId, data) {
  1198. var self = this;
  1199. if (!self.showPreview) {
  1200. return;
  1201. }
  1202. var cat = self.parseFileType(file), caption = self.slug(file.name), data, obj, content,
  1203. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes, fType = file.type,
  1204. template = isSet(cat,
  1205. self.previewTemplates) ? self.previewTemplates[cat] : defaultPreviewTemplates[cat],
  1206. config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat],
  1207. wrapLen = parseInt(self.wrapTextLength), wrapInd = self.wrapIndicator, $preview = self.$preview,
  1208. chkTypes = types.indexOf(cat) >= 0, chkMimes = isEmpty(mimes) || (!isEmpty(mimes) && isSet(file.type,
  1209. mimes)),
  1210. footer = self.renderFileFooter(caption, config.width),
  1211. ind = previewId.slice(previewId.lastIndexOf('-') + 1);
  1212. if (chkTypes && chkMimes) {
  1213. if (cat == 'text') {
  1214. var strText = htmlEncode(theFile.target.result);
  1215. vUrl.revokeObjectURL(data);
  1216. if (strText.length > wrapLen) {
  1217. var id = 'text-' + uniqId(), height = window.innerHeight * .75,
  1218. modal = self.getLayoutTemplate('modal')
  1219. .replace(/\{id\}/g, id)
  1220. .replace(/\{title\}/g, caption)
  1221. .replace(/\{height\}/g, height)
  1222. .replace(/\{body\}/g, strText);
  1223. wrapInd = wrapInd
  1224. .replace(/\{title\}/g, caption)
  1225. .replace(/\{dialog\}/g, "$('#" + id + "').modal('show')");
  1226. strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
  1227. }
  1228. content = template
  1229. .replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption)
  1230. .replace(/\{frameClass\}/g, '')
  1231. .replace(/\{type\}/g, file.type).replace(/\{width\}/g, config.width)
  1232. .replace(/\{height\}/g, config.height).replace(/\{data\}/g, strText)
  1233. .replace(/\{footer\}/g, footer).replace(/\{fileindex\}/g, ind) + modal;
  1234. } else {
  1235. content = template
  1236. .replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption)
  1237. .replace(/\{frameClass\}/g, '')
  1238. .replace(/\{type\}/g, file.type).replace(/\{data\}/g, data)
  1239. .replace(/\{width\}/g, config.width).replace(/\{height\}/g, config.height)
  1240. .replace(/\{footer\}/g, footer).replace(/\{fileindex\}/g, ind);
  1241. }
  1242. $preview.append("\n" + content);
  1243. self.autoSizeImage(previewId);
  1244. } else {
  1245. self.previewDefault(file, previewId);
  1246. }
  1247. },
  1248. slugDefault: function (text) {
  1249. return isEmpty(text) ? '' : text.split(/(\\|\/)/g).pop().replace(/[^\w-.\\\/ ]+/g, '');
  1250. },
  1251. getFileStack: function () {
  1252. var size = 0, self = this;
  1253. return self.filestack.filter(function (n) {
  1254. return n != undefined
  1255. });
  1256. },
  1257. readFiles: function (files) {
  1258. this.reader = new FileReader();
  1259. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  1260. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  1261. msgProgress = self.msgProgress, msgSelected = self.msgSelected, fileType = self.previewFileType,
  1262. wrapLen = parseInt(self.wrapTextLength), wrapInd = self.wrapIndicator,
  1263. previewInitId = self.previewInitId, numFiles = files.length, settings = self.fileTypeSettings,
  1264. isText = isSet('text', settings) ? settings['text'] : defaultFileTypeSettings['text'],
  1265. ctr = self.filestack.length,
  1266. throwError = function (msg, file, previewId, index) {
  1267. self.previewDefault(file, previewId, true);
  1268. var outData = self.getOutData({}, {}, files);
  1269. return self.isUploadable ? self.showUploadError(msg, outData, previewId,
  1270. index) : self.showError(msg, file, previewId, index);
  1271. };
  1272. function readFile(i) {
  1273. if (isEmpty($el.attr('multiple'))) {
  1274. numFiles = 1;
  1275. }
  1276. if (i >= numFiles) {
  1277. $container.removeClass('loading');
  1278. $status.html('');
  1279. return;
  1280. }
  1281. var node = ctr + i, previewId = previewInitId + "-" + node, file = files[i], caption = self.slug(file.name),
  1282. fileSize = (file.size ? file.size : 0) / 1000, checkFile,
  1283. previewData = vUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk,
  1284. fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '),
  1285. fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', '),
  1286. fileExtExpr = isEmpty(fileExt) ? '' : new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  1287. fileSize = fileSize.toFixed(2);
  1288. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  1289. msg = self.msgSizeTooLarge.replace(/\{name\}/g, caption).replace(/\{size\}/g,
  1290. fileSize).replace(/\{maxSize\}/g, self.maxFileSize);
  1291. self.isError = throwError(msg, file, previewId, i);
  1292. return;
  1293. }
  1294. if (!isEmpty(fileTypes) && isArray(fileTypes)) {
  1295. for (j = 0; j < fileTypes.length; j++) {
  1296. typ = fileTypes[j];
  1297. checkFile = settings[typ];
  1298. chk = (checkFile !== undefined && checkFile(file.type, caption));
  1299. fileCount += isEmpty(chk) ? 0 : chk.length;
  1300. }
  1301. if (fileCount == 0) {
  1302. msg = self.msgInvalidFileType.replace(/\{name\}/g, caption).replace(/\{types\}/g, strTypes);
  1303. self.isError = throwError(msg, file, previewId, i);
  1304. return;
  1305. }
  1306. }
  1307. if (fileCount == 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) {
  1308. chk = caption.match(fileExtExpr);
  1309. fileCount += isEmpty(chk) ? 0 : chk.length;
  1310. if (fileCount == 0) {
  1311. msg = self.msgInvalidFileExtension.replace(/\{name\}/g, caption).replace(/\{extensions\}/g,
  1312. strExt);
  1313. self.isError = throwError(msg, file, previewId, i);
  1314. return;
  1315. }
  1316. }
  1317. if (!self.showPreview) {
  1318. self.filestack.push(file);
  1319. setTimeout(readFile(i + 1), 100);
  1320. self.raise('fileloaded', [file, previewId, i, reader]);
  1321. return;
  1322. }
  1323. if ($preview.length > 0 && typeof FileReader !== "undefined") {
  1324. $status.html(msgLoading.replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles));
  1325. $container.addClass('loading');
  1326. reader.onerror = function (evt) {
  1327. self.errorHandler(evt, caption);
  1328. };
  1329. reader.onload = function (theFile) {
  1330. self.previewFile(file, theFile, previewId, previewData);
  1331. self.initFileActions();
  1332. };
  1333. reader.onloadend = function (e) {
  1334. var msg = msgProgress
  1335. .replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles)
  1336. .replace(/\{percent\}/g, 50).replace(/\{name\}/g, caption);
  1337. setTimeout(function () {
  1338. $status.html(msg);
  1339. vUrl.revokeObjectURL(previewData);
  1340. }, 100);
  1341. setTimeout(function () {
  1342. readFile(i + 1);
  1343. self.updateFileDetails(numFiles);
  1344. }, 100);
  1345. self.raise('fileloaded', [file, previewId, i, reader]);
  1346. };
  1347. reader.onprogress = function (data) {
  1348. if (data.lengthComputable) {
  1349. var progress = parseInt(((data.loaded / data.total) * 100), 10);
  1350. var msg = msgProgress
  1351. .replace(/\{index\}/g, i + 1).replace(/\{files\}/g, numFiles)
  1352. .replace(/\{percent\}/g, progress).replace(/\{name\}/g, caption);
  1353. setTimeout(function () {
  1354. $status.html(msg);
  1355. }, 100);
  1356. }
  1357. };
  1358. if (isText(file.type, caption)) {
  1359. reader.readAsText(file, self.textEncoding);
  1360. } else {
  1361. reader.readAsArrayBuffer(file);
  1362. }
  1363. } else {
  1364. self.previewDefault(file, previewId);
  1365. setTimeout(function () {
  1366. readFile(i + 1);
  1367. self.updateFileDetails(numFiles);
  1368. }, 100);
  1369. self.raise('fileloaded', [file, previewId, i, reader]);
  1370. }
  1371. self.filestack.push(file);
  1372. }
  1373. readFile(0);
  1374. self.updateFileDetails(numFiles, false);
  1375. },
  1376. updateFileDetails: function (numFiles) {
  1377. var self = this, msgSelected = self.msgSelected, $el = self.$element, fileStack = self.getFileStack(),
  1378. name = $el.val() || (fileStack.length && fileStack[0].name) || '', label = self.slug(name),
  1379. n = self.isUploadable ? fileStack.length : numFiles;
  1380. numFiles = self.initialPreviewCount + n,
  1381. log = n > 1 ? msgSelected.replace(/\{n\}/g, numFiles) : label;
  1382. if (self.isError) {
  1383. self.$previewContainer.removeClass('loading');
  1384. self.$previewStatus.html('');
  1385. self.$captionContainer.find('.kv-caption-icon').hide();
  1386. log = self.msgValidationError;
  1387. } else {
  1388. self.showFileIcon();
  1389. }
  1390. self.setCaption(log);
  1391. self.$container.removeClass('file-input-new file-input-ajax-new');
  1392. if (arguments.length == 1) {
  1393. self.raise('fileselect', [numFiles, label]);
  1394. }
  1395. },
  1396. change: function (e) {
  1397. var self = this, $el = self.$element, label = self.slug($el.val()),
  1398. total = 0, $preview = self.$preview, isDragDrop = arguments.length > 1,
  1399. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files,
  1400. msgSelected = self.msgSelected,
  1401. numFiles = !isEmpty(files) ? (files.length + self.initialPreviewCount) : 1, tfiles,
  1402. ctr = self.filestack.length, isAjaxUpload = (self.isUploadable && ctr != 0),
  1403. isSingleUpload = isEmpty($el.attr('multiple')),
  1404. throwError = function (msg, file, previewId, index) {
  1405. var outData = self.getOutData({}, {}, files);
  1406. return self.isUploadable ? self.showUploadError(msg, outData, previewId,
  1407. index) : self.showError(msg, file, previewId, index);
  1408. };
  1409. self.resetUpload();
  1410. self.hideFileIcon();
  1411. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  1412. if (isDragDrop) {
  1413. tfiles = files;
  1414. } else {
  1415. if (e.target.files === undefined) {
  1416. tfiles = e.target && e.target.value ? [
  1417. {name: e.target.value.replace(/^.+\\/, '')}
  1418. ] : [];
  1419. } else {
  1420. tfiles = e.target.files;
  1421. }
  1422. }
  1423. if (isEmpty(tfiles) || tfiles.length === 0) {
  1424. if (!isAjaxUpload) {
  1425. self.clear(false);
  1426. }
  1427. self.raise('fileselectnone');
  1428. return;
  1429. }
  1430. self.resetErrors();
  1431. if (!isAjaxUpload || (isSingleUpload && ctr > 0)) {
  1432. if (!self.overwriteInitial) {
  1433. $preview.html(self.initialPreviewContent);
  1434. } else {
  1435. $preview.html('');
  1436. }
  1437. if (isSingleUpload && ctr > 0) {
  1438. self.filestack = [];
  1439. }
  1440. }
  1441. var total = self.isUploadable ? self.getFileStack().length + tfiles.length : tfiles.length;
  1442. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  1443. var msg = self.msgFilesTooMany.replace(/\{m\}/g, self.maxFileCount).replace(/\{n\}/g, total);
  1444. self.isError = throwError(msg, null, null, null);
  1445. self.$captionContainer.find('.kv-caption-icon').hide();
  1446. self.$caption.html(self.msgValidationError);
  1447. self.setEllipsis();
  1448. self.$container.removeClass('file-input-new file-input-ajax-new');
  1449. return;
  1450. }
  1451. if (!self.isIE9) {
  1452. self.readFiles(files);
  1453. } else {
  1454. self.updateFileDetails(1);
  1455. }
  1456. self.reader = null;
  1457. },
  1458. autoSizeImage: function (previewId) {
  1459. var self = this, $preview = self.$preview,
  1460. $thumb = $preview.find("#" + previewId),
  1461. $img = $thumb.find('img');
  1462. if (!$img.length) {
  1463. return;
  1464. }
  1465. $img.on('load', function () {
  1466. var w1 = $thumb.width(), w2 = $preview.width();
  1467. if (w1 > w2) {
  1468. $img.css('width', '100%');
  1469. $thumb.css('width', '97%');
  1470. }
  1471. var $cap = $img.closest('.file-preview-frame').find('.file-caption-name');
  1472. if ($cap.length) {
  1473. $cap.width($img.width());
  1474. $cap.attr('title', $cap.text());
  1475. }
  1476. self.raise('fileimageloaded', previewId);
  1477. });
  1478. },
  1479. setCaption: function (content) {
  1480. var self = this, title = $('<div>' + content + '</div>').text(),
  1481. icon = self.getLayoutTemplate('icon'),
  1482. out = icon + title;
  1483. if (self.$caption.length == 0) {
  1484. return;
  1485. }
  1486. self.$caption.html(out);
  1487. self.$caption.attr('title', title);
  1488. self.$captionContainer.find('.file-caption-ellipsis').attr('title', title);
  1489. self.setEllipsis();
  1490. },
  1491. initBrowse: function ($container) {
  1492. var self = this;
  1493. self.$btnFile = $container.find('.btn-file');
  1494. self.$btnFile.append(self.$element);
  1495. },
  1496. createContainer: function () {
  1497. var self = this;
  1498. var $container = $(document.createElement("span")).attr({"class": 'file-input file-input-new'}).html(self.renderMain());
  1499. self.$element.before($container);
  1500. self.initBrowse($container);
  1501. return $container;
  1502. },
  1503. refreshContainer: function () {
  1504. var self = this, $container = self.$container;
  1505. $container.before(self.$element);
  1506. $container.html(self.renderMain());
  1507. self.initBrowse($container);
  1508. },
  1509. renderMain: function () {
  1510. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : '';
  1511. var preview = self.showPreview ? self.getLayoutTemplate('preview')
  1512. .replace(/\{class\}/g, self.previewClass)
  1513. .replace(/\{dropClass\}/g, dropCss)
  1514. : '';
  1515. var css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass;
  1516. var caption = self.captionTemplate.replace(/\{class\}/g, css + ' kv-fileinput-caption');
  1517. return self.mainTemplate.replace(/\{class\}/g, self.mainClass).
  1518. replace(/\{preview\}/g, preview).
  1519. replace(/\{caption\}/g, caption).
  1520. replace(/\{upload\}/g, self.renderUpload()).
  1521. replace(/\{remove\}/g, self.renderRemove()).
  1522. replace(/\{cancel\}/g, self.renderCancel()).
  1523. replace(/\{browse\}/g, self.renderBrowse());
  1524. },
  1525. renderBrowse: function () {
  1526. var self = this, css = self.browseClass + ' btn-file', status = '';
  1527. if (self.isDisabled) {
  1528. status = ' disabled ';
  1529. }
  1530. return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>';
  1531. },
  1532. renderRemove: function () {
  1533. var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
  1534. if (!self.showRemove) {
  1535. return '';
  1536. }
  1537. if (self.isDisabled) {
  1538. status = ' disabled ';
  1539. }
  1540. return '<button type="button" title="' + self.removeTitle + '" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
  1541. },
  1542. renderCancel: function () {
  1543. var self = this, css = self.cancelClass + ' fileinput-cancel fileinput-cancel-button', status = '';
  1544. if (!self.showCancel) {
  1545. return '';
  1546. }
  1547. return '<button type="button" title="' + self.cancelTitle + '" class="hide ' + css + '">' + self.cancelIcon + self.cancelLabel + '</button>';
  1548. },
  1549. renderUpload: function () {
  1550. var self = this, css = self.uploadClass + ' kv-fileinput-upload fileinput-upload-button', content = '', status = '';
  1551. if (!self.showUpload) {
  1552. return '';
  1553. }
  1554. if (self.isDisabled) {
  1555. status = ' disabled ';
  1556. }
  1557. if (!self.isUploadable || self.isDisabled) {
  1558. content = '<button type="submit" title="' + self.uploadTitle + '"class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
  1559. } else {
  1560. content = '<a href="' + self.uploadUrl + '" title="' + self.uploadTitle + '" class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>';
  1561. }
  1562. return content;
  1563. }
  1564. }
  1565. //FileInput plugin definition
  1566. $.fn.fileinput = function (option) {
  1567. if (!hasFileAPISupport() && !isIE(9)) {
  1568. return;
  1569. }
  1570. var args = Array.apply(null, arguments);
  1571. args.shift();
  1572. return this.each(function () {
  1573. var $this = $(this),
  1574. data = $this.data('fileinput'),
  1575. options = typeof option === 'object' && option;
  1576. if (!data) {
  1577. $this.data('fileinput',
  1578. (data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data()))));
  1579. }
  1580. if (typeof option === 'string') {
  1581. data[option].apply(data, args);
  1582. }
  1583. });
  1584. };
  1585. $.fn.fileinput.defaults = {
  1586. showCaption: true,
  1587. showPreview: true,
  1588. showRemove: true,
  1589. showUpload: true,
  1590. showCancel: true,
  1591. mainClass: '',
  1592. previewClass: '',
  1593. captionClass: '',
  1594. mainTemplate: null,
  1595. initialCaption: '',
  1596. initialPreview: '',
  1597. initialPreviewCount: 0,
  1598. initialPreviewDelimiter: '*$$*',
  1599. initialPreviewConfig: [],
  1600. initialPreviewShowDelete: true,
  1601. overwriteInitial: true,
  1602. layoutTemplates: defaultLayoutTemplates,
  1603. previewTemplates: defaultPreviewTemplates,
  1604. allowedPreviewTypes: defaultPreviewTypes,
  1605. allowedPreviewMimeTypes: null,
  1606. allowedFileTypes: null,
  1607. allowedFileExtensions: null,
  1608. previewSettings: defaultPreviewSettings,
  1609. fileTypeSettings: defaultFileTypeSettings,
  1610. browseLabel: 'Browse &hellip;',
  1611. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  1612. browseClass: 'btn btn-primary',
  1613. removeLabel: 'Remove',
  1614. removeTitle: 'Clear selected files',
  1615. removeIcon: '<i class="glyphicon glyphicon-trash"></i> ',
  1616. removeClass: 'btn btn-default',
  1617. cancelLabel: 'Cancel',
  1618. cancelTitle: 'Abort ongoing upload',
  1619. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  1620. cancelClass: 'btn btn-default',
  1621. uploadLabel: 'Upload',
  1622. uploadTitle: 'Upload selected files',
  1623. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  1624. uploadClass: 'btn btn-default',
  1625. uploadUrl: null,
  1626. uploadExtraData: [],
  1627. uploadAsync: true,
  1628. maxFileSize: 0,
  1629. maxFileCount: 0,
  1630. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>. Please retry your upload!',
  1631. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>. Please retry your upload!',
  1632. msgFileNotFound: 'File "{name}" not found!',
  1633. msgFileNotReadable: 'File "{name}" is not readable.',
  1634. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  1635. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  1636. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  1637. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  1638. msgValidationError: '<span class="text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i> File Upload Error</span>',
  1639. msgErrorClass: 'file-error-message',
  1640. msgLoading: 'Loading file {index} of {files} &hellip;',
  1641. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  1642. msgSelected: '{n} files selected',
  1643. previewFileType: 'image',
  1644. wrapTextLength: 250,
  1645. wrapIndicator: ' <span class="wrap-indicator" title="{title}" onclick="{dialog}">[&hellip;]</span>',
  1646. elCaptionContainer: null,
  1647. elCaptionText: null,
  1648. elPreviewContainer: null,
  1649. elPreviewImage: null,
  1650. elPreviewStatus: null,
  1651. elErrorContainer: null,
  1652. slugCallback: null,
  1653. dropZoneEnabled: true,
  1654. dropZoneTitle: 'Drag & drop files here &hellip;',
  1655. dropZoneTitleClass: 'file-drop-zone-title',
  1656. fileActionSettings: {},
  1657. otherActionButtons: '',
  1658. textEncoding: 'UTF-8'
  1659. };
  1660. $.fn.fileinput.Constructor = FileInput;
  1661. /**
  1662. * Convert automatically file inputs with class 'file'
  1663. * into a bootstrap fileinput control.
  1664. */
  1665. $(document).ready(function () {
  1666. var $input = $('input.file[type=file]'), count = $input.attr('type') != null ? $input.length : 0;
  1667. if (count > 0) {
  1668. $input.fileinput();
  1669. }
  1670. });
  1671. })(window.jQuery);