fileinput.js 109 KB

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