fileinput.js 79 KB

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