fileinput.js 86 KB

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