fileinput.js 82 KB

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