fileinput.js 126 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764
  1. /*!
  2. * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2015
  3. * @version 4.3.2
  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. if (isEmpty(self.allowedPreviewTypes)) {
  560. self.allowedPreviewTypes = defaultPreviewTypes;
  561. }
  562. self.fileInputCleared = false;
  563. self.fileBatchCompleted = true;
  564. if (!self.isPreviewable) {
  565. self.showPreview = false;
  566. }
  567. self.uploadFileAttr = !isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data';
  568. self.reader = null;
  569. self.formdata = {};
  570. self.clearStack();
  571. self.uploadCount = 0;
  572. self.uploadStatus = {};
  573. self.uploadLog = [];
  574. self.uploadAsyncCount = 0;
  575. self.loadedImages = [];
  576. self.totalImagesCount = 0;
  577. self.ajaxRequests = [];
  578. self.isError = false;
  579. self.ajaxAborted = false;
  580. self.cancelling = false;
  581. t = self._getLayoutTemplate('progress');
  582. self.progressTemplate = t.replace('{class}', self.progressClass);
  583. self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass);
  584. self.progressErrorTemplate = t.replace('{class}', self.progressErrorClass);
  585. self.dropZoneEnabled = hasDragDropSupport() && self.dropZoneEnabled;
  586. self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly');
  587. self.isUploadable = hasFileUploadSupport() && !isEmpty(self.uploadUrl);
  588. self.slug = typeof options.slugCallback === "function" ? options.slugCallback : self._slugDefault;
  589. self.mainTemplate = self.showCaption ? self._getLayoutTemplate('main1') : self._getLayoutTemplate('main2');
  590. self.captionTemplate = self._getLayoutTemplate('caption');
  591. self.previewGenericTemplate = self._getPreviewTemplate('generic');
  592. if (self.resizeImage && (self.maxImageWidth || self.maxImageHeight)) {
  593. self.imageCanvas = document.createElement('canvas');
  594. self.imageCanvasContext = self.imageCanvas.getContext('2d');
  595. }
  596. if (isEmpty(self.$element.attr('id'))) {
  597. self.$element.attr('id', uniqId());
  598. }
  599. if (self.$container === undefined) {
  600. self.$container = self._createContainer();
  601. } else {
  602. self._refreshContainer();
  603. }
  604. self.$dropZone = self.$container.find('.file-drop-zone');
  605. self.$progress = self.$container.find('.kv-upload-progress');
  606. self.$btnUpload = self.$container.find('.fileinput-upload');
  607. self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption'));
  608. self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name'));
  609. self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview'));
  610. self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails'));
  611. self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status'));
  612. self.$errorContainer = getElement(options, 'elErrorContainer',
  613. self.$previewContainer.find('.kv-fileinput-error'));
  614. if (!isEmpty(self.msgErrorClass)) {
  615. addCss(self.$errorContainer, self.msgErrorClass);
  616. }
  617. self.$errorContainer.hide();
  618. self.fileActionSettings = $.extend(true, defaultFileActionSettings, options.fileActionSettings);
  619. self.previewInitId = "preview-" + uniqId();
  620. self.id = self.$element.attr('id');
  621. previewCache.init(self);
  622. self._initPreview(true);
  623. self._initPreviewDeletes();
  624. self.options = options;
  625. self._setFileDropZoneTitle();
  626. self.$element.removeClass('file-loading');
  627. if (self.$element.attr('disabled')) {
  628. self.disable();
  629. }
  630. },
  631. _validate: function () {
  632. var self = this, $exception;
  633. if (self.$element.attr('type') === 'file') {
  634. return true;
  635. }
  636. $exception = '<div class="help-block alert alert-warning">' +
  637. '<h4>Invalid Input Type</h4>' +
  638. 'You must set an input <code>type = file</code> for <b>bootstrap-fileinput</b> plugin to initialize.' +
  639. '</div>';
  640. self.$element.after($exception);
  641. return false;
  642. },
  643. _errorsExist: function () {
  644. var self = this, $err;
  645. if (self.$errorContainer.find('li').length) {
  646. return true;
  647. }
  648. $err = $(document.createElement('div')).html(self.$errorContainer.html());
  649. $err.find('span.kv-error-close').remove();
  650. $err.find('ul').remove();
  651. return $.trim($err.text()).length ? true : false;
  652. },
  653. _errorHandler: function (evt, caption) {
  654. var self = this, err = evt.target.error;
  655. /** @namespace err.NOT_FOUND_ERR */
  656. /** @namespace err.SECURITY_ERR */
  657. /** @namespace err.NOT_READABLE_ERR */
  658. if (err.code === err.NOT_FOUND_ERR) {
  659. self._showError(self.msgFileNotFound.replace('{name}', caption));
  660. } else if (err.code === err.SECURITY_ERR) {
  661. self._showError(self.msgFileSecured.replace('{name}', caption));
  662. } else if (err.code === err.NOT_READABLE_ERR) {
  663. self._showError(self.msgFileNotReadable.replace('{name}', caption));
  664. } else if (err.code === err.ABORT_ERR) {
  665. self._showError(self.msgFilePreviewAborted.replace('{name}', caption));
  666. } else {
  667. self._showError(self.msgFilePreviewError.replace('{name}', caption));
  668. }
  669. },
  670. _addError: function (msg) {
  671. var self = this, $error = self.$errorContainer;
  672. if (msg && $error.length) {
  673. $error.html(self.errorCloseButton + msg);
  674. handler($error.find('.kv-error-close'), 'click', function () {
  675. $error.fadeOut('slow');
  676. });
  677. }
  678. },
  679. _resetErrors: function (fade) {
  680. var self = this, $error = self.$errorContainer;
  681. self.isError = false;
  682. self.$container.removeClass('has-error');
  683. $error.html('');
  684. if (fade) {
  685. $error.fadeOut('slow');
  686. } else {
  687. $error.hide();
  688. }
  689. },
  690. _showFolderError: function (folders) {
  691. var self = this, $error = self.$errorContainer, msg;
  692. if (!folders) {
  693. return;
  694. }
  695. msg = self.msgFoldersNotAllowed.replace(/\{n}/g, folders);
  696. self._addError(msg);
  697. addCss(self.$container, 'has-error');
  698. $error.fadeIn(800);
  699. self._raise('filefoldererror', [folders, msg]);
  700. },
  701. _showUploadError: function (msg, params, event) {
  702. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror', e = params && params.id ?
  703. '<li data-file-id="' + params.id + '">' + msg + '</li>' : '<li>' + msg + '</li>';
  704. if ($error.find('ul').length === 0) {
  705. self._addError('<ul>' + e + '</ul>');
  706. } else {
  707. $error.find('ul').append(e);
  708. }
  709. $error.fadeIn(800);
  710. self._raise(ev, [params, msg]);
  711. self.$container.removeClass('file-input-new');
  712. addCss(self.$container, 'has-error');
  713. return true;
  714. },
  715. _showError: function (msg, params, event) {
  716. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  717. params = params || {};
  718. params.reader = self.reader;
  719. self._addError(msg);
  720. $error.fadeIn(800);
  721. self._raise(ev, [params, msg]);
  722. if (!self.isUploadable) {
  723. self._clearFileInput();
  724. }
  725. self.$container.removeClass('file-input-new');
  726. addCss(self.$container, 'has-error');
  727. self.$btnUpload.attr('disabled', true);
  728. return true;
  729. },
  730. _noFilesError: function (params) {
  731. var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle,
  732. msg = self.msgFilesTooLess.replace('{n}', self.minFileCount).replace('{files}', label),
  733. $error = self.$errorContainer;
  734. self._addError(msg);
  735. self.isError = true;
  736. self._updateFileDetails(0);
  737. $error.fadeIn(800);
  738. self._raise('fileerror', [params, msg]);
  739. self._clearFileInput();
  740. addCss(self.$container, 'has-error');
  741. },
  742. _parseError: function (jqXHR, errorThrown, fileName) {
  743. /** @namespace jqXHR.responseJSON */
  744. var self = this, errMsg = $.trim(errorThrown + ''),
  745. dot = errMsg.slice(-1) === '.' ? '' : '.',
  746. text = jqXHR.responseJSON !== undefined && jqXHR.responseJSON.error !== undefined ?
  747. jqXHR.responseJSON.error : jqXHR.responseText;
  748. if (self.cancelling && self.msgUploadAborted) {
  749. errMsg = self.msgUploadAborted;
  750. }
  751. if (self.showAjaxErrorDetails && text) {
  752. text = $.trim(text.replace(/\n\s*\n/g, '\n'));
  753. text = text.length > 0 ? '<pre>' + text + '</pre>' : '';
  754. errMsg += dot + text;
  755. } else {
  756. errMsg += dot;
  757. }
  758. self.cancelling = false;
  759. return fileName ? '<b>' + fileName + ': </b>' + errMsg : errMsg;
  760. },
  761. _parseFileType: function (file) {
  762. var self = this, isValid, vType, cat, i;
  763. for (i = 0; i < defaultPreviewTypes.length; i += 1) {
  764. cat = defaultPreviewTypes[i];
  765. isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  766. vType = isValid(file.type, file.name) ? cat : '';
  767. if (!isEmpty(vType)) {
  768. return vType;
  769. }
  770. }
  771. return 'other';
  772. },
  773. _parseFilePreviewIcon: function (content, fname) {
  774. var self = this, ext, icn = self.previewFileIcon;
  775. if (fname && fname.indexOf('.') > -1) {
  776. ext = fname.split('.').pop();
  777. if (self.previewFileIconSettings && self.previewFileIconSettings[ext]) {
  778. icn = self.previewFileIconSettings[ext];
  779. }
  780. if (self.previewFileExtSettings) {
  781. $.each(self.previewFileExtSettings, function (key, func) {
  782. if (self.previewFileIconSettings[key] && func(ext)) {
  783. icn = self.previewFileIconSettings[key];
  784. }
  785. });
  786. }
  787. }
  788. if (content.indexOf('{previewFileIcon}') > -1) {
  789. return content.replace(/\{previewFileIconClass}/g, self.previewFileIconClass).replace(
  790. /\{previewFileIcon}/g, icn);
  791. }
  792. return content;
  793. },
  794. _raise: function (event, params) {
  795. var self = this, e = $.Event(event);
  796. if (params !== undefined) {
  797. self.$element.trigger(e, params);
  798. } else {
  799. self.$element.trigger(e);
  800. }
  801. if (e.isDefaultPrevented()) {
  802. return false;
  803. }
  804. if (!e.result) {
  805. return e.result;
  806. }
  807. switch (event) {
  808. // ignore these events
  809. case 'filebatchuploadcomplete':
  810. case 'filebatchuploadsuccess':
  811. case 'fileuploaded':
  812. case 'fileclear':
  813. case 'filecleared':
  814. case 'filereset':
  815. case 'fileerror':
  816. case 'filefoldererror':
  817. case 'fileuploaderror':
  818. case 'filebatchuploaderror':
  819. case 'filedeleteerror':
  820. case 'filecustomerror':
  821. case 'filesuccessremove':
  822. break;
  823. // receive data response via `filecustomerror` event`
  824. default:
  825. self.ajaxAborted = e.result;
  826. break;
  827. }
  828. return true;
  829. },
  830. _listen: function () {
  831. var self = this, $el = self.$element, $form = $el.closest('form'), $cont = self.$container;
  832. handler($el, 'change', $.proxy(self._change, self));
  833. handler(self.$btnFile, 'click', $.proxy(self._browse, self));
  834. handler($form, 'reset', $.proxy(self.reset, self));
  835. handler($cont.find('.fileinput-remove:not([disabled])'), 'click', $.proxy(self.clear, self));
  836. handler($cont.find('.fileinput-cancel'), 'click', $.proxy(self.cancel, self));
  837. self._initDragDrop();
  838. if (!self.isUploadable) {
  839. handler($form, 'submit', $.proxy(self._submitForm, self));
  840. }
  841. handler(self.$container.find('.fileinput-upload'), 'click', $.proxy(self._uploadClick, self));
  842. },
  843. _initDragDrop: function () {
  844. var self = this, $zone = self.$dropZone;
  845. if (self.isUploadable && self.dropZoneEnabled && self.showPreview) {
  846. handler($zone, 'dragenter dragover', $.proxy(self._zoneDragEnter, self));
  847. handler($zone, 'dragleave', $.proxy(self._zoneDragLeave, self));
  848. handler($zone, 'drop', $.proxy(self._zoneDrop, self));
  849. handler($(document), 'dragenter dragover drop', self._zoneDragDropInit);
  850. }
  851. },
  852. _zoneDragDropInit: function (e) {
  853. e.stopPropagation();
  854. e.preventDefault();
  855. },
  856. _zoneDragEnter: function (e) {
  857. var self = this, hasFiles = $.inArray('Files', e.originalEvent.dataTransfer.types) > -1;
  858. self._zoneDragDropInit(e);
  859. if (self.isDisabled || !hasFiles) {
  860. e.originalEvent.dataTransfer.effectAllowed = 'none';
  861. e.originalEvent.dataTransfer.dropEffect = 'none';
  862. return;
  863. }
  864. addCss(self.$dropZone, 'file-highlighted');
  865. },
  866. _zoneDragLeave: function (e) {
  867. var self = this;
  868. self._zoneDragDropInit(e);
  869. if (self.isDisabled) {
  870. return;
  871. }
  872. self.$dropZone.removeClass('file-highlighted');
  873. },
  874. _zoneDrop: function (e) {
  875. var self = this;
  876. e.preventDefault();
  877. /** @namespace e.originalEvent.dataTransfer */
  878. if (self.isDisabled || isEmpty(e.originalEvent.dataTransfer.files)) {
  879. return;
  880. }
  881. self._change(e, 'dragdrop');
  882. self.$dropZone.removeClass('file-highlighted');
  883. },
  884. _uploadClick: function (e) {
  885. var self = this, $btn = self.$container.find('.fileinput-upload'), $form,
  886. isEnabled = !$btn.hasClass('disabled') && isEmpty($btn.attr('disabled'));
  887. if (e && e.isDefaultPrevented()) {
  888. return;
  889. }
  890. if (!self.isUploadable) {
  891. if (isEnabled && $btn.attr('type') !== 'submit') {
  892. $form = $btn.closest('form');
  893. // downgrade to normal form submit if possible
  894. if ($form.length) {
  895. $form.trigger('submit');
  896. }
  897. e.preventDefault();
  898. }
  899. return;
  900. }
  901. e.preventDefault();
  902. if (isEnabled) {
  903. self.upload();
  904. }
  905. },
  906. _submitForm: function () {
  907. var self = this, $el = self.$element, files = $el.get(0).files;
  908. if (files && self.minFileCount > 0 && self._getFileCount(files.length) < self.minFileCount) {
  909. self._noFilesError({});
  910. return false;
  911. }
  912. return !self._abort({});
  913. },
  914. _clearPreview: function () {
  915. var self = this, $thumbs = !self.showUploadedThumbs ? self.$preview.find('.file-preview-frame') :
  916. self.$preview.find('.file-preview-frame:not(.file-preview-success)');
  917. $thumbs.remove();
  918. if (!self.$preview.find('.file-preview-frame').length || !self.showPreview) {
  919. self._resetUpload();
  920. }
  921. self._validateDefaultPreview();
  922. },
  923. _initPreview: function (isInit) {
  924. var self = this, cap = self.initialCaption || '', out;
  925. if (!previewCache.count(self.id)) {
  926. self._clearPreview();
  927. if (isInit) {
  928. self._setCaption(cap);
  929. } else {
  930. self._initCaption();
  931. }
  932. return;
  933. }
  934. out = previewCache.out(self.id);
  935. cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
  936. self.$preview.html(out.content);
  937. self._setCaption(cap);
  938. if (!isEmpty(out.content)) {
  939. self.$container.removeClass('file-input-new');
  940. }
  941. },
  942. _initPreviewDeletes: function () {
  943. var self = this, deleteExtraData = self.deleteExtraData || {},
  944. resetProgress = function () {
  945. var hasFiles = self.isUploadable ? previewCache.count(self.id) : self.$element.get(0).files.length;
  946. if (self.$preview.find('.kv-file-remove').length === 0 && !hasFiles) {
  947. self.reset();
  948. self.initialCaption = '';
  949. }
  950. };
  951. self.$preview.find('.kv-file-remove').each(function () {
  952. var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key');
  953. if (isEmpty(vUrl) || vKey === undefined) {
  954. return;
  955. }
  956. var $frame = $el.closest('.file-preview-frame'), cache = previewCache.data[self.id],
  957. settings, params, index = $frame.data('fileindex'), config, extraData;
  958. index = parseInt(index.replace('init_', ''));
  959. config = isEmpty(cache.config) && isEmpty(cache.config[index]) ? null : cache.config[index];
  960. extraData = isEmpty(config) || isEmpty(config.extra) ? deleteExtraData : config.extra;
  961. if (typeof extraData === "function") {
  962. extraData = extraData();
  963. }
  964. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  965. settings = $.extend(true, {}, {
  966. url: vUrl,
  967. type: 'POST',
  968. dataType: 'json',
  969. data: $.extend(true, {}, {key: vKey}, extraData),
  970. beforeSend: function (jqXHR) {
  971. self.ajaxAborted = false;
  972. self._raise('filepredelete', [vKey, jqXHR, extraData]);
  973. if (self.ajaxAborted) {
  974. jqXHR.abort();
  975. } else {
  976. addCss($frame, 'file-uploading');
  977. addCss($el, 'disabled');
  978. }
  979. },
  980. success: function (data, textStatus, jqXHR) {
  981. var n, cap;
  982. if (isEmpty(data) || isEmpty(data.error)) {
  983. previewCache.unset(self.id, index);
  984. n = previewCache.count(self.id);
  985. cap = n > 0 ? self._getMsgSelected(n) : '';
  986. self._raise('filedeleted', [vKey, jqXHR, extraData]);
  987. self._setCaption(cap);
  988. } else {
  989. params.jqXHR = jqXHR;
  990. params.response = data;
  991. self._showError(data.error, params, 'filedeleteerror');
  992. $frame.removeClass('file-uploading');
  993. $el.removeClass('disabled');
  994. resetProgress();
  995. return;
  996. }
  997. $frame.removeClass('file-uploading').addClass('file-deleted');
  998. $frame.fadeOut('slow', function () {
  999. self._clearObjects($frame);
  1000. $frame.remove();
  1001. resetProgress();
  1002. if (!n && self.getFileStack().length === 0) {
  1003. self._setCaption('');
  1004. self.reset();
  1005. }
  1006. });
  1007. },
  1008. error: function (jqXHR, textStatus, errorThrown) {
  1009. var errMsg = self._parseError(jqXHR, errorThrown);
  1010. params.jqXHR = jqXHR;
  1011. params.response = {};
  1012. self._showError(errMsg, params, 'filedeleteerror');
  1013. $frame.removeClass('file-uploading');
  1014. resetProgress();
  1015. }
  1016. }, self.ajaxDeleteSettings);
  1017. handler($el, 'click', function () {
  1018. if (!self._validateMinCount()) {
  1019. return false;
  1020. }
  1021. $.ajax(settings);
  1022. });
  1023. });
  1024. },
  1025. _clearObjects: function ($el) {
  1026. $el.find('video audio').each(function () {
  1027. this.pause();
  1028. $(this).remove();
  1029. });
  1030. $el.find('img object div').each(function () {
  1031. $(this).remove();
  1032. });
  1033. },
  1034. _clearFileInput: function () {
  1035. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  1036. if (isEmpty($el.val())) {
  1037. return;
  1038. }
  1039. // Fix for IE ver < 11, that does not clear file inputs. Requires a sequence of steps to prevent IE
  1040. // crashing but still allow clearing of the file input.
  1041. if (self.isIE9 || self.isIE10) {
  1042. $srcFrm = $el.closest('form');
  1043. $tmpFrm = $(document.createElement('form'));
  1044. $tmpEl = $(document.createElement('div'));
  1045. $el.before($tmpEl);
  1046. if ($srcFrm.length) {
  1047. $srcFrm.after($tmpFrm);
  1048. } else {
  1049. $tmpEl.after($tmpFrm);
  1050. }
  1051. $tmpFrm.append($el).trigger('reset');
  1052. $tmpEl.before($el).remove();
  1053. $tmpFrm.remove();
  1054. } else { // normal input clear behavior for other sane browsers
  1055. $el.val('');
  1056. }
  1057. self.fileInputCleared = true;
  1058. },
  1059. _resetUpload: function () {
  1060. var self = this;
  1061. self.uploadCache = {content: [], config: [], tags: [], append: true};
  1062. self.uploadCount = 0;
  1063. self.uploadStatus = {};
  1064. self.uploadLog = [];
  1065. self.uploadAsyncCount = 0;
  1066. self.loadedImages = [];
  1067. self.totalImagesCount = 0;
  1068. self.$btnUpload.removeAttr('disabled');
  1069. self._setProgress(0);
  1070. addCss(self.$progress, 'hide');
  1071. self._resetErrors(false);
  1072. self.ajaxAborted = false;
  1073. self.ajaxRequests = [];
  1074. self._resetCanvas();
  1075. },
  1076. _resetCanvas: function () {
  1077. var self = this;
  1078. if (self.canvas && self.imageCanvasContext) {
  1079. self.imageCanvasContext.clearRect(0, 0, self.canvas.width, self.canvas.height);
  1080. }
  1081. },
  1082. _hasInitialPreview: function () {
  1083. var self = this;
  1084. return !self.overwriteInitial && previewCache.count(self.id);
  1085. },
  1086. _resetPreview: function () {
  1087. var self = this, out, cap;
  1088. if (previewCache.count(self.id)) {
  1089. out = previewCache.out(self.id);
  1090. self.$preview.html(out.content);
  1091. cap = self.initialCaption ? self.initialCaption : out.caption;
  1092. self._setCaption(cap);
  1093. } else {
  1094. self._clearPreview();
  1095. self._initCaption();
  1096. }
  1097. },
  1098. _clearDefaultPreview: function () {
  1099. var self = this;
  1100. self.$preview.find('.file-default-preview').remove();
  1101. },
  1102. _validateDefaultPreview: function () {
  1103. var self = this;
  1104. if (!self.showPreview || isEmpty(self.defaultPreviewContent)) {
  1105. return;
  1106. }
  1107. self.$preview.html('<div class="file-default-preview">' + self.defaultPreviewContent + '</div>');
  1108. self.$container.removeClass('file-input-new');
  1109. },
  1110. _resetPreviewThumbs: function (isAjax) {
  1111. var self = this, out;
  1112. if (isAjax) {
  1113. self._clearPreview();
  1114. self.clearStack();
  1115. return;
  1116. }
  1117. if (self._hasInitialPreview()) {
  1118. out = previewCache.out(self.id);
  1119. self.$preview.html(out.content);
  1120. self._setCaption(out.caption);
  1121. self._initPreviewDeletes();
  1122. } else {
  1123. self._clearPreview();
  1124. }
  1125. },
  1126. _getLayoutTemplate: function (t) {
  1127. var self = this,
  1128. template = isSet(t, self.layoutTemplates) ? self.layoutTemplates[t] : defaultLayoutTemplates[t];
  1129. if (isEmpty(self.customLayoutTags)) {
  1130. return template;
  1131. }
  1132. return replaceTags(template, self.customLayoutTags);
  1133. },
  1134. _getPreviewTemplate: function (t) {
  1135. var self = this,
  1136. template = isSet(t, self.previewTemplates) ? self.previewTemplates[t] : defaultPreviewTemplates[t];
  1137. if (isEmpty(self.customPreviewTags)) {
  1138. return template;
  1139. }
  1140. return replaceTags(template, self.customPreviewTags);
  1141. },
  1142. _getOutData: function (jqXHR, responseData, filesData) {
  1143. var self = this;
  1144. jqXHR = jqXHR || {};
  1145. responseData = responseData || {};
  1146. filesData = filesData || self.filestack.slice(0) || {};
  1147. return {
  1148. form: self.formdata,
  1149. files: filesData,
  1150. filenames: self.filenames,
  1151. extra: self._getExtraData(),
  1152. response: responseData,
  1153. reader: self.reader,
  1154. jqXHR: jqXHR
  1155. };
  1156. },
  1157. _getMsgSelected: function (n) {
  1158. var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural;
  1159. return self.msgSelected.replace('{n}', n).replace('{files}', strFiles);
  1160. },
  1161. _getThumbs: function (css) {
  1162. css = css || '';
  1163. return this.$preview.find('.file-preview-frame:not(.file-preview-initial)' + css);
  1164. },
  1165. _getExtraData: function (previewId, index) {
  1166. var self = this, data = self.uploadExtraData;
  1167. if (typeof self.uploadExtraData === "function") {
  1168. data = self.uploadExtraData(previewId, index);
  1169. }
  1170. return data;
  1171. },
  1172. _initXhr: function (xhrobj, previewId, fileCount) {
  1173. var self = this;
  1174. if (xhrobj.upload) {
  1175. xhrobj.upload.addEventListener('progress', function (event) {
  1176. var pct = 0, position = event.loaded || event.position, total = event.total;
  1177. /** @namespace event.lengthComputable */
  1178. if (event.lengthComputable) {
  1179. pct = Math.ceil(position / total * 100);
  1180. }
  1181. if (previewId) {
  1182. self._setAsyncUploadStatus(previewId, pct, fileCount);
  1183. } else {
  1184. self._setProgress(Math.ceil(pct));
  1185. }
  1186. }, false);
  1187. }
  1188. return xhrobj;
  1189. },
  1190. _ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, previewId, index) {
  1191. var self = this, settings;
  1192. self._raise('filepreajax', [previewId, index]);
  1193. self._uploadExtra(previewId, index);
  1194. settings = $.extend(true, {}, {
  1195. xhr: function () {
  1196. var xhrobj = $.ajaxSettings.xhr();
  1197. return self._initXhr(xhrobj, previewId, self.getFileStack().length);
  1198. },
  1199. url: self.uploadUrl,
  1200. type: 'POST',
  1201. dataType: 'json',
  1202. data: self.formdata,
  1203. cache: false,
  1204. processData: false,
  1205. contentType: false,
  1206. beforeSend: fnBefore,
  1207. success: fnSuccess,
  1208. complete: fnComplete,
  1209. error: fnError
  1210. }, self.ajaxSettings);
  1211. self.ajaxRequests.push($.ajax(settings));
  1212. },
  1213. _initUploadSuccess: function (out, $thumb, allFiles) {
  1214. var self = this, append, data, index, $newThumb, content, config, tags, i;
  1215. if (!self.showPreview || typeof out !== 'object' || $.isEmptyObject(out)) {
  1216. return;
  1217. }
  1218. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  1219. self.hasInitData = true;
  1220. content = out.initialPreview || [];
  1221. config = out.initialPreviewConfig || [];
  1222. tags = out.initialPreviewThumbTags || [];
  1223. append = out.append === undefined || out.append ? true : false;
  1224. self.overwriteInitial = false;
  1225. if ($thumb !== undefined) {
  1226. if (!allFiles) {
  1227. index = previewCache.add(self.id, content, config[0], tags[0], append);
  1228. data = previewCache.get(self.id, index, false);
  1229. $newThumb = $(data).hide();
  1230. $thumb.after($newThumb).fadeOut('slow', function () {
  1231. $newThumb.fadeIn('slow').css('display:inline-block');
  1232. self._initPreviewDeletes();
  1233. self._clearFileInput();
  1234. $thumb.remove();
  1235. });
  1236. } else {
  1237. i = $thumb.attr('data-fileindex');
  1238. self.uploadCache.content[i] = content[0];
  1239. self.uploadCache.config[i] = config[0];
  1240. self.uploadCache.tags[i] = tags[0];
  1241. self.uploadCache.append = append;
  1242. }
  1243. } else {
  1244. previewCache.set(self.id, content, config, tags, append);
  1245. self._initPreview();
  1246. self._initPreviewDeletes();
  1247. }
  1248. }
  1249. },
  1250. _initSuccessThumbs: function () {
  1251. var self = this;
  1252. if (!self.showPreview) {
  1253. return;
  1254. }
  1255. self._getThumbs('.file-preview-success').each(function () {
  1256. var $thumb = $(this), $remove = $thumb.find('.kv-file-remove');
  1257. $remove.removeAttr('disabled');
  1258. handler($remove, 'click', function () {
  1259. var out = self._raise('filesuccessremove', [$thumb.attr('id'), $thumb.data('fileindex')]);
  1260. cleanMemory($thumb);
  1261. if (out === false) {
  1262. return;
  1263. }
  1264. $thumb.fadeOut('slow', function () {
  1265. $thumb.remove();
  1266. if (!self.$preview.find('.file-preview-frame').length) {
  1267. self.reset();
  1268. }
  1269. });
  1270. });
  1271. });
  1272. },
  1273. _checkAsyncComplete: function () {
  1274. var self = this, previewId, i;
  1275. for (i = 0; i < self.filestack.length; i++) {
  1276. if (self.filestack[i]) {
  1277. previewId = self.previewInitId + "-" + i;
  1278. if ($.inArray(previewId, self.uploadLog) === -1) {
  1279. return false;
  1280. }
  1281. }
  1282. }
  1283. return (self.uploadAsyncCount === self.uploadLog.length);
  1284. },
  1285. _uploadExtra: function (previewId, index) {
  1286. var self = this, data = self._getExtraData(previewId, index);
  1287. if (data.length === 0) {
  1288. return;
  1289. }
  1290. $.each(data, function (key, value) {
  1291. self.formdata.append(key, value);
  1292. });
  1293. },
  1294. _uploadSingle: function (i, files, allFiles) {
  1295. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  1296. previewId = self.previewInitId + "-" + i, $thumb, chkComplete, $btnUpload, $btnDelete,
  1297. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1298. fnBefore, fnSuccess, fnComplete, fnError, updateUploadLog, params = {id: previewId, index: i};
  1299. self.formdata = formdata;
  1300. if (self.showPreview) {
  1301. $thumb = $('#' + previewId + ':not(.file-preview-initial)');
  1302. $btnUpload = $thumb.find('.kv-file-upload');
  1303. $btnDelete = $thumb.find('.kv-file-remove');
  1304. $('#' + previewId).find('.file-thumb-progress').removeClass('hide');
  1305. }
  1306. if (total === 0 || !hasPostData || ($btnUpload && $btnUpload.hasClass('disabled')) || self._abort(params)) {
  1307. return;
  1308. }
  1309. updateUploadLog = function (i, previewId) {
  1310. self.updateStack(i, undefined);
  1311. self.uploadLog.push(previewId);
  1312. if (self._checkAsyncComplete()) {
  1313. self.fileBatchCompleted = true;
  1314. }
  1315. };
  1316. chkComplete = function () {
  1317. if (!self.fileBatchCompleted) {
  1318. return;
  1319. }
  1320. setTimeout(function () {
  1321. if (self.showPreview) {
  1322. previewCache.set(
  1323. self.id,
  1324. self.uploadCache.content,
  1325. self.uploadCache.config,
  1326. self.uploadCache.tags,
  1327. self.uploadCache.append
  1328. );
  1329. if (self.hasInitData) {
  1330. self._initPreview();
  1331. self._initPreviewDeletes();
  1332. }
  1333. }
  1334. self.unlock();
  1335. self._clearFileInput();
  1336. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  1337. self.uploadCount = 0;
  1338. self.uploadStatus = {};
  1339. self.uploadLog = [];
  1340. self._setProgress(100);
  1341. }, 100);
  1342. };
  1343. fnBefore = function (jqXHR) {
  1344. outData = self._getOutData(jqXHR);
  1345. self.fileBatchCompleted = false;
  1346. if (self.showPreview) {
  1347. if (!$thumb.hasClass('file-preview-success')) {
  1348. self._setThumbStatus($thumb, 'Loading');
  1349. addCss($thumb, 'file-uploading');
  1350. }
  1351. $btnUpload.attr('disabled', true);
  1352. $btnDelete.attr('disabled', true);
  1353. }
  1354. if (!allFiles) {
  1355. self.lock();
  1356. }
  1357. self._raise('filepreupload', [outData, previewId, i]);
  1358. $.extend(true, params, outData);
  1359. if (self._abort(params)) {
  1360. jqXHR.abort();
  1361. self._setProgressCancelled();
  1362. }
  1363. };
  1364. fnSuccess = function (data, textStatus, jqXHR) {
  1365. outData = self._getOutData(jqXHR, data);
  1366. $.extend(true, params, outData);
  1367. setTimeout(function () {
  1368. if (isEmpty(data) || isEmpty(data.error)) {
  1369. if (self.showPreview) {
  1370. self._setThumbStatus($thumb, 'Success');
  1371. $btnUpload.hide();
  1372. self._initUploadSuccess(data, $thumb, allFiles);
  1373. }
  1374. self._raise('fileuploaded', [outData, previewId, i]);
  1375. if (!allFiles) {
  1376. self.updateStack(i, undefined);
  1377. } else {
  1378. updateUploadLog(i, previewId);
  1379. }
  1380. } else {
  1381. self._showUploadError(data.error, params);
  1382. self._setPreviewError($thumb, i);
  1383. if (allFiles) {
  1384. updateUploadLog(i, previewId);
  1385. }
  1386. }
  1387. }, 100);
  1388. };
  1389. fnComplete = function () {
  1390. setTimeout(function () {
  1391. if (self.showPreview) {
  1392. $btnUpload.removeAttr('disabled');
  1393. $btnDelete.removeAttr('disabled');
  1394. $thumb.removeClass('file-uploading');
  1395. }
  1396. if (!allFiles) {
  1397. self.unlock(false);
  1398. self._clearFileInput();
  1399. } else {
  1400. chkComplete();
  1401. }
  1402. self._initSuccessThumbs();
  1403. }, 100);
  1404. };
  1405. fnError = function (jqXHR, textStatus, errorThrown) {
  1406. var errMsg = self._parseError(jqXHR, errorThrown, (allFiles ? files[i].name : null));
  1407. setTimeout(function () {
  1408. if (allFiles) {
  1409. updateUploadLog(i, previewId);
  1410. }
  1411. self.uploadStatus[previewId] = 100;
  1412. self._setPreviewError($thumb, i);
  1413. $.extend(true, params, self._getOutData(jqXHR));
  1414. self._showUploadError(errMsg, params);
  1415. }, 100);
  1416. };
  1417. formdata.append(self.uploadFileAttr, files[i], self.filenames[i]);
  1418. formdata.append('file_id', i);
  1419. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, previewId, i);
  1420. },
  1421. _uploadBatch: function () {
  1422. var self = this, files = self.filestack, total = files.length, params = {}, fnBefore, fnSuccess, fnError,
  1423. fnComplete, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1424. setAllUploaded;
  1425. self.formdata = new FormData();
  1426. if (total === 0 || !hasPostData || self._abort(params)) {
  1427. return;
  1428. }
  1429. setAllUploaded = function () {
  1430. $.each(files, function (key) {
  1431. self.updateStack(key, undefined);
  1432. });
  1433. self._clearFileInput();
  1434. };
  1435. fnBefore = function (jqXHR) {
  1436. self.lock();
  1437. var outData = self._getOutData(jqXHR);
  1438. if (self.showPreview) {
  1439. self._getThumbs().each(function () {
  1440. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  1441. $btnDelete = $thumb.find('.kv-file-remove');
  1442. if (!$thumb.hasClass('file-preview-success')) {
  1443. self._setThumbStatus($thumb, 'Loading');
  1444. addCss($thumb, 'file-uploading');
  1445. }
  1446. $btnUpload.attr('disabled', true);
  1447. $btnDelete.attr('disabled', true);
  1448. });
  1449. }
  1450. self._raise('filebatchpreupload', [outData]);
  1451. if (self._abort(outData)) {
  1452. jqXHR.abort();
  1453. self._setProgressCancelled();
  1454. }
  1455. };
  1456. fnSuccess = function (data, textStatus, jqXHR) {
  1457. /** @namespace data.errorkeys */
  1458. var outData = self._getOutData(jqXHR, data), $thumbs = self._getThumbs(), key = 0,
  1459. keys = isEmpty(data) || isEmpty(data.errorkeys) ? [] : data.errorkeys;
  1460. if (isEmpty(data) || isEmpty(data.error)) {
  1461. self._raise('filebatchuploadsuccess', [outData]);
  1462. setAllUploaded();
  1463. if (self.showPreview) {
  1464. $thumbs.each(function () {
  1465. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload');
  1466. $thumb.find('.kv-file-upload').hide();
  1467. self._setThumbStatus($thumb, 'Success');
  1468. $thumb.removeClass('file-uploading');
  1469. $btnUpload.removeAttr('disabled');
  1470. });
  1471. self._initUploadSuccess(data);
  1472. } else {
  1473. self.reset();
  1474. }
  1475. } else {
  1476. if (self.showPreview) {
  1477. $thumbs.each(function () {
  1478. var $thumb = $(this), $btnDelete = $thumb.find('.kv-file-remove'),
  1479. $btnUpload = $thumb.find('.kv-file-upload');
  1480. $thumb.removeClass('file-uploading');
  1481. $btnUpload.removeAttr('disabled');
  1482. $btnDelete.removeAttr('disabled');
  1483. if (keys.length === 0) {
  1484. self._setPreviewError($thumb);
  1485. return;
  1486. }
  1487. if ($.inArray(key, keys) !== -1) {
  1488. self._setPreviewError($thumb);
  1489. } else {
  1490. $thumb.find('.kv-file-upload').hide();
  1491. self._setThumbStatus($thumb, 'Success');
  1492. self.updateStack(key, undefined);
  1493. }
  1494. key++;
  1495. });
  1496. self._initUploadSuccess(data);
  1497. }
  1498. self._showUploadError(data.error, outData, 'filebatchuploaderror');
  1499. }
  1500. };
  1501. fnComplete = function () {
  1502. self._setProgress(100);
  1503. self.unlock();
  1504. self._initSuccessThumbs();
  1505. self._clearFileInput();
  1506. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  1507. };
  1508. fnError = function (jqXHR, textStatus, errorThrown) {
  1509. var outData = self._getOutData(jqXHR), errMsg = self._parseError(jqXHR, errorThrown);
  1510. self._showUploadError(errMsg, outData, 'filebatchuploaderror');
  1511. self.uploadFileCount = total - 1;
  1512. if (!self.showPreview) {
  1513. return;
  1514. }
  1515. self._getThumbs().each(function () {
  1516. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1517. $thumb.removeClass('file-uploading');
  1518. if (self.filestack[key] !== undefined) {
  1519. self._setPreviewError($thumb);
  1520. }
  1521. });
  1522. self._getThumbs().removeClass('file-uploading');
  1523. self._getThumbs(' .kv-file-upload').removeAttr('disabled');
  1524. self._getThumbs(' .kv-file-delete').removeAttr('disabled');
  1525. };
  1526. $.each(files, function (key, data) {
  1527. if (!isEmpty(files[key])) {
  1528. self.formdata.append(self.uploadFileAttr, data, self.filenames[key]);
  1529. }
  1530. });
  1531. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1532. },
  1533. _uploadExtraOnly: function () {
  1534. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  1535. self.formdata = new FormData();
  1536. if (self._abort(params)) {
  1537. return;
  1538. }
  1539. fnBefore = function (jqXHR) {
  1540. self.lock();
  1541. var outData = self._getOutData(jqXHR);
  1542. self._raise('filebatchpreupload', [outData]);
  1543. self._setProgress(50);
  1544. params.data = outData;
  1545. params.xhr = jqXHR;
  1546. if (self._abort(params)) {
  1547. jqXHR.abort();
  1548. self._setProgressCancelled();
  1549. }
  1550. };
  1551. fnSuccess = function (data, textStatus, jqXHR) {
  1552. var outData = self._getOutData(jqXHR, data);
  1553. if (isEmpty(data) || isEmpty(data.error)) {
  1554. self._raise('filebatchuploadsuccess', [outData]);
  1555. self._clearFileInput();
  1556. self._initUploadSuccess(data);
  1557. } else {
  1558. self._showUploadError(data.error, outData, 'filebatchuploaderror');
  1559. }
  1560. };
  1561. fnComplete = function () {
  1562. self._setProgress(100);
  1563. self.unlock();
  1564. self._clearFileInput();
  1565. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  1566. };
  1567. fnError = function (jqXHR, textStatus, errorThrown) {
  1568. var outData = self._getOutData(jqXHR), errMsg = self._parseError(jqXHR, errorThrown);
  1569. params.data = outData;
  1570. self._showUploadError(errMsg, outData, 'filebatchuploaderror');
  1571. };
  1572. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1573. },
  1574. _initFileActions: function () {
  1575. var self = this;
  1576. if (!self.showPreview) {
  1577. return;
  1578. }
  1579. self.$preview.find('.kv-file-remove').each(function () {
  1580. var $el = $(this), $frame = $el.closest('.file-preview-frame'), hasError,
  1581. id = $frame.attr('id'), ind = $frame.attr('data-fileindex'), n, cap, status;
  1582. handler($el, 'click', function () {
  1583. status = self._raise('filepreremove', [id, ind]);
  1584. if (status === false || !self._validateMinCount()) {
  1585. return false;
  1586. }
  1587. hasError = $frame.hasClass('file-preview-error');
  1588. cleanMemory($frame);
  1589. $frame.fadeOut('slow', function () {
  1590. self.updateStack(ind, undefined);
  1591. self._clearObjects($frame);
  1592. $frame.remove();
  1593. if (id && hasError) {
  1594. self.$errorContainer.find('li[data-file-id="' + id + '"]').fadeOut('fast', function () {
  1595. $(this).remove();
  1596. if (!self._errorsExist()) {
  1597. self._resetErrors();
  1598. }
  1599. });
  1600. }
  1601. var filestack = self.getFileStack(true), len = filestack.length, chk = previewCache.count(
  1602. self.id),
  1603. hasThumb = self.showPreview && self.$preview.find('.file-preview-frame').length;
  1604. self._clearFileInput();
  1605. if (len === 0 && chk === 0 && !hasThumb) {
  1606. self.reset();
  1607. } else {
  1608. n = chk + len;
  1609. cap = n > 1 ? self._getMsgSelected(n) : (filestack[0] ? self._getFileNames()[0] : '');
  1610. self._setCaption(cap);
  1611. }
  1612. self._raise('fileremoved', [id, ind]);
  1613. });
  1614. });
  1615. });
  1616. self.$preview.find('.kv-file-upload').each(function () {
  1617. var $el = $(this);
  1618. handler($el, 'click', function () {
  1619. var $frame = $el.closest('.file-preview-frame'),
  1620. ind = $frame.attr('data-fileindex');
  1621. if (!$frame.hasClass('file-preview-error')) {
  1622. self._uploadSingle(ind, self.filestack, false);
  1623. }
  1624. });
  1625. });
  1626. },
  1627. _hideFileIcon: function () {
  1628. if (this.overwriteInitial) {
  1629. this.$captionContainer.find('.kv-caption-icon').hide();
  1630. }
  1631. },
  1632. _showFileIcon: function () {
  1633. this.$captionContainer.find('.kv-caption-icon').show();
  1634. },
  1635. _previewDefault: function (file, previewId, isDisabled) {
  1636. if (!this.showPreview) {
  1637. return;
  1638. }
  1639. var self = this, frameClass = '', fname = file ? file.name : '',
  1640. /** @namespace objUrl.createObjectURL */
  1641. data = objUrl.createObjectURL(file), ind = previewId.slice(previewId.lastIndexOf('-') + 1),
  1642. config = self.previewSettings.other || defaultPreviewSettings.other,
  1643. footer = self._renderFileFooter(file.name, config.width),
  1644. previewOtherTemplate = self._parseFilePreviewIcon(self._getPreviewTemplate('other'), fname);
  1645. if (isDisabled === true) {
  1646. if (!self.isUploadable) {
  1647. footer += '<div class="file-other-error" title="' + self.fileActionSettings.indicatorErrorTitle +
  1648. '">' + self.fileActionSettings.indicatorError + '</div>';
  1649. }
  1650. }
  1651. self._clearDefaultPreview();
  1652. self.$preview.append("\n" + previewOtherTemplate
  1653. .replace(/\{previewId}/g, previewId)
  1654. .replace(/\{frameClass}/g, frameClass)
  1655. .replace(/\{fileindex}/g, ind)
  1656. .replace(/\{caption}/g, self.slug(file.name))
  1657. .replace(/\{width}/g, config.width)
  1658. .replace(/\{height}/g, config.height)
  1659. .replace(/\{type}/g, file.type)
  1660. .replace(/\{data}/g, data)
  1661. .replace(/\{footer}/g, footer));
  1662. if (isDisabled === true && self.isUploadable) {
  1663. self._setThumbStatus($('#' + previewId), 'Error');
  1664. }
  1665. },
  1666. _previewFile: function (i, file, theFile, previewId, data) {
  1667. if (!this.showPreview) {
  1668. return;
  1669. }
  1670. var self = this, cat = self._parseFileType(file), fname = file ? file.name : '', caption = self.slug(fname),
  1671. content, strText, types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes,
  1672. tmplt = self._getPreviewTemplate(cat), chkTypes = types && types.indexOf(cat) >= 0, id,
  1673. config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat],
  1674. chkMimes = mimes && mimes.indexOf(file.type) !== -1,
  1675. footer = self._renderFileFooter(caption, config.width), modal = '',
  1676. ind = previewId.slice(previewId.lastIndexOf('-') + 1);
  1677. if (chkTypes || chkMimes) {
  1678. tmplt = self._parseFilePreviewIcon(tmplt, fname.split('.').pop());
  1679. if (cat === 'text') {
  1680. strText = htmlEncode(theFile.target.result);
  1681. id = 'text-' + uniqId();
  1682. content = tmplt.replace(/\{zoom}/g, self._getLayoutTemplate('zoom'));
  1683. modal = self._getLayoutTemplate('modal').replace('{id}', id)
  1684. .replace(/\{title}/g, caption)
  1685. .replace(/\{body}/g, strText).replace(/\{heading}/g, self.msgZoomModalHeading);
  1686. content = content.replace(/\{previewId}/g, previewId).replace(/\{caption}/g, caption)
  1687. .replace(/\{width}/g, config.width).replace(/\{height}/g, config.height)
  1688. .replace(/\{frameClass}/g, '').replace(/\{zoomInd}/g, self.zoomIndicator)
  1689. .replace(/\{footer}/g, footer).replace(/\{fileindex}/g, ind)
  1690. .replace(/\{type}/g, file.type).replace(/\{zoomTitle}/g, self.msgZoomTitle)
  1691. .replace(/\{dialog}/g, "$('#" + id + "').modal('show')")
  1692. .replace(/\{data}/g, strText) + modal;
  1693. } else {
  1694. content = tmplt.replace(/\{previewId}/g, previewId).replace(/\{caption}/g, caption)
  1695. .replace(/\{frameClass}/g, '').replace(/\{type}/g, file.type).replace(/\{fileindex}/g, ind)
  1696. .replace(/\{width}/g, config.width).replace(/\{height}/g, config.height)
  1697. .replace(/\{footer}/g, footer).replace(/\{data}/g, data);
  1698. }
  1699. self._clearDefaultPreview();
  1700. self.$preview.append("\n" + content);
  1701. self._validateImage(i, previewId, caption, file.type);
  1702. } else {
  1703. self._previewDefault(file, previewId);
  1704. }
  1705. },
  1706. _slugDefault: function (text) {
  1707. return isEmpty(text) ? '' : String(text).replace(/[\-\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_');
  1708. },
  1709. _readFiles: function (files) {
  1710. this.reader = new FileReader();
  1711. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  1712. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  1713. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  1714. settings = self.fileTypeSettings, ctr = self.filestack.length, readFile,
  1715. throwError = function (msg, file, previewId, index) {
  1716. var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}),
  1717. p2 = {id: previewId, index: index, file: file, files: files};
  1718. self._previewDefault(file, previewId, true);
  1719. if (self.isUploadable) {
  1720. self.addToStack(undefined);
  1721. }
  1722. setTimeout(readFile(index + 1), 100);
  1723. self._initFileActions();
  1724. if (self.removeFromPreviewOnError) {
  1725. $('#' + previewId).remove();
  1726. }
  1727. return self.isUploadable ? self._showUploadError(msg, p1) : self._showError(msg, p2);
  1728. };
  1729. self.loadedImages = [];
  1730. self.totalImagesCount = 0;
  1731. $.each(files, function (key, file) {
  1732. var func = self.fileTypeSettings.image || defaultFileTypeSettings.image;
  1733. if (func && func(file.type)) {
  1734. self.totalImagesCount++;
  1735. }
  1736. });
  1737. readFile = function (i) {
  1738. if (isEmpty($el.attr('multiple'))) {
  1739. numFiles = 1;
  1740. }
  1741. if (i >= numFiles) {
  1742. if (self.isUploadable && self.filestack.length > 0) {
  1743. self._raise('filebatchselected', [self.getFileStack()]);
  1744. } else {
  1745. self._raise('filebatchselected', [files]);
  1746. }
  1747. $container.removeClass('file-thumb-loading');
  1748. $status.html('');
  1749. return;
  1750. }
  1751. var node = ctr + i, previewId = previewInitId + "-" + node, isText, file = files[i],
  1752. caption = self.slug(file.name), fileSize = (file.size || 0) / 1000, checkFile, fileExtExpr = '',
  1753. previewData = objUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk,
  1754. fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '),
  1755. fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', ');
  1756. if (!isEmpty(fileExt)) {
  1757. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  1758. }
  1759. fileSize = fileSize.toFixed(2);
  1760. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  1761. msg = self.msgSizeTooLarge.replace('{name}', caption)
  1762. .replace('{size}', fileSize)
  1763. .replace('{maxSize}', self.maxFileSize);
  1764. self.isError = throwError(msg, file, previewId, i);
  1765. return;
  1766. }
  1767. if (!isEmpty(fileTypes) && isArray(fileTypes)) {
  1768. for (j = 0; j < fileTypes.length; j += 1) {
  1769. typ = fileTypes[j];
  1770. checkFile = settings[typ];
  1771. chk = (checkFile !== undefined && checkFile(file.type, caption));
  1772. fileCount += isEmpty(chk) ? 0 : chk.length;
  1773. }
  1774. if (fileCount === 0) {
  1775. msg = self.msgInvalidFileType.replace('{name}', caption).replace('{types}', strTypes);
  1776. self.isError = throwError(msg, file, previewId, i);
  1777. return;
  1778. }
  1779. }
  1780. if (fileCount === 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) {
  1781. chk = compare(caption, fileExtExpr);
  1782. fileCount += isEmpty(chk) ? 0 : chk.length;
  1783. if (fileCount === 0) {
  1784. msg = self.msgInvalidFileExtension.replace('{name}', caption).replace('{extensions}',
  1785. strExt);
  1786. self.isError = throwError(msg, file, previewId, i);
  1787. return;
  1788. }
  1789. }
  1790. if (!self.showPreview) {
  1791. self.addToStack(file);
  1792. setTimeout(readFile(i + 1), 100);
  1793. self._raise('fileloaded', [file, previewId, i, reader]);
  1794. return;
  1795. }
  1796. if ($preview.length > 0 && FileReader !== undefined) {
  1797. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  1798. $container.addClass('file-thumb-loading');
  1799. reader.onerror = function (evt) {
  1800. self._errorHandler(evt, caption);
  1801. };
  1802. reader.onload = function (theFile) {
  1803. self._previewFile(i, file, theFile, previewId, previewData);
  1804. self._initFileActions();
  1805. };
  1806. reader.onloadend = function () {
  1807. msg = msgProgress
  1808. .replace('{index}', i + 1).replace('{files}', numFiles)
  1809. .replace('{percent}', 50).replace('{name}', caption);
  1810. setTimeout(function () {
  1811. $status.html(msg);
  1812. self._updateFileDetails(numFiles);
  1813. readFile(i + 1);
  1814. }, 100);
  1815. self._raise('fileloaded', [file, previewId, i, reader]);
  1816. };
  1817. reader.onprogress = function (data) {
  1818. if (data.lengthComputable) {
  1819. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  1820. msg = msgProgress.replace('{index}', i + 1).replace('{files}', numFiles)
  1821. .replace('{percent}', progress).replace('{name}', caption);
  1822. setTimeout(function () {
  1823. $status.html(msg);
  1824. }, 100);
  1825. }
  1826. };
  1827. isText = isSet('text', settings) ? settings.text : defaultFileTypeSettings.text;
  1828. if (isText(file.type, caption)) {
  1829. reader.readAsText(file, self.textEncoding);
  1830. } else {
  1831. reader.readAsArrayBuffer(file);
  1832. }
  1833. } else {
  1834. self._previewDefault(file, previewId);
  1835. setTimeout(function () {
  1836. readFile(i + 1);
  1837. self._updateFileDetails(numFiles);
  1838. }, 100);
  1839. self._raise('fileloaded', [file, previewId, i, reader]);
  1840. }
  1841. self.addToStack(file);
  1842. };
  1843. readFile(0);
  1844. self._updateFileDetails(numFiles, false);
  1845. },
  1846. _updateFileDetails: function (numFiles) {
  1847. var self = this, $el = self.$element, fileStack = self.getFileStack(),
  1848. name = ($el[0].files[0] && $el[0].files[0].name) || (fileStack.length && fileStack[0].name) || '',
  1849. label = self.slug(name), n = self.isUploadable ? fileStack.length : numFiles,
  1850. nFiles = previewCache.count(self.id) + n, log = n > 1 ? self._getMsgSelected(nFiles) : label;
  1851. if (self.isError) {
  1852. self.$previewContainer.removeClass('file-thumb-loading');
  1853. self.$previewStatus.html('');
  1854. self.$captionContainer.find('.kv-caption-icon').hide();
  1855. } else {
  1856. self._showFileIcon();
  1857. }
  1858. self._setCaption(log, self.isError);
  1859. self.$container.removeClass('file-input-new file-input-ajax-new');
  1860. if (arguments.length === 1) {
  1861. self._raise('fileselect', [numFiles, label]);
  1862. }
  1863. if (previewCache.count(self.id)) {
  1864. self._initPreviewDeletes();
  1865. }
  1866. },
  1867. _setThumbStatus: function ($thumb, status) {
  1868. var self = this;
  1869. if (!self.showPreview) {
  1870. return;
  1871. }
  1872. var icon = 'indicator' + status, msg = icon + 'Title',
  1873. css = 'file-preview-' + status.toLowerCase(),
  1874. $indicator = $thumb.find('.file-upload-indicator'),
  1875. config = self.fileActionSettings;
  1876. $thumb.removeClass('file-preview-success file-preview-error file-preview-loading');
  1877. if (status === 'Error') {
  1878. $thumb.find('.kv-file-upload').attr('disabled', true);
  1879. }
  1880. $indicator.html(config[icon]);
  1881. $indicator.attr('title', config[msg]);
  1882. $thumb.addClass(css);
  1883. },
  1884. _setProgressCancelled: function () {
  1885. var self = this;
  1886. self._setProgress(100, self.$progress, self.msgCancelled);
  1887. },
  1888. _setProgress: function (p, $el, error) {
  1889. var self = this, pct = Math.min(p, 100), template = pct < 100 ? self.progressTemplate :
  1890. (error ? self.progressErrorTemplate : self.progressCompleteTemplate);
  1891. $el = $el || self.$progress;
  1892. if (!isEmpty(template)) {
  1893. $el.html(template.replace(/\{percent}/g, pct));
  1894. if (error) {
  1895. $el.find('[role="progressbar"]').html(error);
  1896. }
  1897. }
  1898. },
  1899. _setFileDropZoneTitle: function () {
  1900. var self = this, $zone = self.$container.find('.file-drop-zone');
  1901. $zone.find('.' + self.dropZoneTitleClass).remove();
  1902. if (!self.isUploadable || !self.showPreview || $zone.length === 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled) {
  1903. return;
  1904. }
  1905. if ($zone.find('.file-preview-frame').length === 0 && isEmpty(self.defaultPreviewContent)) {
  1906. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + self.dropZoneTitle + '</div>');
  1907. }
  1908. self.$container.removeClass('file-input-new');
  1909. addCss(self.$container, 'file-input-ajax-new');
  1910. },
  1911. _setAsyncUploadStatus: function (previewId, pct, total) {
  1912. var self = this, sum = 0;
  1913. self._setProgress(pct, $('#' + previewId).find('.file-thumb-progress'));
  1914. self.uploadStatus[previewId] = pct;
  1915. $.each(self.uploadStatus, function (key, value) {
  1916. sum += value;
  1917. });
  1918. self._setProgress(Math.ceil(sum / total));
  1919. },
  1920. _validateMinCount: function () {
  1921. var self = this, len = self.isUploadable ? self.getFileStack().length : self.$element.get(0).files.length;
  1922. if (self.validateInitialCount && self.minFileCount > 0 && self._getFileCount(
  1923. len - 1) < self.minFileCount) {
  1924. self._noFilesError({});
  1925. return false;
  1926. }
  1927. return true;
  1928. },
  1929. _getFileCount: function (fileCount) {
  1930. var self = this, addCount = 0;
  1931. if (self.validateInitialCount && !self.overwriteInitial) {
  1932. addCount = previewCache.count(self.id);
  1933. fileCount += addCount;
  1934. }
  1935. return fileCount;
  1936. },
  1937. _getFileName: function (file) {
  1938. return file && file.name ? this.slug(file.name) : undefined;
  1939. },
  1940. _getFileNames: function (skipNull) {
  1941. var self = this;
  1942. return self.filenames.filter(function (n) {
  1943. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  1944. });
  1945. },
  1946. _setPreviewError: function ($thumb, i, val) {
  1947. var self = this;
  1948. if (i) {
  1949. self.updateStack(i, val);
  1950. }
  1951. if (self.removeFromPreviewOnError) {
  1952. $thumb.remove();
  1953. } else {
  1954. self._setThumbStatus($thumb, 'Error');
  1955. }
  1956. },
  1957. _checkDimensions: function (i, chk, $img, $thumb, fname, type, params) {
  1958. var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max', limit = self[tag + 'Image' + type],
  1959. $imgEl, isValid;
  1960. if (isEmpty(limit) || !$img.length) {
  1961. return;
  1962. }
  1963. $imgEl = $img[0];
  1964. dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height;
  1965. isValid = chk === 'Small' ? dim >= limit : dim <= limit;
  1966. if (isValid) {
  1967. return;
  1968. }
  1969. msg = self['msgImage' + type + chk].replace('{name}', fname).replace('{size}', limit);
  1970. self._showUploadError(msg, params);
  1971. self._setPreviewError($thumb, i, null);
  1972. },
  1973. _validateImage: function (i, previewId, fname, ftype) {
  1974. var self = this, $preview = self.$preview, params, w1, w2,
  1975. $thumb = $preview.find("#" + previewId), $img = $thumb.find('img');
  1976. fname = fname || 'Untitled';
  1977. if (!$img.length) {
  1978. return;
  1979. }
  1980. handler($img, 'load', function () {
  1981. w1 = $thumb.width();
  1982. w2 = $preview.width();
  1983. if (w1 > w2) {
  1984. $img.css('width', '100%');
  1985. $thumb.css('width', '97%');
  1986. }
  1987. params = {ind: i, id: previewId};
  1988. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
  1989. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
  1990. if (!self.resizeImage) {
  1991. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
  1992. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
  1993. }
  1994. self._raise('fileimageloaded', [previewId]);
  1995. self.loadedImages.push({ind: i, img: $img, thumb: $thumb, pid: previewId, typ: ftype});
  1996. self._validateAllImages();
  1997. objUrl.revokeObjectURL($img.attr('src'));
  1998. });
  1999. },
  2000. _validateAllImages: function () {
  2001. var self = this, i, config, $img, $thumb, pid, ind, params = {}, errFunc;
  2002. if (self.loadedImages.length !== self.totalImagesCount) {
  2003. return;
  2004. }
  2005. self._raise('fileimagesloaded');
  2006. if (!self.resizeImage) {
  2007. return;
  2008. }
  2009. errFunc = self.isUploadable ? self._showUploadError : self._showError;
  2010. for (i = 0; i < self.loadedImages.length; i++) {
  2011. config = self.loadedImages[i];
  2012. $img = config.img;
  2013. $thumb = config.thumb;
  2014. pid = config.pid;
  2015. ind = config.ind;
  2016. params = {id: pid, 'index': ind};
  2017. if (!self._getResizedImage($img[0], config.typ, pid, ind)) {
  2018. errFunc(self.msgImageResizeError, params, 'fileimageresizeerror');
  2019. self._setPreviewError($thumb, ind);
  2020. }
  2021. }
  2022. self._raise('fileimagesresized');
  2023. },
  2024. _getResizedImage: function (image, type, pid, ind) {
  2025. var self = this, width = image.naturalWidth, height = image.naturalHeight, ratio = 1,
  2026. maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height,
  2027. isValidImage = (width && height), chkWidth, chkHeight,
  2028. canvas = self.imageCanvas, context = self.imageCanvasContext;
  2029. if (!isValidImage) {
  2030. return false;
  2031. }
  2032. if (width === maxWidth && height === maxHeight) {
  2033. return true;
  2034. }
  2035. type = type || self.resizeDefaultImageType;
  2036. chkWidth = width > maxWidth;
  2037. chkHeight = height > maxHeight;
  2038. if (self.resizePreference === 'width') {
  2039. ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1);
  2040. } else {
  2041. ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1);
  2042. }
  2043. self._resetCanvas();
  2044. width *= ratio;
  2045. height *= ratio;
  2046. canvas.width = width;
  2047. canvas.height = height;
  2048. try {
  2049. context.drawImage(image, 0, 0, width, height);
  2050. canvas.toBlob(function (blob) {
  2051. self._raise('fileimageresized', [pid, ind]);
  2052. self.filestack[ind] = blob;
  2053. }, type, self.resizeQuality);
  2054. return true;
  2055. }
  2056. catch (err) {
  2057. return false;
  2058. }
  2059. },
  2060. _initBrowse: function ($container) {
  2061. var self = this;
  2062. self.$btnFile = $container.find('.btn-file');
  2063. self.$btnFile.append(self.$element);
  2064. },
  2065. _initCaption: function () {
  2066. var self = this, cap = self.initialCaption || '';
  2067. if (self.overwriteInitial || isEmpty(cap)) {
  2068. self.$caption.html('');
  2069. return false;
  2070. }
  2071. self._setCaption(cap);
  2072. return true;
  2073. },
  2074. _setCaption: function (content, isError) {
  2075. var self = this, title, out, n, cap, stack = self.getFileStack();
  2076. if (!self.$caption.length) {
  2077. return;
  2078. }
  2079. if (isError) {
  2080. title = $('<div>' + self.msgValidationError + '</div>').text();
  2081. n = stack.length;
  2082. if (n) {
  2083. cap = n === 1 && stack[0] ? self._getFileNames()[0] : self._getMsgSelected(n);
  2084. } else {
  2085. cap = self._getMsgSelected(self.msgNo);
  2086. }
  2087. out = '<span class="' + self.msgValidationErrorClass + '">' + self.msgValidationErrorIcon +
  2088. (isEmpty(content) ? cap : content) + '</span>';
  2089. } else {
  2090. if (isEmpty(content)) {
  2091. return;
  2092. }
  2093. title = $('<div>' + content + '</div>').text();
  2094. out = self._getLayoutTemplate('icon') + title;
  2095. }
  2096. self.$caption.html(out);
  2097. self.$caption.attr('title', title);
  2098. self.$captionContainer.find('.file-caption-ellipsis').attr('title', title);
  2099. },
  2100. _createContainer: function () {
  2101. var self = this,
  2102. $container = $(document.createElement("div"))
  2103. .attr({"class": 'file-input file-input-new'})
  2104. .html(self._renderMain());
  2105. self.$element.before($container);
  2106. self._initBrowse($container);
  2107. return $container;
  2108. },
  2109. _refreshContainer: function () {
  2110. var self = this, $container = self.$container;
  2111. $container.before(self.$element);
  2112. $container.html(self._renderMain());
  2113. self._initBrowse($container);
  2114. },
  2115. _renderMain: function () {
  2116. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : 'file-drop-disabled',
  2117. close = !self.showClose ? '' : self._getLayoutTemplate('close'),
  2118. preview = !self.showPreview ? '' : self._getLayoutTemplate('preview')
  2119. .replace(/\{class}/g, self.previewClass)
  2120. .replace(/\{dropClass}/g, dropCss),
  2121. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  2122. caption = self.captionTemplate.replace(/\{class}/g, css + ' kv-fileinput-caption');
  2123. return self.mainTemplate.replace(/\{class}/g, self.mainClass)
  2124. .replace(/\{preview}/g, preview)
  2125. .replace(/\{close}/g, close)
  2126. .replace(/\{caption}/g, caption)
  2127. .replace(/\{upload}/g, self._renderButton('upload'))
  2128. .replace(/\{remove}/g, self._renderButton('remove'))
  2129. .replace(/\{cancel}/g, self._renderButton('cancel'))
  2130. .replace(/\{browse}/g, self._renderButton('browse'));
  2131. },
  2132. _renderButton: function (type) {
  2133. var self = this, tmplt = self._getLayoutTemplate('btnDefault'), css = self[type + 'Class'],
  2134. title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'],
  2135. status = self.isDisabled ? ' disabled' : '', btnType = 'button';
  2136. switch (type) {
  2137. case 'remove':
  2138. if (!self.showRemove) {
  2139. return '';
  2140. }
  2141. break;
  2142. case 'cancel':
  2143. if (!self.showCancel) {
  2144. return '';
  2145. }
  2146. css += ' hide';
  2147. break;
  2148. case 'upload':
  2149. if (!self.showUpload) {
  2150. return '';
  2151. }
  2152. if (self.isUploadable && !self.isDisabled) {
  2153. tmplt = self._getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl);
  2154. } else {
  2155. btnType = 'submit';
  2156. }
  2157. break;
  2158. case 'browse':
  2159. tmplt = self._getLayoutTemplate('btnBrowse');
  2160. break;
  2161. default:
  2162. return '';
  2163. }
  2164. css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button';
  2165. if (!isEmpty(label)) {
  2166. label = ' <span class="' + self.buttonLabelClass + '">' + label + '</span>';
  2167. }
  2168. return tmplt.replace('{type}', btnType)
  2169. .replace('{css}', css)
  2170. .replace('{title}', title)
  2171. .replace('{status}', status)
  2172. .replace('{icon}', icon)
  2173. .replace('{label}', label);
  2174. },
  2175. _renderThumbProgress: function () {
  2176. return '<div class="file-thumb-progress hide">' + this.progressTemplate.replace(/\{percent}/g,
  2177. '0') + '</div>';
  2178. },
  2179. _renderFileFooter: function (caption, width) {
  2180. var self = this, config = self.fileActionSettings, footer, out, template = self._getLayoutTemplate(
  2181. 'footer');
  2182. if (self.isUploadable) {
  2183. footer = template.replace(/\{actions}/g, self._renderFileActions(true, true, false, false, false));
  2184. out = footer.replace(/\{caption}/g, caption)
  2185. .replace(/\{width}/g, width)
  2186. .replace(/\{progress}/g, self._renderThumbProgress())
  2187. .replace(/\{indicator}/g, config.indicatorNew)
  2188. .replace(/\{indicatorTitle}/g, config.indicatorNewTitle);
  2189. } else {
  2190. out = template.replace(/\{actions}/g, '')
  2191. .replace(/\{caption}/g, caption)
  2192. .replace(/\{progress}/g, '')
  2193. .replace(/\{width}/g, width)
  2194. .replace(/\{indicator}/g, '')
  2195. .replace(/\{indicatorTitle}/g, '');
  2196. }
  2197. out = replaceTags(out, self.previewThumbTags);
  2198. return out;
  2199. },
  2200. _renderFileActions: function (showUpload, showDelete, disabled, url, key) {
  2201. if (!showUpload && !showDelete) {
  2202. return '';
  2203. }
  2204. var self = this,
  2205. vUrl = url === false ? '' : ' data-url="' + url + '"',
  2206. vKey = key === false ? '' : ' data-key="' + key + '"',
  2207. btnDelete = self._getLayoutTemplate('actionDelete'),
  2208. btnUpload = '',
  2209. template = self._getLayoutTemplate('actions'),
  2210. otherButtons = self.otherActionButtons.replace(/\{dataKey}/g, vKey),
  2211. config = self.fileActionSettings,
  2212. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  2213. btnDelete = btnDelete
  2214. .replace(/\{removeClass}/g, removeClass)
  2215. .replace(/\{removeIcon}/g, config.removeIcon)
  2216. .replace(/\{removeTitle}/g, config.removeTitle)
  2217. .replace(/\{dataUrl}/g, vUrl)
  2218. .replace(/\{dataKey}/g, vKey);
  2219. if (showUpload) {
  2220. btnUpload = self._getLayoutTemplate('actionUpload')
  2221. .replace(/\{uploadClass}/g, config.uploadClass)
  2222. .replace(/\{uploadIcon}/g, config.uploadIcon)
  2223. .replace(/\{uploadTitle}/g, config.uploadTitle);
  2224. }
  2225. return template
  2226. .replace(/\{delete}/g, btnDelete)
  2227. .replace(/\{upload}/g, btnUpload)
  2228. .replace(/\{other}/g, otherButtons);
  2229. },
  2230. _browse: function (e) {
  2231. var self = this;
  2232. self._raise('filebrowse');
  2233. if (e && e.isDefaultPrevented()) {
  2234. return;
  2235. }
  2236. if (self.isError && !self.isUploadable) {
  2237. self.clear();
  2238. }
  2239. self.$captionContainer.focus();
  2240. },
  2241. _change: function (e) {
  2242. var self = this, $el = self.$element;
  2243. if (!self.isUploadable && isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix
  2244. self.fileInputCleared = false;
  2245. return;
  2246. }
  2247. self.fileInputCleared = false;
  2248. var tfiles, msg, total, isDragDrop = arguments.length > 1, isAjaxUpload = self.isUploadable, i = 0, f, n, len,
  2249. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files, ctr = self.filestack.length,
  2250. isSingleUpload = isEmpty($el.attr('multiple')), flagSingle = (isSingleUpload && ctr > 0), folders = 0,
  2251. throwError = function (mesg, file, previewId, index) {
  2252. var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}),
  2253. p2 = {id: previewId, index: index, file: file, files: files};
  2254. return self.isUploadable ? self._showUploadError(mesg, p1) : self._showError(mesg, p2);
  2255. };
  2256. self.reader = null;
  2257. self._resetUpload();
  2258. self._hideFileIcon();
  2259. if (self.isUploadable) {
  2260. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  2261. }
  2262. if (isDragDrop) {
  2263. tfiles = [];
  2264. while (files[i]) {
  2265. f = files[i];
  2266. if (!f.type && f.size % 4096 === 0) {
  2267. folders++;
  2268. } else {
  2269. tfiles.push(f);
  2270. }
  2271. i++;
  2272. }
  2273. } else {
  2274. if (e.target.files === undefined) {
  2275. tfiles = e.target && e.target.value ? [
  2276. {name: e.target.value.replace(/^.+\\/, '')}
  2277. ] : [];
  2278. } else {
  2279. tfiles = e.target.files;
  2280. }
  2281. }
  2282. if (isEmpty(tfiles) || tfiles.length === 0) {
  2283. if (!isAjaxUpload) {
  2284. self.clear();
  2285. }
  2286. self._showFolderError(folders);
  2287. self._raise('fileselectnone');
  2288. return;
  2289. }
  2290. self._resetErrors();
  2291. len = tfiles.length;
  2292. total = self._getFileCount(self.isUploadable ? (self.getFileStack().length + len) : len);
  2293. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  2294. if (!self.autoReplace || len > self.maxFileCount) {
  2295. n = (self.autoReplace && len > self.maxFileCount) ? len : total;
  2296. msg = self.msgFilesTooMany.replace('{m}', self.maxFileCount).replace('{n}', n);
  2297. self.isError = throwError(msg, null, null, null);
  2298. self.$captionContainer.find('.kv-caption-icon').hide();
  2299. self._setCaption('', true);
  2300. self.$container.removeClass('file-input-new file-input-ajax-new');
  2301. return;
  2302. }
  2303. if (total > self.maxFileCount) {
  2304. self._resetPreviewThumbs(isAjaxUpload);
  2305. }
  2306. } else {
  2307. if (!isAjaxUpload || flagSingle) {
  2308. self._resetPreviewThumbs(false);
  2309. if (flagSingle) {
  2310. self.clearStack();
  2311. }
  2312. } else {
  2313. if (isAjaxUpload && ctr === 0 && (!previewCache.count(self.id) || self.overwriteInitial)) {
  2314. self._resetPreviewThumbs(true);
  2315. }
  2316. }
  2317. }
  2318. if (self.isPreviewable) {
  2319. self._readFiles(tfiles);
  2320. } else {
  2321. self._updateFileDetails(1);
  2322. }
  2323. self._showFolderError(folders);
  2324. },
  2325. _abort: function (params) {
  2326. var self = this, data;
  2327. if (self.ajaxAborted && typeof self.ajaxAborted === "object" && self.ajaxAborted.message !== undefined) {
  2328. data = $.extend(true, {}, self._getOutData(), params);
  2329. data.abortData = self.ajaxAborted.data || {};
  2330. data.abortMessage = self.ajaxAborted.message;
  2331. self.cancel();
  2332. self._setProgress(100, self.$progress, self.msgCancelled);
  2333. self._showUploadError(self.ajaxAborted.message, data, 'filecustomerror');
  2334. return true;
  2335. }
  2336. return false;
  2337. },
  2338. _resetFileStack: function () {
  2339. var self = this, i = 0, newstack = [], newnames = [];
  2340. self._getThumbs().each(function () {
  2341. var $thumb = $(this), ind = $thumb.attr('data-fileindex'),
  2342. file = self.filestack[ind];
  2343. if (ind === -1) {
  2344. return;
  2345. }
  2346. if (file !== undefined) {
  2347. newstack[i] = file;
  2348. newnames[i] = self._getFileName(file);
  2349. $thumb.attr({
  2350. 'id': self.previewInitId + '-' + i,
  2351. 'data-fileindex': i
  2352. });
  2353. i++;
  2354. } else {
  2355. $thumb.attr({
  2356. 'id': 'uploaded-' + uniqId(),
  2357. 'data-fileindex': '-1'
  2358. });
  2359. }
  2360. });
  2361. self.filestack = newstack;
  2362. self.filenames = newnames;
  2363. },
  2364. clearStack: function () {
  2365. var self = this;
  2366. self.filestack = [];
  2367. self.filenames = [];
  2368. return self.$element;
  2369. },
  2370. updateStack: function (i, file) {
  2371. var self = this;
  2372. self.filestack[i] = file;
  2373. self.filenames[i] = self._getFileName(file);
  2374. return self.$element;
  2375. },
  2376. addToStack: function (file) {
  2377. var self = this;
  2378. self.filestack.push(file);
  2379. self.filenames.push(self._getFileName(file));
  2380. return self.$element;
  2381. },
  2382. getFileStack: function (skipNull) {
  2383. var self = this;
  2384. return self.filestack.filter(function (n) {
  2385. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  2386. });
  2387. },
  2388. lock: function () {
  2389. var self = this;
  2390. self._resetErrors();
  2391. self.disable();
  2392. if (self.showRemove) {
  2393. addCss(self.$container.find('.fileinput-remove'), 'hide');
  2394. }
  2395. if (self.showCancel) {
  2396. self.$container.find('.fileinput-cancel').removeClass('hide');
  2397. }
  2398. self._raise('filelock', [self.filestack, self._getExtraData()]);
  2399. return self.$element;
  2400. },
  2401. unlock: function (reset) {
  2402. var self = this;
  2403. if (reset === undefined) {
  2404. reset = true;
  2405. }
  2406. self.enable();
  2407. if (self.showCancel) {
  2408. addCss(self.$container.find('.fileinput-cancel'), 'hide');
  2409. }
  2410. if (self.showRemove) {
  2411. self.$container.find('.fileinput-remove').removeClass('hide');
  2412. }
  2413. if (reset) {
  2414. self._resetFileStack();
  2415. }
  2416. self._raise('fileunlock', [self.filestack, self._getExtraData()]);
  2417. return self.$element;
  2418. },
  2419. cancel: function () {
  2420. var self = this, xhr = self.ajaxRequests, len = xhr.length, i;
  2421. if (len > 0) {
  2422. for (i = 0; i < len; i += 1) {
  2423. self.cancelling = true;
  2424. xhr[i].abort();
  2425. }
  2426. }
  2427. self._setProgressCancelled();
  2428. self._getThumbs().each(function () {
  2429. var $thumb = $(this), ind = $thumb.attr('data-fileindex');
  2430. $thumb.removeClass('file-uploading');
  2431. if (self.filestack[ind] !== undefined) {
  2432. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  2433. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  2434. }
  2435. self.unlock();
  2436. });
  2437. return self.$element;
  2438. },
  2439. clear: function () {
  2440. var self = this, cap;
  2441. self.$btnUpload.removeAttr('disabled');
  2442. self._getThumbs().find('video,audio,img').each(function () {
  2443. cleanMemory($(this));
  2444. });
  2445. self._resetUpload();
  2446. self.clearStack();
  2447. self._clearFileInput();
  2448. self._resetErrors(true);
  2449. self._raise('fileclear');
  2450. if (self._hasInitialPreview()) {
  2451. self._showFileIcon();
  2452. self._resetPreview();
  2453. self._initPreviewDeletes();
  2454. self.$container.removeClass('file-input-new');
  2455. } else {
  2456. self._getThumbs().each(function () {
  2457. self._clearObjects($(this));
  2458. });
  2459. if (self.isUploadable) {
  2460. previewCache.data[self.id] = {};
  2461. }
  2462. self.$preview.html('');
  2463. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  2464. self._setCaption(cap);
  2465. self.$caption.attr('title', '');
  2466. addCss(self.$container, 'file-input-new');
  2467. self._validateDefaultPreview();
  2468. }
  2469. if (self.$container.find('.file-preview-frame').length === 0) {
  2470. if (!self._initCaption()) {
  2471. self.$captionContainer.find('.kv-caption-icon').hide();
  2472. }
  2473. }
  2474. self._hideFileIcon();
  2475. self._raise('filecleared');
  2476. self.$captionContainer.focus();
  2477. self._setFileDropZoneTitle();
  2478. return self.$element;
  2479. },
  2480. reset: function () {
  2481. var self = this;
  2482. self._resetPreview();
  2483. self.$container.find('.fileinput-filename').text('');
  2484. self._raise('filereset');
  2485. addCss(self.$container, 'file-input-new');
  2486. if (self.$preview.find('.file-preview-frame').length || self.isUploadable && self.dropZoneEnabled) {
  2487. self.$container.removeClass('file-input-new');
  2488. }
  2489. self._setFileDropZoneTitle();
  2490. self.clearStack();
  2491. self.formdata = {};
  2492. return self.$element;
  2493. },
  2494. disable: function () {
  2495. var self = this;
  2496. self.isDisabled = true;
  2497. self._raise('filedisabled');
  2498. self.$element.attr('disabled', 'disabled');
  2499. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  2500. self.$container.find(".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").attr(
  2501. "disabled",
  2502. true);
  2503. self._initDragDrop();
  2504. return self.$element;
  2505. },
  2506. enable: function () {
  2507. var self = this;
  2508. self.isDisabled = false;
  2509. self._raise('fileenabled');
  2510. self.$element.removeAttr('disabled');
  2511. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  2512. self.$container.find(
  2513. ".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").removeAttr("disabled");
  2514. self._initDragDrop();
  2515. return self.$element;
  2516. },
  2517. upload: function () {
  2518. var self = this, totLen = self.getFileStack().length, params = {},
  2519. i, outData, len, hasExtraData = !$.isEmptyObject(self._getExtraData());
  2520. if (self.minFileCount > 0 && self._getFileCount(totLen) < self.minFileCount) {
  2521. self._noFilesError(params);
  2522. return;
  2523. }
  2524. if (!self.isUploadable || self.isDisabled || (totLen === 0 && !hasExtraData)) {
  2525. return;
  2526. }
  2527. self._resetUpload();
  2528. self.$progress.removeClass('hide');
  2529. self.uploadCount = 0;
  2530. self.uploadStatus = {};
  2531. self.uploadLog = [];
  2532. self.lock();
  2533. self._setProgress(2);
  2534. if (totLen === 0 && hasExtraData) {
  2535. self._uploadExtraOnly();
  2536. return;
  2537. }
  2538. len = self.filestack.length;
  2539. self.hasInitData = false;
  2540. if (self.uploadAsync) {
  2541. outData = self._getOutData();
  2542. self._raise('filebatchpreupload', [outData]);
  2543. self.fileBatchCompleted = false;
  2544. self.uploadCache = {content: [], config: [], tags: [], append: true};
  2545. self.uploadAsyncCount = self.getFileStack().length;
  2546. for (i = 0; i < len; i++) {
  2547. self.uploadCache.content[i] = null;
  2548. self.uploadCache.config[i] = null;
  2549. self.uploadCache.tags[i] = null;
  2550. }
  2551. for (i = 0; i < len; i++) {
  2552. if (self.filestack[i] !== undefined) {
  2553. self._uploadSingle(i, self.filestack, true);
  2554. }
  2555. }
  2556. return;
  2557. }
  2558. self._uploadBatch();
  2559. return self.$element;
  2560. },
  2561. destroy: function () {
  2562. var self = this, $cont = self.$container;
  2563. $cont.find('.file-drop-zone').off();
  2564. self.$element.insertBefore($cont).off(NAMESPACE).removeData();
  2565. $cont.off().remove();
  2566. return self.$element;
  2567. },
  2568. refresh: function (options) {
  2569. var self = this, $el = self.$element;
  2570. options = options ? $.extend(true, {}, self.options, options) : self.options;
  2571. self.destroy();
  2572. $el.fileinput(options);
  2573. if ($el.val()) {
  2574. $el.trigger('change.fileinput');
  2575. }
  2576. return $el;
  2577. }
  2578. };
  2579. $.fn.fileinput = function (option) {
  2580. if (!hasFileAPISupport() && !isIE(9)) {
  2581. return;
  2582. }
  2583. var args = Array.apply(null, arguments), retvals = [];
  2584. args.shift();
  2585. this.each(function () {
  2586. var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option,
  2587. lang = options.language || self.data('language') || 'en', loc = {}, opts;
  2588. if (!data) {
  2589. if (lang !== 'en' && !isEmpty($.fn.fileinputLocales[lang])) {
  2590. loc = $.fn.fileinputLocales[lang];
  2591. }
  2592. opts = $.extend(true, {}, $.fn.fileinput.defaults, $.fn.fileinputLocales.en, loc, options, self.data());
  2593. data = new FileInput(this, opts);
  2594. self.data('fileinput', data);
  2595. }
  2596. if (typeof option === 'string') {
  2597. retvals.push(data[option].apply(data, args));
  2598. }
  2599. });
  2600. switch (retvals.length) {
  2601. case 0:
  2602. return this;
  2603. case 1:
  2604. return retvals[0];
  2605. default:
  2606. return retvals;
  2607. }
  2608. };
  2609. $.fn.fileinput.defaults = {
  2610. language: 'en',
  2611. showCaption: true,
  2612. showPreview: true,
  2613. showRemove: true,
  2614. showUpload: true,
  2615. showCancel: true,
  2616. showClose: true,
  2617. showUploadedThumbs: true,
  2618. autoReplace: false,
  2619. mainClass: '',
  2620. previewClass: '',
  2621. captionClass: '',
  2622. mainTemplate: null,
  2623. initialCaption: '',
  2624. initialPreview: [],
  2625. initialPreviewDelimiter: '*$$*',
  2626. initialPreviewConfig: [],
  2627. initialPreviewThumbTags: [],
  2628. previewThumbTags: {},
  2629. initialPreviewShowDelete: true,
  2630. removeFromPreviewOnError: false,
  2631. deleteUrl: '',
  2632. deleteExtraData: {},
  2633. overwriteInitial: true,
  2634. layoutTemplates: defaultLayoutTemplates,
  2635. previewTemplates: defaultPreviewTemplates,
  2636. allowedPreviewTypes: null,
  2637. allowedPreviewMimeTypes: null,
  2638. allowedFileTypes: null,
  2639. allowedFileExtensions: null,
  2640. defaultPreviewContent: null,
  2641. customLayoutTags: {},
  2642. customPreviewTags: {},
  2643. previewSettings: defaultPreviewSettings,
  2644. fileTypeSettings: defaultFileTypeSettings,
  2645. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  2646. previewFileIconClass: 'file-icon-4x',
  2647. previewFileIconSettings: {},
  2648. previewFileExtSettings: {},
  2649. buttonLabelClass: 'hidden-xs',
  2650. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i>&nbsp;',
  2651. browseClass: 'btn btn-primary',
  2652. removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
  2653. removeClass: 'btn btn-default',
  2654. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i>',
  2655. cancelClass: 'btn btn-default',
  2656. uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
  2657. uploadClass: 'btn btn-default',
  2658. uploadUrl: null,
  2659. uploadAsync: true,
  2660. uploadExtraData: {},
  2661. minImageWidth: null,
  2662. minImageHeight: null,
  2663. maxImageWidth: null,
  2664. maxImageHeight: null,
  2665. resizeImage: false,
  2666. resizePreference: 'width',
  2667. resizeQuality: 0.92,
  2668. resizeDefaultImageType: 'image/jpeg',
  2669. maxFileSize: 0,
  2670. minFileCount: 0,
  2671. maxFileCount: 0,
  2672. validateInitialCount: false,
  2673. msgValidationErrorClass: 'text-danger',
  2674. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  2675. msgErrorClass: 'file-error-message',
  2676. progressThumbClass: "progress-bar progress-bar-success progress-bar-striped active",
  2677. progressClass: "progress-bar progress-bar-success progress-bar-striped active",
  2678. progressCompleteClass: "progress-bar progress-bar-success",
  2679. progressErrorClass: "progress-bar progress-bar-danger",
  2680. previewFileType: 'image',
  2681. zoomIndicator: '<i class="glyphicon glyphicon-zoom-in"></i>',
  2682. elCaptionContainer: null,
  2683. elCaptionText: null,
  2684. elPreviewContainer: null,
  2685. elPreviewImage: null,
  2686. elPreviewStatus: null,
  2687. elErrorContainer: null,
  2688. errorCloseButton: '<span class="close kv-error-close">&times;</span>',
  2689. slugCallback: null,
  2690. dropZoneEnabled: true,
  2691. dropZoneTitleClass: 'file-drop-zone-title',
  2692. fileActionSettings: {},
  2693. otherActionButtons: '',
  2694. textEncoding: 'UTF-8',
  2695. ajaxSettings: {},
  2696. ajaxDeleteSettings: {},
  2697. showAjaxErrorDetails: true
  2698. };
  2699. $.fn.fileinputLocales.en = {
  2700. fileSingle: 'file',
  2701. filePlural: 'files',
  2702. browseLabel: 'Browse &hellip;',
  2703. removeLabel: 'Remove',
  2704. removeTitle: 'Clear selected files',
  2705. cancelLabel: 'Cancel',
  2706. cancelTitle: 'Abort ongoing upload',
  2707. uploadLabel: 'Upload',
  2708. uploadTitle: 'Upload selected files',
  2709. msgNo: 'No',
  2710. msgCancelled: 'Cancelled',
  2711. msgZoomTitle: 'View details',
  2712. msgZoomModalHeading: 'Detailed Preview',
  2713. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
  2714. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
  2715. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
  2716. msgFileNotFound: 'File "{name}" not found!',
  2717. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  2718. msgFileNotReadable: 'File "{name}" is not readable.',
  2719. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  2720. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  2721. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  2722. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  2723. msgUploadAborted: 'The file upload was aborted',
  2724. msgValidationError: 'Validation Error',
  2725. msgLoading: 'Loading file {index} of {files} &hellip;',
  2726. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  2727. msgSelected: '{n} {files} selected',
  2728. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  2729. msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
  2730. msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
  2731. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
  2732. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
  2733. msgImageResizeError: 'Could not get the image dimensions to resize.',
  2734. msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>',
  2735. dropZoneTitle: 'Drag & drop files here &hellip;'
  2736. };
  2737. $.fn.fileinput.Constructor = FileInput;
  2738. /**
  2739. * Convert automatically file inputs with class 'file' into a bootstrap fileinput control.
  2740. */
  2741. $(document).ready(function () {
  2742. var $input = $('input.file[type=file]');
  2743. if ($input.length) {
  2744. $input.fileinput();
  2745. }
  2746. });
  2747. }));