fileinput.js 86 KB

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