fileinput.js 82 KB

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