fileinput.js 81 KB

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