fileinput.js 84 KB

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