fileinput.js 85 KB

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