fileinput.js 127 KB

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