fileinput.js 104 KB

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