fileinput.js 101 KB

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