fileinput.js 86 KB

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