fileinput.js 121 KB

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