fileinput.js 79 KB

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