fileinput.js 84 KB

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