fileinput.js 84 KB

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