fileinput.js 84 KB

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