fileinput.js 82 KB

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