fileinput.js 101 KB

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