fileinput.js 101 KB

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