fileinput.js 126 KB

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