fileinput.js 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843
  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. cap = n > 1 ? self.msgSelected.repl('{n}', n) : filestack[0].name;
  613. self.setCaption(cap);
  614. }
  615. });
  616. });
  617. });
  618. self.$preview.find('.kv-file-upload').each(function () {
  619. var $el = $(this);
  620. $el.off('click').on('click', function () {
  621. var $frame = $el.closest('.file-preview-frame'),
  622. ind = $frame.attr('data-fileindex');
  623. self.uploadSingle(ind, self.filestack, false);
  624. });
  625. });
  626. },
  627. renderInitFileFooter: function (i) {
  628. if (this.initialPreviewConfig.length === 0 || isEmpty(this.initialPreviewConfig[i])) {
  629. return '';
  630. }
  631. var self = this, template = self.getLayoutTemplate('footer'),
  632. config = self.initialPreviewConfig[i],
  633. caption = isSet('caption', config) ? config.caption : '',
  634. width = isSet('width', config) ? config.width : 'auto',
  635. url = isSet('url', config) ? config.url : false,
  636. key = isSet('key', config) ? config.key : null,
  637. disabled = (url === false),
  638. actions = self.initialPreviewShowDelete ? self.renderFileActions(false, true, disabled, url, key, i) : '',
  639. footer = template.repl('{actions}', actions);
  640. return footer.repl('{caption}', caption).repl('{width}', width)
  641. .repl('{indicator}', '').repl('{indicatorTitle}', '');
  642. },
  643. renderFileFooter: function (caption, width) {
  644. var self = this, config = self.fileActionSettings, footer,
  645. template = self.getLayoutTemplate('footer');
  646. if (self.isUploadable) {
  647. footer = template.repl('{actions}', self.renderFileActions(true, true, false, false, false, false));
  648. return footer.repl('{caption}', caption)
  649. .repl('{width}', width)
  650. .repl('{indicator}', config.indicatorNew)
  651. .repl('{indicatorTitle}', config.indicatorNewTitle);
  652. }
  653. return template.repl('{actions}', '')
  654. .repl('{caption}', caption)
  655. .repl('{width}', width)
  656. .repl('{indicator}', '')
  657. .repl('{indicatorTitle}', '');
  658. },
  659. renderFileActions: function (showUpload, showDelete, disabled, url, key, index) {
  660. if (!showUpload && !showDelete) {
  661. return '';
  662. }
  663. var self = this,
  664. vUrl = url === false ? '' : ' data-url="' + url + '"',
  665. vIndex = index === false ? '' : ' data-index="' + index + '"',
  666. vKey = key === false ? '' : ' data-key="' + key + '"',
  667. btnDelete = self.getLayoutTemplate('actionDelete'),
  668. btnUpload = '',
  669. template = self.getLayoutTemplate('actions'),
  670. otherActionButtons = self.otherActionButtons.repl('{dataKey}', vKey),
  671. config = self.fileActionSettings,
  672. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  673. btnDelete = btnDelete
  674. .repl('{removeClass}', removeClass)
  675. .repl('{removeIcon}', config.removeIcon)
  676. .repl('{removeTitle}', config.removeTitle)
  677. .repl('{dataUrl}', vUrl)
  678. .repl('{dataKey}', vKey)
  679. .repl('{dataIndex}', vIndex);
  680. if (showUpload) {
  681. btnUpload = self.getLayoutTemplate('actionUpload')
  682. .repl('{uploadClass}', config.uploadClass)
  683. .repl('{uploadIcon}', config.uploadIcon)
  684. .repl('{uploadTitle}', config.uploadTitle);
  685. }
  686. return template
  687. .repl('{delete}', btnDelete)
  688. .repl('{upload}', btnUpload)
  689. .repl('{other}', otherActionButtons);
  690. },
  691. getInitialPreview: function (template, content, i) {
  692. var self = this, ind = 'init_' + i,
  693. previewId = self.previewInitId + '-' + ind,
  694. footer = self.renderInitFileFooter(i, false);
  695. return template
  696. .repl('{previewId}', previewId)
  697. .repl('{frameClass}', ' file-preview-initial')
  698. .repl('{fileindex}', ind)
  699. .repl('{content}', content)
  700. .repl('{footer}', footer);
  701. },
  702. initPreview: function () {
  703. var self = this, html = '', content = self.initialPreview, len = self.initialPreviewCount,
  704. cap = self.initialCaption.length, i, fileList,
  705. caption = (cap > 0) ? self.initialCaption : self.msgSelected.repl('{n}', len);
  706. if (isArray(content) && len > 0) {
  707. for (i = 0; i < len; i += 1) {
  708. html += self.getInitialPreview(self.previewGenericTemplate, content[i], i);
  709. }
  710. if (len > 1 && cap === 0) {
  711. caption = self.msgSelected.repl('{n}', len);
  712. }
  713. } else {
  714. if (len > 0) {
  715. fileList = content.split(self.initialPreviewDelimiter);
  716. for (i = 0; i < len; i += 1) {
  717. html += self.getInitialPreview(self.previewGenericTemplate, fileList[i], i);
  718. }
  719. if (len > 1 && cap === 0) {
  720. caption = self.msgSelected.repl('{n}', len);
  721. }
  722. } else {
  723. if (cap > 0) {
  724. self.setCaption(caption);
  725. }
  726. return;
  727. }
  728. }
  729. self.initialPreviewContent = html;
  730. self.$preview.html(html);
  731. self.setCaption(caption);
  732. self.$container.removeClass('file-input-new');
  733. },
  734. initPreviewDeletes: function () {
  735. var self = this, deleteExtraData = self.deleteExtraData || {}, caption, $that,
  736. resetProgress = function () {
  737. if (self.$preview.find('.kv-file-remove').length === 0) {
  738. self.reset();
  739. }
  740. };
  741. self.$preview.find('.kv-file-remove').each(function () {
  742. var $el = $(this), $frame = $el.closest('.file-preview-frame'), index = $el.data('index'),
  743. config = isEmpty(self.initialPreviewConfig[index]) ? null : self.initialPreviewConfig[index],
  744. extraData = isEmpty(config) || isEmpty(config.extra) ? deleteExtraData : config.extra,
  745. vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key'), $content;
  746. if (typeof extraData === "function") {
  747. extraData = extraData();
  748. }
  749. if (vUrl === undefined || vKey === undefined) {
  750. return;
  751. }
  752. $el.off('click').on('click', function () {
  753. $.ajax({
  754. url: vUrl,
  755. type: 'POST',
  756. dataType: 'json',
  757. data: $.extend({key: vKey}, extraData),
  758. beforeSend: function (jqXHR) {
  759. addCss($frame, 'file-uploading');
  760. addCss($el, 'disabled');
  761. self.raise('filepredelete', [vKey, jqXHR, extraData]);
  762. },
  763. success: function (data, textStatus, jqXHR) {
  764. if (data.error === undefined) {
  765. self.raise('filedeleted', [vKey, jqXHR, extraData]);
  766. } else {
  767. self.showError(data.error, extraData, $el.attr('id'), vKey, 'filedeleteerror', jqXHR);
  768. $frame.removeClass('file-uploading');
  769. $el.removeClass('disabled');
  770. resetProgress();
  771. return;
  772. }
  773. $frame.removeClass('file-uploading').addClass('file-deleted');
  774. $frame.fadeOut('slow', function () {
  775. self.clearObjects($frame);
  776. $frame.remove();
  777. $content = $(document.createElement('div')).html(self.original.preview);
  778. $content.find('.file-preview-frame').each(function () {
  779. $that = $(this);
  780. if ($that.find('.kv-file-remove').attr('data-key') == vKey) {
  781. $that.remove();
  782. }
  783. });
  784. self.initialPreviewContent = $content.html();
  785. if (self.initialPreviewCount > 0) {
  786. self.initialPreviewCount -= 1;
  787. }
  788. caption = self.initialCaption;
  789. if (self.initialCaption.length === 0) {
  790. caption = self.msgSelected.repl('{n}', self.initialPreviewCount);
  791. }
  792. self.original.preview = $content.html();
  793. self.setCaption(caption);
  794. self.original.caption = self.$caption.html();
  795. $content.remove();
  796. resetProgress();
  797. });
  798. },
  799. error: function (jqXHR, textStatus, errorThrown) {
  800. self.showError(errorThrown, extraData, $el.attr('id'), vKey, 'filedeleteerror', jqXHR);
  801. $frame.removeClass('file-uploading');
  802. resetProgress();
  803. }
  804. });
  805. });
  806. });
  807. },
  808. clearObjects: function ($el) {
  809. $el.find('video audio').each(function () {
  810. this.pause();
  811. $(this).remove();
  812. });
  813. $el.find('img object div').each(function () {
  814. $(this).remove();
  815. });
  816. },
  817. clearFileInput: function () {
  818. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  819. if (isEmpty($el.val())) {
  820. return;
  821. }
  822. // Fix for IE ver < 11, that does not clear file inputs
  823. // Requires a sequence of steps to prevent IE crashing but
  824. // still allow clearing of the file input.
  825. if (self.isIE9 || self.isIE10) {
  826. $srcFrm = $el.closest('form');
  827. $tmpFrm = $(document.createElement('form'));
  828. $tmpEl = $(document.createElement('div'));
  829. $el.before($tmpEl);
  830. if ($srcFrm.length) {
  831. $srcFrm.after($tmpFrm);
  832. } else {
  833. $tmpEl.after($tmpFrm);
  834. }
  835. $tmpFrm.append($el).trigger('reset');
  836. $tmpEl.before($el).remove();
  837. $tmpFrm.remove();
  838. } else { // normal input clear behavior for other sane browsers
  839. $el.val('');
  840. }
  841. },
  842. resetUpload: function () {
  843. var self = this;
  844. self.uploadCount = 0;
  845. self.uploadPercent = 0;
  846. self.$btnUpload.removeAttr('disabled');
  847. self.setProgress(0);
  848. addCss(self.$progress, 'hide');
  849. self.resetErrors(false);
  850. self.ajaxRequests = [];
  851. },
  852. cancel: function () {
  853. var self = this, xhr = self.ajaxRequests, len = xhr.length, i;
  854. if (len > 0) {
  855. for (i = 0; i < len; i += 1) {
  856. xhr[i].abort();
  857. }
  858. }
  859. self.$preview.find('.file-preview-frame').each(function () {
  860. var $thumb = $(this), ind = $thumb.attr('data-fileindex');
  861. $thumb.removeClass('file-uploading');
  862. if (self.filestack[ind] !== undefined) {
  863. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  864. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  865. }
  866. self.unlock();
  867. });
  868. },
  869. clear: function (trig) {
  870. var self = this, cap;
  871. if (!self.isIE9 && self.reader instanceof FileReader) {
  872. self.reader.abort();
  873. }
  874. self.$btnUpload.removeAttr('disabled');
  875. self.resetUpload();
  876. self.filestack = [];
  877. self.clearFileInput();
  878. self.resetErrors(true);
  879. if (trig !== true) {
  880. self.raise('change');
  881. self.raise('fileclear');
  882. }
  883. if (self.overwriteInitial) {
  884. self.initialPreviewCount = 0;
  885. self.initialPreviewContent = '';
  886. }
  887. if (!self.overwriteInitial && self.initialPreviewContent.length > 0) {
  888. self.showFileIcon();
  889. self.$preview.html(self.original.preview);
  890. self.$caption.html(self.original.caption);
  891. self.setEllipsis();
  892. self.initPreviewDeletes();
  893. self.$container.removeClass('file-input-new');
  894. } else {
  895. self.$preview.find('.file-preview-frame').each(function () {
  896. self.clearObjects($(this));
  897. });
  898. self.$preview.html('');
  899. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.original.caption : '';
  900. self.$caption.html(cap);
  901. self.setEllipsis();
  902. self.$caption.attr('title', '');
  903. addCss(self.$container, 'file-input-new');
  904. }
  905. if (self.$container.find('.file-preview-frame').length === 0) {
  906. self.initialCaption = '';
  907. self.original.caption = '';
  908. self.$caption.html('');
  909. self.setEllipsis();
  910. self.$captionContainer.find('.kv-caption-icon').hide();
  911. }
  912. self.hideFileIcon();
  913. self.raise('filecleared');
  914. self.$captionContainer.focus();
  915. self.setFileDropZoneTitle();
  916. },
  917. reset: function () {
  918. var self = this;
  919. self.clear(true);
  920. self.$preview.html(self.original.preview);
  921. self.$caption.html(self.original.caption);
  922. self.setEllipsis();
  923. self.$container.find('.fileinput-filename').text('');
  924. self.raise('filereset');
  925. if (self.initialPreview.length > 0) {
  926. self.$container.removeClass('file-input-new');
  927. }
  928. self.setFileDropZoneTitle();
  929. if (self.isUploadable) {
  930. self.resetUpload();
  931. }
  932. self.filestack = [];
  933. self.formdata = {};
  934. },
  935. disable: function () {
  936. var self = this;
  937. self.isDisabled = true;
  938. self.raise('filedisabled');
  939. self.$element.attr('disabled', 'disabled');
  940. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  941. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").attr("disabled", true);
  942. self.initDragDrop();
  943. },
  944. enable: function () {
  945. var self = this;
  946. self.isDisabled = false;
  947. self.raise('fileenabled');
  948. self.$element.removeAttr('disabled');
  949. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  950. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").removeAttr("disabled");
  951. self.initDragDrop();
  952. },
  953. getExtraData: function () {
  954. var self = this, data = self.uploadExtraData;
  955. if (typeof self.uploadExtraData === "function") {
  956. data = self.uploadExtraData();
  957. }
  958. return data;
  959. },
  960. uploadExtra: function () {
  961. var self = this, data = self.getExtraData();
  962. if (data.length === 0) {
  963. return;
  964. }
  965. $.each(data, function (key, value) {
  966. self.formdata.append(key, value);
  967. });
  968. },
  969. initXhr: function (xhrobj, factor) {
  970. var self = this;
  971. if (xhrobj.upload) {
  972. xhrobj.upload.addEventListener('progress', function (event) {
  973. var pct = 0, position = event.loaded || event.position, total = event.total;
  974. if (event.lengthComputable) {
  975. pct = Math.ceil(position / total * factor);
  976. }
  977. self.uploadPercent = Math.max(pct, self.uploadPercent);
  978. self.setProgress(self.uploadPercent);
  979. }, false);
  980. }
  981. return xhrobj;
  982. },
  983. ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError) {
  984. var self = this, settings;
  985. self.uploadExtra();
  986. settings = $.extend(self.ajaxSettings, {
  987. xhr: function () {
  988. var xhrobj = $.ajaxSettings.xhr();
  989. return self.initXhr(xhrobj, 98);
  990. },
  991. url: self.uploadUrl,
  992. type: 'POST',
  993. dataType: 'json',
  994. data: self.formdata,
  995. cache: false,
  996. processData: false,
  997. contentType: false,
  998. beforeSend: fnBefore,
  999. success: fnSuccess,
  1000. complete: fnComplete,
  1001. error: fnError
  1002. });
  1003. self.ajaxRequests.push($.ajax(settings));
  1004. },
  1005. uploadSingle: function (i, files, allFiles) {
  1006. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  1007. previewId = self.previewInitId + "-" + i, $thumb = $('#' + previewId), cap, pct, chkComplete,
  1008. $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove'),
  1009. $indicator = $thumb.find('.file-upload-indicator'), config = self.fileActionSettings,
  1010. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1011. setIndicator, updateProgress, resetActions, fnBefore, fnSuccess, fnComplete, fnError;
  1012. self.formdata = formdata;
  1013. if (total === 0 || !hasPostData || $btnUpload.hasClass('disabled')) {
  1014. return;
  1015. }
  1016. chkComplete = function () {
  1017. var $thumbs = self.$preview.find('.file-preview-frame.file-uploading'), chk = $thumbs.length;
  1018. if (chk > 0) {
  1019. return;
  1020. }
  1021. self.setProgress(100);
  1022. self.unlock();
  1023. self.clearFileInput();
  1024. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1025. };
  1026. setIndicator = function (icon, msg) {
  1027. $indicator.html(config[icon]);
  1028. $indicator.attr('title', config[msg]);
  1029. };
  1030. updateProgress = function () {
  1031. if (!allFiles || total === 0 || self.uploadPercent >= 100) {
  1032. return;
  1033. }
  1034. self.uploadCount += 1;
  1035. pct = 80 + Math.ceil(self.uploadCount * 20 / total);
  1036. self.uploadPercent = Math.max(pct, self.uploadPercent);
  1037. self.setProgress(self.uploadPercent);
  1038. self.initPreviewDeletes();
  1039. };
  1040. resetActions = function () {
  1041. $btnUpload.removeAttr('disabled');
  1042. $btnDelete.removeAttr('disabled');
  1043. $thumb.removeClass('file-uploading');
  1044. };
  1045. fnBefore = function (jqXHR) {
  1046. outData = self.getOutData(jqXHR);
  1047. setIndicator('indicatorLoading', 'indicatorLoadingTitle');
  1048. addCss($thumb, 'file-uploading');
  1049. $btnUpload.attr('disabled', true);
  1050. $btnDelete.attr('disabled', true);
  1051. if (!allFiles) {
  1052. self.lock();
  1053. }
  1054. self.raise('filepreupload', [outData, previewId, i]);
  1055. };
  1056. fnSuccess = function (data, textStatus, jqXHR) {
  1057. outData = self.getOutData(jqXHR, data);
  1058. setTimeout(function () {
  1059. if (data.error === undefined) {
  1060. setIndicator('indicatorSuccess', 'indicatorSuccessTitle');
  1061. $btnUpload.hide();
  1062. $btnDelete.hide();
  1063. self.filestack[i] = undefined;
  1064. if (!allFiles) {
  1065. self.resetFileStack();
  1066. }
  1067. self.raise('fileuploaded', [outData, previewId, i]);
  1068. } else {
  1069. setIndicator('indicatorError', 'indicatorErrorTitle');
  1070. self.showUploadError(data.error, outData, previewId, i);
  1071. }
  1072. }, 100);
  1073. };
  1074. fnComplete = function () {
  1075. setTimeout(function () {
  1076. updateProgress();
  1077. resetActions();
  1078. if (!allFiles) {
  1079. self.unlock(false);
  1080. } else {
  1081. chkComplete();
  1082. }
  1083. }, 100);
  1084. };
  1085. fnError = function (jqXHR, textStatus, errorThrown) {
  1086. setIndicator('indicatorError', 'indicatorErrorTitle');
  1087. outData = self.getOutData(jqXHR);
  1088. if (allFiles) {
  1089. cap = files[i].name;
  1090. self.showUploadError('<b>' + cap + '</b>: ' + errorThrown, outData, previewId, i);
  1091. } else {
  1092. self.showUploadError(errorThrown, outData, previewId, i);
  1093. }
  1094. };
  1095. formdata.append(self.uploadFileAttr, files[i]);
  1096. formdata.append('file_id', i);
  1097. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1098. },
  1099. uploadBatch: function () {
  1100. var self = this, files = self.filestack, total = files.length, config,
  1101. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1102. setIndicator, setAllUploaded, enableActions, fnBefore, fnSuccess, fnComplete, fnError;
  1103. self.formdata = new FormData();
  1104. if (total === 0 || !hasPostData) {
  1105. return;
  1106. }
  1107. config = self.fileActionSettings;
  1108. setIndicator = function (i, icon, msg) {
  1109. var $indicator = $('#' + self.previewInitId + "-" + i).find('.file-upload-indicator');
  1110. $indicator.html(config[icon]);
  1111. $indicator.attr('title', config[msg]);
  1112. };
  1113. enableActions = function (i) {
  1114. var $thumb = $('#' + self.previewInitId + "-" + i),
  1115. $btnUpload = $thumb.find('.kv-file-upload'),
  1116. $btnDelete = $thumb.find('.kv-file-delete');
  1117. $thumb.removeClass('file-uploading');
  1118. $btnUpload.removeAttr('disabled');
  1119. $btnDelete.removeAttr('disabled');
  1120. };
  1121. setAllUploaded = function () {
  1122. $.each(files, function (key, data) {
  1123. self.filestack[key] = undefined;
  1124. });
  1125. self.clearFileInput();
  1126. };
  1127. fnBefore = function (jqXHR) {
  1128. self.lock();
  1129. var outData = self.getOutData(jqXHR);
  1130. if (self.showPreview) {
  1131. self.$preview.find('.file-preview-frame').each(function () {
  1132. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove');
  1133. addCss($thumb, 'file-uploading');
  1134. $btnUpload.attr('disabled', true);
  1135. $btnDelete.attr('disabled', true);
  1136. });
  1137. }
  1138. self.raise('filebatchpreupload', [outData]);
  1139. };
  1140. fnSuccess = function (data, textStatus, jqXHR) {
  1141. var outData = self.getOutData(jqXHR, data),
  1142. keys = isEmpty(data.errorkeys) ? [] : data.errorkeys;
  1143. if (data.error === undefined || isEmpty(data.error)) {
  1144. self.raise('filebatchuploadsuccess', [outData]);
  1145. setAllUploaded();
  1146. if (self.showPreview) {
  1147. self.$preview.find('.kv-file-upload').hide();
  1148. self.$preview.find('.kv-file-remove').hide();
  1149. self.$preview.find('.file-preview-frame').each(function () {
  1150. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1151. setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle');
  1152. enableActions(key);
  1153. });
  1154. } else {
  1155. self.reset();
  1156. }
  1157. } else {
  1158. if (self.showPreview) {
  1159. self.$preview.find('.file-preview-frame').each(function () {
  1160. var $thumb = $(this), key = parseInt($thumb.attr('data-fileindex'), 10);
  1161. enableActions(key);
  1162. if (keys.length === 0) {
  1163. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1164. return;
  1165. }
  1166. if ($.inArray(key, keys) !== -1) {
  1167. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1168. } else {
  1169. $thumb.find('.kv-file-upload').hide();
  1170. $thumb.find('.kv-file-remove').hide();
  1171. setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle');
  1172. self.filestack[key] = undefined;
  1173. }
  1174. });
  1175. }
  1176. self.showUploadError(data.error, outData, null, null, 'filebatchuploaderror');
  1177. }
  1178. };
  1179. fnComplete = function () {
  1180. self.setProgress(100);
  1181. self.unlock();
  1182. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1183. self.clearFileInput();
  1184. };
  1185. fnError = function (jqXHR, textStatus, errorThrown) {
  1186. var outData = self.getOutData(jqXHR);
  1187. self.showUploadError(errorThrown, outData, null, null, 'filebatchuploaderror');
  1188. self.uploadFileCount = total - 1;
  1189. if (!self.showPreview) {
  1190. return;
  1191. }
  1192. self.$preview.find('.file-preview-frame').each(function () {
  1193. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1194. $thumb.removeClass('file-uploading');
  1195. if (self.filestack[key] !== undefined) {
  1196. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1197. }
  1198. });
  1199. self.$preview.find('.file-preview-frame').removeClass('file-uploading');
  1200. self.$preview.find('.file-preview-frame kv-file-upload').removeAttr('disabled');
  1201. self.$preview.find('.file-preview-frame kv-file-delete').removeAttr('disabled');
  1202. };
  1203. $.each(files, function (key, data) {
  1204. if (!isEmpty(files[key])) {
  1205. self.formdata.append(self.uploadFileAttr, data);
  1206. }
  1207. });
  1208. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1209. },
  1210. uploadExtraOnly: function () {
  1211. var self = this, fnBefore, fnSuccess, fnComplete, fnError;
  1212. self.formdata = new FormData();
  1213. fnBefore = function (jqXHR) {
  1214. self.lock();
  1215. var outData = self.getOutData(jqXHR);
  1216. self.raise('filebatchpreupload', [outData]);
  1217. self.setProgress(50);
  1218. };
  1219. fnSuccess = function (data, textStatus, jqXHR) {
  1220. var outData = self.getOutData(jqXHR, data),
  1221. keys = isEmpty(data.errorkeys) ? [] : data.errorkeys;
  1222. if (data.error === undefined || isEmpty(data.error)) {
  1223. self.raise('filebatchuploadsuccess', [outData]);
  1224. self.clearFileInput();
  1225. } else {
  1226. self.showUploadError(data.error, outData, null, null, 'filebatchuploaderror');
  1227. }
  1228. };
  1229. fnComplete = function () {
  1230. self.setProgress(100);
  1231. self.unlock();
  1232. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1233. self.clearFileInput();
  1234. };
  1235. fnError = function (jqXHR, textStatus, errorThrown) {
  1236. var outData = self.getOutData(jqXHR);
  1237. self.showUploadError(errorThrown, outData, null, null, 'filebatchuploaderror');
  1238. };
  1239. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1240. },
  1241. hideFileIcon: function () {
  1242. if (this.overwriteInitial) {
  1243. this.$captionContainer.find('.kv-caption-icon').hide();
  1244. }
  1245. },
  1246. showFileIcon: function () {
  1247. this.$captionContainer.find('.kv-caption-icon').show();
  1248. },
  1249. resetErrors: function (fade) {
  1250. var self = this, $error = self.$errorContainer;
  1251. self.isError = false;
  1252. self.$container.removeClass('has-error');
  1253. $error.html('');
  1254. if (fade) {
  1255. $error.fadeOut('slow');
  1256. } else {
  1257. $error.hide();
  1258. }
  1259. },
  1260. showUploadError: function (msg, data, previewId, index, ev) {
  1261. var self = this, $error = self.$errorContainer;
  1262. ev = ev || 'fileuploaderror';
  1263. if ($error.find('ul').length === 0) {
  1264. $error.html('<ul class="text-left"><li>' + msg + '</li></ul>');
  1265. } else {
  1266. $error.find('ul').append('<li>' + msg + '</li>');
  1267. }
  1268. $error.fadeIn(800);
  1269. self.raise(ev, [data, previewId, index, self.reader]);
  1270. addCss(self.$container, 'has-error');
  1271. return true;
  1272. },
  1273. showError: function (msg, file, previewId, index, ev, jqXHR) {
  1274. var self = this, $error = self.$errorContainer;
  1275. ev = ev || 'fileerror';
  1276. jqXHR = jqXHR || {};
  1277. $error.html(msg);
  1278. $error.fadeIn(800);
  1279. self.raise(ev, [file, previewId, index, self.reader, jqXHR]);
  1280. if (!self.isUploadable) {
  1281. self.clearFileInput();
  1282. }
  1283. addCss(self.$container, 'has-error');
  1284. self.$btnUpload.attr('disabled', true);
  1285. return true;
  1286. },
  1287. errorHandler: function (evt, caption) {
  1288. var self = this, err = evt.target.error;
  1289. switch (err.code) {
  1290. case err.NOT_FOUND_ERR:
  1291. self.addError(self.msgFileNotFound.repl('{name}', caption));
  1292. break;
  1293. case err.SECURITY_ERR:
  1294. self.addError(self.msgFileSecured.repl('{name}', caption));
  1295. break;
  1296. case err.NOT_READABLE_ERR:
  1297. self.addError(self.msgFileNotReadable.repl('{name}', caption));
  1298. break;
  1299. case err.ABORT_ERR:
  1300. self.addError(self.msgFilePreviewAborted.repl('{name}', caption));
  1301. break;
  1302. default:
  1303. self.addError(self.msgFilePreviewError.repl('{name}', caption));
  1304. }
  1305. },
  1306. parseFileType: function (file) {
  1307. var self = this, isValid, vType, cat, i;
  1308. for (i = 0; i < defaultPreviewTypes.length; i += 1) {
  1309. cat = defaultPreviewTypes[i];
  1310. isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  1311. vType = isValid(file.type, file.name) ? cat : '';
  1312. if (!isEmpty(vType)) {
  1313. return vType;
  1314. }
  1315. }
  1316. return 'other';
  1317. },
  1318. previewDefault: function (file, previewId, isDisabled) {
  1319. if (!this.showPreview) {
  1320. return;
  1321. }
  1322. var self = this, data = objUrl.createObjectURL(file), $obj = $('#' + previewId),
  1323. config = self.previewSettings.other,
  1324. footer = self.renderFileFooter(file.name, config.width),
  1325. previewOtherTemplate = self.getPreviewTemplate('other'),
  1326. ind = previewId.slice(previewId.lastIndexOf('-') + 1),
  1327. frameClass = '';
  1328. if (isDisabled === true) {
  1329. frameClass = ' btn disabled';
  1330. footer += '<div class="file-other-error text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i></div>';
  1331. }
  1332. self.$preview.append("\n" + previewOtherTemplate
  1333. .repl('{previewId}', previewId)
  1334. .repl('{frameClass}', frameClass)
  1335. .repl('{fileindex}', ind)
  1336. .repl('{caption}', self.slug(file.name))
  1337. .repl('{width}', config.width)
  1338. .repl('{height}', config.height)
  1339. .repl('{type}', file.type)
  1340. .repl('{data}', data)
  1341. .repl('{footer}', footer));
  1342. $obj.on('load', function () {
  1343. objUrl.revokeObjectURL($obj.attr('data'));
  1344. });
  1345. },
  1346. previewFile: function (file, theFile, previewId, data) {
  1347. if (!this.showPreview) {
  1348. return;
  1349. }
  1350. var self = this, cat = self.parseFileType(file), caption = self.slug(file.name), content, strText,
  1351. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes,
  1352. tmplt = self.getPreviewTemplate(cat),
  1353. config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat],
  1354. wrapLen = parseInt(self.wrapTextLength, 10), wrapInd = self.wrapIndicator,
  1355. chkTypes = types.indexOf(cat) >= 0, id, height,
  1356. chkMimes = isEmpty(mimes) || (!isEmpty(mimes) && isSet(file.type, mimes)),
  1357. footer = self.renderFileFooter(caption, config.width), modal = '',
  1358. ind = previewId.slice(previewId.lastIndexOf('-') + 1);
  1359. if (chkTypes && chkMimes) {
  1360. if (cat === 'text') {
  1361. strText = htmlEncode(theFile.target.result);
  1362. objUrl.revokeObjectURL(data);
  1363. if (strText.length > wrapLen) {
  1364. id = 'text-' + uniqId();
  1365. height = window.innerHeight * 0.75;
  1366. modal = self.getLayoutTemplate('modal').repl('{id}', id)
  1367. .repl('{title}', caption)
  1368. .repl('{height}', height)
  1369. .repl('{body}', strText);
  1370. wrapInd = wrapInd
  1371. .repl('{title}', caption)
  1372. .repl('{dialog}', "$('#" + id + "').modal('show')");
  1373. strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
  1374. }
  1375. content = tmplt.repl('{previewId}', previewId).repl('{caption}', caption)
  1376. .repl('{frameClass}', '')
  1377. .repl('{type}', file.type).repl('{width}', config.width)
  1378. .repl('{height}', config.height).repl('{data}', strText)
  1379. .repl('{footer}', footer).repl('{fileindex}', ind) + modal;
  1380. } else {
  1381. content = tmplt.repl('{previewId}', previewId).repl('{caption}', caption)
  1382. .repl('{frameClass}', '')
  1383. .repl('{type}', file.type).repl('{data}', data)
  1384. .repl('{width}', config.width).repl('{height}', config.height)
  1385. .repl('{footer}', footer).repl('{fileindex}', ind);
  1386. }
  1387. self.$preview.append("\n" + content);
  1388. self.autoSizeImage(previewId);
  1389. } else {
  1390. self.previewDefault(file, previewId);
  1391. }
  1392. },
  1393. slugDefault: function (text) {
  1394. return isEmpty(text) ? '' : text.split(/(\\|\/)/g).pop().replace(/[^\w\-.\\\/ ]+/g, '');
  1395. },
  1396. getFileStack: function () {
  1397. var self = this;
  1398. return self.filestack.filter(function (n) {
  1399. return n !== undefined;
  1400. });
  1401. },
  1402. readFiles: function (files) {
  1403. this.reader = new FileReader();
  1404. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  1405. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  1406. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  1407. settings = self.fileTypeSettings, ctr = self.filestack.length,
  1408. throwError = function (msg, file, previewId, index) {
  1409. self.previewDefault(file, previewId, true);
  1410. var outData = self.getOutData({}, {}, files);
  1411. return self.isUploadable ? self.showUploadError(msg, outData, previewId,
  1412. index) : self.showError(msg, file, previewId, index);
  1413. };
  1414. function readFile(i) {
  1415. if (isEmpty($el.attr('multiple'))) {
  1416. numFiles = 1;
  1417. }
  1418. if (i >= numFiles) {
  1419. $container.removeClass('loading');
  1420. $status.html('');
  1421. return;
  1422. }
  1423. var node = ctr + i, previewId = previewInitId + "-" + node, isText, file = files[i],
  1424. caption = self.slug(file.name), fileSize = (file.size || 0) / 1000, checkFile, fileExtExpr = '',
  1425. previewData = objUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk,
  1426. fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '),
  1427. fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', ');
  1428. if (!isEmpty(fileExt)) {
  1429. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  1430. }
  1431. fileSize = fileSize.toFixed(2);
  1432. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  1433. msg = self.msgSizeTooLarge.repl('{name}', caption)
  1434. .repl('{size}', fileSize)
  1435. .repl('{maxSize}', self.maxFileSize);
  1436. self.isError = throwError(msg, file, previewId, i);
  1437. return;
  1438. }
  1439. if (!isEmpty(fileTypes) && isArray(fileTypes)) {
  1440. for (j = 0; j < fileTypes.length; j += 1) {
  1441. typ = fileTypes[j];
  1442. checkFile = settings[typ];
  1443. chk = (checkFile !== undefined && checkFile(file.type, caption));
  1444. fileCount += isEmpty(chk) ? 0 : chk.length;
  1445. }
  1446. if (fileCount === 0) {
  1447. msg = self.msgInvalidFileType.repl('{name}', caption).repl('{types}', strTypes);
  1448. self.isError = throwError(msg, file, previewId, i);
  1449. return;
  1450. }
  1451. }
  1452. if (fileCount === 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) {
  1453. chk = caption.match(fileExtExpr);
  1454. fileCount += isEmpty(chk) ? 0 : chk.length;
  1455. if (fileCount === 0) {
  1456. msg = self.msgInvalidFileExtension.repl('{name}', caption).repl('{extensions}',
  1457. strExt);
  1458. self.isError = throwError(msg, file, previewId, i);
  1459. return;
  1460. }
  1461. }
  1462. if (!self.showPreview) {
  1463. self.filestack.push(file);
  1464. setTimeout(readFile(i + 1), 100);
  1465. self.raise('fileloaded', [file, previewId, i, reader]);
  1466. return;
  1467. }
  1468. if ($preview.length > 0 && FileReader !== undefined) {
  1469. $status.html(msgLoading.repl('{index}', i + 1).repl('{files}', numFiles));
  1470. $container.addClass('loading');
  1471. reader.onerror = function (evt) {
  1472. self.errorHandler(evt, caption);
  1473. };
  1474. reader.onload = function (theFile) {
  1475. self.previewFile(file, theFile, previewId, previewData);
  1476. self.initFileActions();
  1477. };
  1478. reader.onloadend = function () {
  1479. msg = msgProgress
  1480. .repl('{index}', i + 1).repl('{files}', numFiles)
  1481. .repl('{percent}', 50).repl('{name}', caption);
  1482. setTimeout(function () {
  1483. $status.html(msg);
  1484. objUrl.revokeObjectURL(previewData);
  1485. }, 100);
  1486. setTimeout(function () {
  1487. readFile(i + 1);
  1488. self.updateFileDetails(numFiles);
  1489. }, 100);
  1490. self.raise('fileloaded', [file, previewId, i, reader]);
  1491. };
  1492. reader.onprogress = function (data) {
  1493. if (data.lengthComputable) {
  1494. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  1495. msg = msgProgress.repl('{index}', i + 1).repl('{files}', numFiles)
  1496. .repl('{percent}', progress).repl('{name}', caption);
  1497. setTimeout(function () {
  1498. $status.html(msg);
  1499. }, 100);
  1500. }
  1501. };
  1502. isText = isSet('text', settings) ? settings.text : defaultFileTypeSettings.text;
  1503. if (isText(file.type, caption)) {
  1504. reader.readAsText(file, self.textEncoding);
  1505. } else {
  1506. reader.readAsArrayBuffer(file);
  1507. }
  1508. } else {
  1509. self.previewDefault(file, previewId);
  1510. setTimeout(function () {
  1511. readFile(i + 1);
  1512. self.updateFileDetails(numFiles);
  1513. }, 100);
  1514. self.raise('fileloaded', [file, previewId, i, reader]);
  1515. }
  1516. self.filestack.push(file);
  1517. }
  1518. readFile(0);
  1519. self.updateFileDetails(numFiles, false);
  1520. },
  1521. updateFileDetails: function (numFiles) {
  1522. var self = this, msgSelected = self.msgSelected, $el = self.$element, fileStack = self.getFileStack(),
  1523. name = $el.val() || (fileStack.length && fileStack[0].name) || '', label = self.slug(name),
  1524. n = self.isUploadable ? fileStack.length : numFiles,
  1525. nFiles = self.initialPreviewCount + n,
  1526. log = n > 1 ? msgSelected.repl('{n}', nFiles) : label;
  1527. if (self.isError) {
  1528. self.$previewContainer.removeClass('loading');
  1529. self.$previewStatus.html('');
  1530. self.$captionContainer.find('.kv-caption-icon').hide();
  1531. log = self.msgValidationError;
  1532. } else {
  1533. self.showFileIcon();
  1534. }
  1535. self.setCaption(log);
  1536. self.$container.removeClass('file-input-new file-input-ajax-new');
  1537. if (arguments.length === 1) {
  1538. self.raise('fileselect', [numFiles, label]);
  1539. }
  1540. },
  1541. change: function (e) {
  1542. var self = this, $el = self.$element;
  1543. if (!self.isUploadable && isEmpty($el.val())) { // IE 11 fix
  1544. return;
  1545. }
  1546. var tfiles, msg, total, $preview = self.$preview, isDragDrop = arguments.length > 1,
  1547. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files,
  1548. isSingleUpload = isEmpty($el.attr('multiple')),
  1549. ctr = self.filestack.length, isAjaxUpload = (self.isUploadable && ctr !== 0),
  1550. throwError = function (mesg, file, previewId, index) {
  1551. var outData = self.getOutData({}, {}, files);
  1552. return self.isUploadable ? self.showUploadError(mesg, outData, previewId,
  1553. index) : self.showError(mesg, file, previewId, index);
  1554. };
  1555. self.resetUpload();
  1556. self.hideFileIcon();
  1557. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  1558. if (isDragDrop) {
  1559. tfiles = files;
  1560. } else {
  1561. if (e.target.files === undefined) {
  1562. tfiles = e.target && e.target.value ? [
  1563. {name: e.target.value.replace(/^.+\\/, '')}
  1564. ] : [];
  1565. } else {
  1566. tfiles = e.target.files;
  1567. }
  1568. }
  1569. if (isEmpty(tfiles) || tfiles.length === 0) {
  1570. if (!isAjaxUpload) {
  1571. self.clear(true);
  1572. }
  1573. self.raise('fileselectnone');
  1574. return;
  1575. }
  1576. self.resetErrors();
  1577. if (!isAjaxUpload || (isSingleUpload && ctr > 0)) {
  1578. if (!self.overwriteInitial) {
  1579. $preview.html(self.initialPreviewContent);
  1580. } else {
  1581. $preview.html('');
  1582. }
  1583. if (isSingleUpload && ctr > 0) {
  1584. self.filestack = [];
  1585. }
  1586. }
  1587. total = self.isUploadable ? self.getFileStack().length + tfiles.length : tfiles.length;
  1588. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  1589. msg = self.msgFilesTooMany.repl('{m}', self.maxFileCount).repl('{n}', total);
  1590. self.isError = throwError(msg, null, null, null);
  1591. self.$captionContainer.find('.kv-caption-icon').hide();
  1592. self.$caption.html(self.msgValidationError);
  1593. self.setEllipsis();
  1594. self.$container.removeClass('file-input-new file-input-ajax-new');
  1595. return;
  1596. }
  1597. if (!self.isIE9) {
  1598. self.readFiles(tfiles);
  1599. } else {
  1600. self.updateFileDetails(1);
  1601. }
  1602. if (isAjaxUpload) {
  1603. self.raise('filebatchselected', [self.getFileStack()]);
  1604. } else {
  1605. self.raise('filebatchselected', [tfiles]);
  1606. }
  1607. self.reader = null;
  1608. },
  1609. autoSizeImage: function (previewId) {
  1610. var self = this, $preview = self.$preview,
  1611. $thumb = $preview.find("#" + previewId),
  1612. $img = $thumb.find('img'), w1, w2, $cap;
  1613. if (!$img.length) {
  1614. return;
  1615. }
  1616. $img.on('load', function () {
  1617. w1 = $thumb.width();
  1618. w2 = $preview.width();
  1619. if (w1 > w2) {
  1620. $img.css('width', '100%');
  1621. $thumb.css('width', '97%');
  1622. }
  1623. $cap = $img.closest('.file-preview-frame').find('.file-caption-name');
  1624. if ($cap.length) {
  1625. $cap.width($img.width());
  1626. $cap.attr('title', $cap.text());
  1627. }
  1628. self.raise('fileimageloaded', previewId);
  1629. });
  1630. },
  1631. setCaption: function (content) {
  1632. var self = this, title = $('<div>' + content + '</div>').text(),
  1633. icon = self.getLayoutTemplate('icon'),
  1634. out = icon + title;
  1635. if (self.$caption.length === 0) {
  1636. return;
  1637. }
  1638. self.$caption.html(out);
  1639. self.$caption.attr('title', title);
  1640. self.$captionContainer.find('.file-caption-ellipsis').attr('title', title);
  1641. self.setEllipsis();
  1642. },
  1643. initBrowse: function ($container) {
  1644. var self = this;
  1645. self.$btnFile = $container.find('.btn-file');
  1646. self.$btnFile.append(self.$element);
  1647. },
  1648. createContainer: function () {
  1649. var self = this,
  1650. $container = $(document.createElement("span"))
  1651. .attr({"class": 'file-input file-input-new'})
  1652. .html(self.renderMain());
  1653. self.$element.before($container);
  1654. self.initBrowse($container);
  1655. return $container;
  1656. },
  1657. refreshContainer: function () {
  1658. var self = this, $container = self.$container;
  1659. $container.before(self.$element);
  1660. $container.html(self.renderMain());
  1661. self.initBrowse($container);
  1662. },
  1663. renderMain: function () {
  1664. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : '',
  1665. preview = self.showPreview ? self.getLayoutTemplate('preview').repl('{class}', self.previewClass)
  1666. .repl('{dropClass}', dropCss) : '',
  1667. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  1668. caption = self.captionTemplate.repl('{class}', css + ' kv-fileinput-caption');
  1669. return self.mainTemplate.repl('{class}', self.mainClass)
  1670. .repl('{preview}', preview)
  1671. .repl('{caption}', caption)
  1672. .repl('{upload}', self.renderUpload())
  1673. .repl('{remove}', self.renderRemove())
  1674. .repl('{cancel}', self.renderCancel())
  1675. .repl('{browse}', self.renderBrowse());
  1676. },
  1677. renderBrowse: function () {
  1678. var self = this, css = self.browseClass + ' btn-file', status = '';
  1679. if (self.isDisabled) {
  1680. status = ' disabled ';
  1681. }
  1682. return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>';
  1683. },
  1684. renderRemove: function () {
  1685. var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
  1686. if (!self.showRemove) {
  1687. return '';
  1688. }
  1689. if (self.isDisabled) {
  1690. status = ' disabled ';
  1691. }
  1692. return '<button type="button" title="' + self.removeTitle + '" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
  1693. },
  1694. renderCancel: function () {
  1695. var self = this, css = self.cancelClass + ' fileinput-cancel fileinput-cancel-button';
  1696. if (!self.showCancel) {
  1697. return '';
  1698. }
  1699. return '<button type="button" title="' + self.cancelTitle + '" class="hide ' + css + '">' + self.cancelIcon + self.cancelLabel + '</button>';
  1700. },
  1701. renderUpload: function () {
  1702. var self = this, css = self.uploadClass + ' kv-fileinput-upload fileinput-upload-button', content = '', status = '';
  1703. if (!self.showUpload) {
  1704. return '';
  1705. }
  1706. if (self.isDisabled) {
  1707. status = ' disabled ';
  1708. }
  1709. if (!self.isUploadable || self.isDisabled) {
  1710. content = '<button type="submit" title="' + self.uploadTitle + '"class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
  1711. } else {
  1712. content = '<a href="' + self.uploadUrl + '" title="' + self.uploadTitle + '" class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>';
  1713. }
  1714. return content;
  1715. }
  1716. };
  1717. //FileInput plugin definition
  1718. $.fn.fileinput = function (option) {
  1719. if (!hasFileAPISupport() && !isIE(9)) {
  1720. return;
  1721. }
  1722. var args = Array.apply(null, arguments);
  1723. args.shift();
  1724. return this.each(function () {
  1725. var $this = $(this),
  1726. data = $this.data('fileinput'),
  1727. options = typeof option === 'object' && option;
  1728. if (!data) {
  1729. data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data()));
  1730. $this.data('fileinput', data);
  1731. }
  1732. if (typeof option === 'string') {
  1733. data[option].apply(data, args);
  1734. }
  1735. });
  1736. };
  1737. $.fn.fileinput.defaults = {
  1738. showCaption: true,
  1739. showPreview: true,
  1740. showRemove: true,
  1741. showUpload: true,
  1742. showCancel: true,
  1743. mainClass: '',
  1744. previewClass: '',
  1745. captionClass: '',
  1746. mainTemplate: null,
  1747. initialCaption: '',
  1748. initialPreview: '',
  1749. initialPreviewCount: 0,
  1750. initialPreviewDelimiter: '*$$*',
  1751. initialPreviewConfig: [],
  1752. initialPreviewShowDelete: true,
  1753. deleteUrl: '',
  1754. deleteExtraData: {},
  1755. overwriteInitial: true,
  1756. layoutTemplates: defaultLayoutTemplates,
  1757. previewTemplates: defaultPreviewTemplates,
  1758. allowedPreviewTypes: defaultPreviewTypes,
  1759. allowedPreviewMimeTypes: null,
  1760. allowedFileTypes: null,
  1761. allowedFileExtensions: null,
  1762. customLayoutTags: {},
  1763. customPreviewTags: {},
  1764. previewSettings: defaultPreviewSettings,
  1765. fileTypeSettings: defaultFileTypeSettings,
  1766. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  1767. browseLabel: 'Browse &hellip;',
  1768. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  1769. browseClass: 'btn btn-primary',
  1770. removeLabel: 'Remove',
  1771. removeTitle: 'Clear selected files',
  1772. removeIcon: '<i class="glyphicon glyphicon-trash"></i> ',
  1773. removeClass: 'btn btn-default',
  1774. cancelLabel: 'Cancel',
  1775. cancelTitle: 'Abort ongoing upload',
  1776. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  1777. cancelClass: 'btn btn-default',
  1778. uploadLabel: 'Upload',
  1779. uploadTitle: 'Upload selected files',
  1780. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  1781. uploadClass: 'btn btn-default',
  1782. uploadUrl: null,
  1783. uploadAsync: true,
  1784. uploadExtraData: {},
  1785. maxFileSize: 0,
  1786. maxFileCount: 0,
  1787. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>. Please retry your upload!',
  1788. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>. Please retry your upload!',
  1789. msgFileNotFound: 'File "{name}" not found!',
  1790. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  1791. msgFileNotReadable: 'File "{name}" is not readable.',
  1792. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  1793. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  1794. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  1795. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  1796. msgValidationError: '<span class="text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i> File Upload Error</span>',
  1797. msgErrorClass: 'file-error-message',
  1798. msgLoading: 'Loading file {index} of {files} &hellip;',
  1799. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  1800. msgSelected: '{n} files selected',
  1801. progressClass: "progress-bar progress-bar-success progress-bar-striped active",
  1802. progressCompleteClass: "progress-bar progress-bar-success",
  1803. previewFileType: 'image',
  1804. wrapTextLength: 250,
  1805. wrapIndicator: ' <span class="wrap-indicator" title="{title}" onclick="{dialog}">[&hellip;]</span>',
  1806. elCaptionContainer: null,
  1807. elCaptionText: null,
  1808. elPreviewContainer: null,
  1809. elPreviewImage: null,
  1810. elPreviewStatus: null,
  1811. elErrorContainer: null,
  1812. slugCallback: null,
  1813. dropZoneEnabled: true,
  1814. dropZoneTitle: 'Drag & drop files here &hellip;',
  1815. dropZoneTitleClass: 'file-drop-zone-title',
  1816. fileActionSettings: {},
  1817. otherActionButtons: '',
  1818. textEncoding: 'UTF-8',
  1819. ajaxSettings: {}
  1820. };
  1821. $.fn.fileinput.Constructor = FileInput;
  1822. /**
  1823. * Convert automatically file inputs with class 'file'
  1824. * into a bootstrap fileinput control.
  1825. */
  1826. $(document).ready(function () {
  1827. var $input = $('input.file[type=file]'), count = $input.attr('type') ? $input.length : 0;
  1828. if (count > 0) {
  1829. $input.fileinput();
  1830. }
  1831. });
  1832. })(window.jQuery);