fileinput.js 109 KB

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