fileinput.js 85 KB

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