fileinput.js 79 KB

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