fileinput.js 85 KB

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