fileinput.js 79 KB

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