fileinput.js 120 KB

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