fileinput.js 79 KB

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