fileinput.js 82 KB

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