fileinput.js 123 KB

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