fileinput.js 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137
  1. /*!
  2. * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2015
  3. * @version 4.1.9
  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. String.prototype.repl = function (from, to) {
  21. return this.split(from).join(to);
  22. };
  23. var isIE = function (ver) {
  24. var div = document.createElement("div"), status;
  25. div.innerHTML = "<!--[if IE " + ver + "]><i></i><![endif]-->";
  26. status = (div.getElementsByTagName("i").length === 1);
  27. document.body.appendChild(div);
  28. div.parentNode.removeChild(div);
  29. return status;
  30. },
  31. previewCache = {
  32. data: {},
  33. init: function (obj) {
  34. var content = obj.initialPreview, id = obj.id;
  35. if (content.length > 0 && !isArray(content)) {
  36. content = content.split(obj.initialPreviewDelimiter);
  37. }
  38. previewCache.data[id] = {
  39. content: content,
  40. config: obj.initialPreviewConfig,
  41. tags: obj.initialPreviewThumbTags,
  42. delimiter: obj.initialPreviewDelimiter,
  43. template: obj.previewGenericTemplate,
  44. msg: obj.msgSelected,
  45. initId: obj.previewInitId,
  46. footer: obj.getLayoutTemplate('footer'),
  47. isDelete: obj.initialPreviewShowDelete,
  48. caption: obj.initialCaption,
  49. actions: function (showUpload, showDelete, disabled, url, key, index) {
  50. return obj.renderFileActions(showUpload, showDelete, disabled, url, key, index);
  51. }
  52. };
  53. },
  54. fetch: function (id) {
  55. return previewCache.data[id].content.filter(function (n) {
  56. return n !== undefined;
  57. });
  58. },
  59. count: function (id) {
  60. return !!previewCache.data[id] && !!previewCache.data[id].content ? previewCache.fetch(id).length : 0;
  61. },
  62. get: function (id, i, isDisabled) {
  63. var ind = 'init_' + i, data = previewCache.data[id],
  64. previewId = data.initId + '-' + ind, out;
  65. isDisabled = isDisabled === undefined ? true : isDisabled;
  66. if (data.content[i] === undefined) {
  67. return '';
  68. }
  69. out = data.template
  70. .repl('{previewId}', previewId)
  71. .repl('{frameClass}', ' file-preview-initial')
  72. .repl('{fileindex}', ind)
  73. .repl('{content}', data.content[i])
  74. .repl('{footer}', previewCache.footer(id, i, isDisabled));
  75. if (data.tags.length && data.tags[i]) {
  76. out = replaceTags(out, data.tags[i]);
  77. }
  78. return out;
  79. },
  80. add: function (id, content, config, append) {
  81. var data = $.extend(true, {}, previewCache.data[id]), index;
  82. if (!isArray(content)) {
  83. content = content.split(data.delimiter);
  84. }
  85. if (append) {
  86. index = data.content.push(content) - 1;
  87. data.config[index] = config;
  88. } else {
  89. index = content.length;
  90. data.content = content;
  91. data.config = config;
  92. }
  93. previewCache.data[id] = data;
  94. return index;
  95. },
  96. set: function (id, content, config, tags, append) {
  97. var data = $.extend(true, {}, previewCache.data[id]), i;
  98. if (!isArray(content)) {
  99. content = content.split(data.delimiter);
  100. }
  101. if (append) {
  102. for (i = 0; i < content.length; i++) {
  103. data.content.push(content[i]);
  104. }
  105. for (i = 0; i < config.length; i++) {
  106. data.config.push(config[i]);
  107. }
  108. for (i = 0; i < tags.length; i++) {
  109. data.tags.push(tags[i]);
  110. }
  111. } else {
  112. data.content = content;
  113. data.config = config;
  114. data.tags = tags;
  115. }
  116. previewCache.data[id] = data;
  117. },
  118. unset: function (id, index) {
  119. var chk = previewCache.count(id);
  120. if (!chk) {
  121. return;
  122. }
  123. if (chk === 1) {
  124. previewCache.data[id].content = [];
  125. previewCache.data[id].config = [];
  126. return;
  127. }
  128. previewCache.data[id].content[index] = undefined;
  129. previewCache.data[id].config[index] = undefined;
  130. },
  131. out: function (id) {
  132. var html = '', data = previewCache.data[id], caption, len = previewCache.count(id);
  133. if (len === 0) {
  134. return {content: '', caption: ''};
  135. }
  136. for (var i = 0; i < len; i++) {
  137. html += previewCache.get(id, i);
  138. }
  139. caption = data.msg.repl('{n}', len);
  140. return {content: html, caption: caption};
  141. },
  142. footer: function (id, i, isDisabled) {
  143. var data = previewCache.data[id];
  144. isDisabled = isDisabled === undefined ? true : isDisabled;
  145. if (data.config.length === 0 || isEmpty(data.config[i])) {
  146. return '';
  147. }
  148. var config = data.config[i],
  149. caption = isSet('caption', config) ? config.caption : '',
  150. width = isSet('width', config) ? config.width : 'auto',
  151. url = isSet('url', config) ? config.url : false,
  152. key = isSet('key', config) ? config.key : null,
  153. disabled = (url === false) && isDisabled,
  154. actions = data.isDelete ? data.actions(false, true, disabled, url, key, i) : '',
  155. footer = data.footer.repl('{actions}', actions);
  156. return footer
  157. .repl('{caption}', caption)
  158. .repl('{width}', width)
  159. .repl('{indicator}', '')
  160. .repl('{indicatorTitle}', '');
  161. }
  162. },
  163. PREVIEW_FRAMES = '.file-preview-frame:not(.file-preview-initial)',
  164. getNum = function (num, def) {
  165. def = def || 0;
  166. if (typeof num === "number") {
  167. return num;
  168. }
  169. if (typeof num === "string") {
  170. num = parseFloat(num);
  171. }
  172. return isNaN(num) ? def : num;
  173. },
  174. hasFileAPISupport = function () {
  175. return window.File && window.FileReader;
  176. },
  177. hasDragDropSupport = function () {
  178. var $div = document.createElement('div');
  179. return !isIE(9) && ($div.draggable !== undefined || ($div.ondragstart !== undefined && $div.ondrop !== undefined));
  180. },
  181. hasFileUploadSupport = function () {
  182. return hasFileAPISupport && window.FormData;
  183. },
  184. addCss = function ($el, css) {
  185. $el.removeClass(css).addClass(css);
  186. },
  187. STYLE_SETTING = 'style="width:{width};height:{height};"',
  188. OBJECT_PARAMS = ' <param name="controller" value="true" />\n' +
  189. ' <param name="allowFullScreen" value="true" />\n' +
  190. ' <param name="allowScriptAccess" value="always" />\n' +
  191. ' <param name="autoPlay" value="false" />\n' +
  192. ' <param name="autoStart" value="false" />\n' +
  193. ' <param name="quality" value="high" />\n',
  194. DEFAULT_PREVIEW = '<div class="file-preview-other">\n' +
  195. ' {previewFileIcon}\n' +
  196. ' </div>',
  197. defaultFileActionSettings = {
  198. removeIcon: '<i class="glyphicon glyphicon-trash text-danger"></i>',
  199. removeClass: 'btn btn-xs btn-default',
  200. removeTitle: 'Remove file',
  201. uploadIcon: '<i class="glyphicon glyphicon-upload text-info"></i>',
  202. uploadClass: 'btn btn-xs btn-default',
  203. uploadTitle: 'Upload file',
  204. indicatorNew: '<i class="glyphicon glyphicon-hand-down text-warning"></i>',
  205. indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign file-icon-large text-success"></i>',
  206. indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>',
  207. indicatorLoading: '<i class="glyphicon glyphicon-hand-up text-muted"></i>',
  208. indicatorNewTitle: 'Not uploaded yet',
  209. indicatorSuccessTitle: 'Uploaded',
  210. indicatorErrorTitle: 'Upload Error',
  211. indicatorLoadingTitle: 'Uploading ...'
  212. },
  213. tMain1 = '{preview}\n' +
  214. '<div class="kv-upload-progress hide"></div>\n' +
  215. '<div class="input-group {class}">\n' +
  216. ' {caption}\n' +
  217. ' <div class="input-group-btn">\n' +
  218. ' {remove}\n' +
  219. ' {cancel}\n' +
  220. ' {upload}\n' +
  221. ' {browse}\n' +
  222. ' </div>\n' +
  223. '</div>',
  224. tMain2 = '{preview}\n<div class="kv-upload-progress hide"></div>\n{remove}\n{cancel}\n{upload}\n{browse}\n',
  225. tPreview = '<div class="file-preview {class}">\n' +
  226. ' <div class="close fileinput-remove">&times;</div>\n' +
  227. ' <div class="{dropClass}">\n' +
  228. ' <div class="file-preview-thumbnails">\n' +
  229. ' </div>\n' +
  230. ' <div class="clearfix"></div>' +
  231. ' <div class="file-preview-status text-center text-success"></div>\n' +
  232. ' <div class="kv-fileinput-error"></div>\n' +
  233. ' </div>\n' +
  234. '</div>',
  235. tIcon = '<span class="glyphicon glyphicon-file kv-caption-icon"></span>',
  236. tCaption = '<div tabindex="-1" class="form-control file-caption {class}">\n' +
  237. ' <span class="file-caption-ellipsis">&hellip;</span>\n' +
  238. ' <div class="file-caption-name"></div>\n' +
  239. '</div>',
  240. tModal = '<div id="{id}" class="modal fade">\n' +
  241. ' <div class="modal-dialog modal-lg">\n' +
  242. ' <div class="modal-content">\n' +
  243. ' <div class="modal-header">\n' +
  244. ' <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>\n' +
  245. ' <h3 class="modal-title">Detailed Preview <small>{title}</small></h3>\n' +
  246. ' </div>\n' +
  247. ' <div class="modal-body">\n' +
  248. ' <textarea class="form-control" style="font-family:Monaco,Consolas,monospace; height: {height}px;" readonly>{body}</textarea>\n' +
  249. ' </div>\n' +
  250. ' </div>\n' +
  251. ' </div>\n' +
  252. '</div>',
  253. tProgress = '<div class="progress">\n' +
  254. ' <div class="{class}" role="progressbar"' +
  255. ' aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' +
  256. ' {percent}%\n' +
  257. ' </div>\n' +
  258. '</div>',
  259. tFooter = '<div class="file-thumbnail-footer">\n' +
  260. ' <div class="file-caption-name">{caption}</div>\n' +
  261. ' {actions}\n' +
  262. '</div>',
  263. tActions = '<div class="file-actions">\n' +
  264. ' <div class="file-footer-buttons">\n' +
  265. ' {upload}{delete}{other}' +
  266. ' </div>\n' +
  267. ' <div class="file-upload-indicator" tabindex="-1" title="{indicatorTitle}">{indicator}</div>\n' +
  268. ' <div class="clearfix"></div>\n' +
  269. '</div>',
  270. tActionDelete = '<button type="button" class="kv-file-remove {removeClass}" ' +
  271. 'title="{removeTitle}"{dataUrl}{dataKey}>{removeIcon}</button>\n',
  272. tActionUpload = '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">' +
  273. ' {uploadIcon}\n</button>\n',
  274. tGeneric = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  275. ' {content}\n' +
  276. ' {footer}\n' +
  277. '</div>\n',
  278. tHtml = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  279. ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  280. ' ' + DEFAULT_PREVIEW + '\n' +
  281. ' </object>\n' +
  282. ' {footer}\n' +
  283. '</div>',
  284. tImage = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  285. ' <img src="{data}" class="file-preview-image" title="{caption}" alt="{caption}" ' + STYLE_SETTING + '>\n' +
  286. ' {footer}\n' +
  287. '</div>\n',
  288. tText = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}">\n' +
  289. ' <div class="file-preview-text" title="{caption}" ' + STYLE_SETTING + '>\n' +
  290. ' {data}\n' +
  291. ' </div>\n' +
  292. ' {footer}\n' +
  293. '</div>',
  294. tVideo = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  295. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  296. ' <video width="{width}" height="{height}" controls>\n' +
  297. ' <source src="{data}" type="{type}">\n' +
  298. ' ' + DEFAULT_PREVIEW + '\n' +
  299. ' </video>\n' +
  300. ' {footer}\n' +
  301. '</div>\n',
  302. tAudio = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  303. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  304. ' <audio controls>\n' +
  305. ' <source src="' + '{data}' + '" type="{type}">\n' +
  306. ' ' + DEFAULT_PREVIEW + '\n' +
  307. ' </audio>\n' +
  308. ' {footer}\n' +
  309. '</div>',
  310. tFlash = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  311. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  312. ' <object type="application/x-shockwave-flash" width="{width}" height="{height}" data="{data}">\n' +
  313. OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' +
  314. ' </object>\n' +
  315. ' {footer}\n' +
  316. '</div>\n',
  317. tObject = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  318. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  319. ' <object data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  320. ' <param name="movie" value="{caption}" />\n' +
  321. OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n' +
  322. ' </object>\n' +
  323. ' {footer}\n' +
  324. '</div>',
  325. tOther = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  326. ' title="{caption}" ' + STYLE_SETTING + '>\n' +
  327. ' ' + DEFAULT_PREVIEW + '\n' +
  328. ' {footer}\n' +
  329. '</div>',
  330. defaultLayoutTemplates = {
  331. main1: tMain1,
  332. main2: tMain2,
  333. preview: tPreview,
  334. icon: tIcon,
  335. caption: tCaption,
  336. modal: tModal,
  337. progress: tProgress,
  338. footer: tFooter,
  339. actions: tActions,
  340. actionDelete: tActionDelete,
  341. actionUpload: tActionUpload
  342. },
  343. defaultPreviewTemplates = {
  344. generic: tGeneric,
  345. html: tHtml,
  346. image: tImage,
  347. text: tText,
  348. video: tVideo,
  349. audio: tAudio,
  350. flash: tFlash,
  351. object: tObject,
  352. other: tOther
  353. },
  354. defaultPreviewTypes = ['image', 'html', 'text', 'video', 'audio', 'flash', 'object'],
  355. defaultPreviewSettings = {
  356. image: {width: "auto", height: "160px"},
  357. html: {width: "213px", height: "160px"},
  358. text: {width: "160px", height: "160px"},
  359. video: {width: "213px", height: "160px"},
  360. audio: {width: "213px", height: "80px"},
  361. flash: {width: "213px", height: "160px"},
  362. object: {width: "160px", height: "160px"},
  363. other: {width: "160px", height: "160px"}
  364. },
  365. defaultFileTypeSettings = {
  366. image: function (vType, vName) {
  367. return (vType !== undefined) ? vType.match('image.*') : vName.match(/\.(gif|png|jpe?g)$/i);
  368. },
  369. html: function (vType, vName) {
  370. return (vType !== undefined) ? vType === 'text/html' : vName.match(/\.(htm|html)$/i);
  371. },
  372. text: function (vType, vName) {
  373. return (vType !== undefined && vType.match('text.*')) || vName.match(/\.(txt|md|csv|nfo|php|ini)$/i);
  374. },
  375. video: function (vType, vName) {
  376. return (vType !== undefined && vType.match(/\.video\/(ogg|mp4|webm)$/i)) || vName.match(/\.(og?|mp4|webm)$/i);
  377. },
  378. audio: function (vType, vName) {
  379. return (vType !== undefined && vType.match(/\.audio\/(ogg|mp3|wav)$/i)) || vName.match(/\.(ogg|mp3|wav)$/i);
  380. },
  381. flash: function (vType, vName) {
  382. return (vType !== undefined && vType === 'application/x-shockwave-flash') || vName.match(/\.(swf)$/i);
  383. },
  384. object: function () {
  385. return true;
  386. },
  387. other: function () {
  388. return true;
  389. }
  390. },
  391. isEmpty = function (value, trim) {
  392. return value === null || value === undefined || value.length === 0 || (trim && $.trim(value) === '');
  393. },
  394. isArray = function (a) {
  395. return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]';
  396. },
  397. isSet = function (needle, haystack) {
  398. return (typeof haystack === 'object' && needle in haystack);
  399. },
  400. getElement = function (options, param, value) {
  401. return (isEmpty(options) || isEmpty(options[param])) ? value : $(options[param]);
  402. },
  403. uniqId = function () {
  404. return Math.round(new Date().getTime() + (Math.random() * 100));
  405. },
  406. htmlEncode = function (str) {
  407. return String(str).repl('&', '&amp;')
  408. .repl('"', '&quot;')
  409. .repl("'", '&#39;')
  410. .repl('<', '&lt;')
  411. .repl('>', '&gt;');
  412. },
  413. replaceTags = function (str, tags) {
  414. var out = str;
  415. tags = tags || {};
  416. $.each(tags, function (key, value) {
  417. if (typeof value === "function") {
  418. value = value();
  419. }
  420. out = out.repl(key, value);
  421. });
  422. return out;
  423. },
  424. objUrl = window.URL || window.webkitURL,
  425. FileInput = function (element, options) {
  426. this.$element = $(element);
  427. if (hasFileAPISupport() || isIE(9)) {
  428. this.init(options);
  429. this.listen();
  430. } else {
  431. this.$element.removeClass('file-loading');
  432. }
  433. };
  434. FileInput.prototype = {
  435. constructor: FileInput,
  436. init: function (options) {
  437. var self = this, $el = self.$element, t;
  438. $.each(options, function (key, value) {
  439. self[key] = (key === 'maxFileCount' || key === 'maxFileSize') ? getNum(value) : value;
  440. });
  441. self.fileInputCleared = false;
  442. self.fileBatchCompleted = true;
  443. if (isEmpty(self.allowedPreviewTypes)) {
  444. self.allowedPreviewTypes = defaultPreviewTypes;
  445. }
  446. self.uploadFileAttr = !isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data';
  447. self.reader = null;
  448. self.formdata = {};
  449. self.isIE9 = isIE(9);
  450. self.isIE10 = isIE(10);
  451. self.filestack = [];
  452. self.ajaxRequests = [];
  453. self.isError = false;
  454. self.ajaxAborted = false;
  455. self.dropZoneEnabled = hasDragDropSupport() && self.dropZoneEnabled;
  456. self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly');
  457. self.isUploadable = hasFileUploadSupport && !isEmpty(self.uploadUrl);
  458. self.slug = typeof options.slugCallback === "function" ? options.slugCallback : self.slugDefault;
  459. self.mainTemplate = self.showCaption ? self.getLayoutTemplate('main1') : self.getLayoutTemplate('main2');
  460. self.captionTemplate = self.getLayoutTemplate('caption');
  461. self.previewGenericTemplate = self.getPreviewTemplate('generic');
  462. if (isEmpty(self.$element.attr('id'))) {
  463. self.$element.attr('id', uniqId());
  464. }
  465. if (self.$container === undefined) {
  466. self.$container = self.createContainer();
  467. } else {
  468. self.refreshContainer();
  469. }
  470. self.$progress = self.$container.find('.kv-upload-progress');
  471. self.$btnUpload = self.$container.find('.kv-fileinput-upload');
  472. self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption'));
  473. self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name'));
  474. self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview'));
  475. self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails'));
  476. self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status'));
  477. self.$errorContainer = getElement(options, 'elErrorContainer',
  478. self.$previewContainer.find('.kv-fileinput-error'));
  479. if (!isEmpty(self.msgErrorClass)) {
  480. addCss(self.$errorContainer, self.msgErrorClass);
  481. }
  482. self.$errorContainer.hide();
  483. self.fileActionSettings = $.extend(defaultFileActionSettings, options.fileActionSettings);
  484. self.previewInitId = "preview-" + uniqId();
  485. self.id = self.$element.attr('id');
  486. previewCache.init(self);
  487. self.initPreview(true);
  488. self.initPreviewDeletes();
  489. self.options = options;
  490. self.setFileDropZoneTitle();
  491. self.uploadCount = 0;
  492. self.uploadPercent = 0;
  493. self.$element.removeClass('file-loading');
  494. t = self.getLayoutTemplate('progress');
  495. self.progressTemplate = t.replace('{class}', self.progressClass);
  496. self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass);
  497. self.setEllipsis();
  498. },
  499. parseError: function (jqXHR, errorThrown, fileName) {
  500. var self = this, errMsg = $.trim(errorThrown + ''),
  501. dot = errMsg.slice(-1) === '.' ? '' : '.',
  502. text = $(jqXHR.responseText).text();
  503. if (self.showAjaxErrorDetails) {
  504. text = $.trim(text.replace(/\n\s*\n/g, '\n'));
  505. text = text.length > 0 ? '<pre>' + text + '</pre>' : '';
  506. errMsg += dot + text;
  507. } else {
  508. errMsg += dot;
  509. }
  510. return fileName ? '<b>' + fileName + ': </b>' + jqXHR : errMsg;
  511. },
  512. raise: function (event, params) {
  513. var self = this, e = $.Event(event), out = false;
  514. if (params !== undefined) {
  515. self.$element.trigger(e, params);
  516. } else {
  517. self.$element.trigger(e);
  518. }
  519. if (e.result) {
  520. out = true;
  521. }
  522. if (!out) {
  523. return;
  524. }
  525. switch (event) {
  526. // ignore these events
  527. case 'filebatchuploadcomplete':
  528. case 'filebatchuploadsuccess':
  529. case 'fileuploaded':
  530. case 'fileclear':
  531. case 'filecleared':
  532. case 'filereset':
  533. case 'fileerror':
  534. case 'filefoldererror':
  535. case 'fileuploaderror':
  536. case 'filebatchuploaderror':
  537. case 'filedeleteerror':
  538. case 'filecustomerror':
  539. break;
  540. // can trigger filecustomerror to abort upload
  541. default:
  542. self.ajaxAborted = out;
  543. break;
  544. }
  545. },
  546. getLayoutTemplate: function (t) {
  547. var self = this,
  548. template = isSet(t, self.layoutTemplates) ? self.layoutTemplates[t] : defaultLayoutTemplates[t];
  549. if (isEmpty(self.customLayoutTags)) {
  550. return template;
  551. }
  552. return replaceTags(template, self.customLayoutTags);
  553. },
  554. getPreviewTemplate: function (t) {
  555. var self = this,
  556. template = isSet(t, self.previewTemplates) ? self.previewTemplates[t] : defaultPreviewTemplates[t];
  557. template = template.repl('{previewFileIcon}', self.previewFileIcon);
  558. if (isEmpty(self.customPreviewTags)) {
  559. return template;
  560. }
  561. return replaceTags(template, self.customPreviewTags);
  562. },
  563. getOutData: function (jqXHR, responseData, filesData) {
  564. var self = this;
  565. jqXHR = jqXHR || {};
  566. responseData = responseData || {};
  567. filesData = filesData || self.filestack.slice(0) || {};
  568. return {
  569. form: self.formdata,
  570. files: filesData,
  571. extra: self.getExtraData(),
  572. response: responseData,
  573. reader: self.reader,
  574. jqXHR: jqXHR
  575. };
  576. },
  577. setEllipsis: function () {
  578. var self = this, $capCont = self.$captionContainer, $cap = self.$caption,
  579. $div = $cap.clone().css('height', 'auto').hide();
  580. $capCont.parent().before($div);
  581. $capCont.removeClass('kv-has-ellipsis');
  582. if ($div.outerWidth() > $cap.outerWidth()) {
  583. $capCont.addClass('kv-has-ellipsis');
  584. }
  585. $div.remove();
  586. },
  587. listen: function () {
  588. var self = this, $el = self.$element, $cap = self.$captionContainer, $btnFile = self.$btnFile,
  589. $form = $el.closest('form');
  590. $el.on('change', $.proxy(self.change, self));
  591. $(window).on('resize', function () {
  592. self.setEllipsis();
  593. });
  594. $btnFile.off('click').on('click', function () {
  595. self.raise('filebrowse');
  596. if (self.isError && !self.isUploadable) {
  597. self.clear();
  598. }
  599. $cap.focus();
  600. });
  601. $form.off('reset').on('reset', $.proxy(self.reset, self));
  602. self.$container.off('click')
  603. .on('click', '.fileinput-remove:not([disabled])', $.proxy(self.clear, self))
  604. .on('click', '.fileinput-cancel', $.proxy(self.cancel, self));
  605. if (self.isUploadable && self.dropZoneEnabled && self.showPreview) {
  606. self.initDragDrop();
  607. }
  608. if (!self.isUploadable) {
  609. $form.on('submit', $.proxy(self.submitForm, self));
  610. }
  611. self.$container.find('.kv-fileinput-upload').off('click').on('click', function (e) {
  612. if (!self.isUploadable) {
  613. return;
  614. }
  615. e.preventDefault();
  616. if (!$(this).hasClass('disabled') && isEmpty($(this).attr('disabled'))) {
  617. self.upload();
  618. }
  619. });
  620. },
  621. submitForm: function () {
  622. var self = this, $el = self.$element, files = $el.get(0).files;
  623. if (files && files.length < self.minFileCount && self.minFileCount > 0) {
  624. self.noFilesError({});
  625. return false;
  626. }
  627. return !self.abort({});
  628. },
  629. abort: function (params) {
  630. var self = this, data;
  631. if (self.ajaxAborted && typeof self.ajaxAborted === "object" && self.ajaxAborted.message !== undefined) {
  632. if (self.ajaxAborted.data !== undefined) {
  633. data = self.getOutData({}, self.ajaxAborted.data);
  634. } else {
  635. data = self.getOutData();
  636. }
  637. data = $.extend(data, params);
  638. self.showUploadError(self.ajaxAborted.message, data, 'filecustomerror');
  639. return true;
  640. }
  641. return false;
  642. },
  643. noFilesError: function (params) {
  644. var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle,
  645. msg = self.msgFilesTooLess.repl('{n}', self.minFileCount).repl('{files}', label),
  646. $error = self.$errorContainer;
  647. $error.html(msg);
  648. self.isError = true;
  649. self.updateFileDetails(0);
  650. $error.fadeIn(800);
  651. self.raise('fileerror', [params]);
  652. self.clearFileInput();
  653. addCss(self.$container, 'has-error');
  654. },
  655. setProgress: function (p) {
  656. var self = this, pct = Math.min(p, 100),
  657. template = pct < 100 ? self.progressTemplate : self.progressCompleteTemplate;
  658. self.$progress.html(template.repl('{percent}', pct));
  659. },
  660. upload: function () {
  661. var self = this, totLen = self.getFileStack().length, params = {},
  662. i, outData, len, hasExtraData = !$.isEmptyObject(self.getExtraData());
  663. if (totLen < self.minFileCount && self.minFileCount > 0) {
  664. self.noFilesError(params);
  665. return;
  666. }
  667. if (!self.isUploadable || self.isDisabled || (totLen === 0 && !hasExtraData)) {
  668. return;
  669. }
  670. self.resetUpload();
  671. self.$progress.removeClass('hide');
  672. self.uploadCount = 0;
  673. self.uploadPercent = 0;
  674. self.lock();
  675. self.setProgress(0);
  676. if (totLen === 0 && hasExtraData) {
  677. self.uploadExtraOnly();
  678. return;
  679. }
  680. len = self.filestack.length;
  681. self.hasInitData = false;
  682. if (self.uploadAsync && self.showPreview) {
  683. outData = self.getOutData();
  684. self.raise('filebatchpreupload', [outData]);
  685. self.fileBatchCompleted = false;
  686. self.uploadCache = {content: [], config: [], tags: [], append: true};
  687. for (i = 0; i < len; i += 1) {
  688. if (self.filestack[i] !== undefined) {
  689. self.uploadSingle(i, self.filestack, true);
  690. }
  691. }
  692. return;
  693. }
  694. self.uploadBatch();
  695. },
  696. lock: function () {
  697. var self = this;
  698. self.resetErrors();
  699. self.disable();
  700. if (self.showRemove) {
  701. addCss(self.$container.find('.fileinput-remove'), 'hide');
  702. }
  703. if (self.showCancel) {
  704. self.$container.find('.fileinput-cancel').removeClass('hide');
  705. }
  706. self.raise('filelock', [self.filestack, self.getExtraData()]);
  707. },
  708. unlock: function (reset) {
  709. var self = this;
  710. if (reset === undefined) {
  711. reset = true;
  712. }
  713. self.enable();
  714. if (self.showCancel) {
  715. addCss(self.$container.find('.fileinput-cancel'), 'hide');
  716. }
  717. if (self.showRemove) {
  718. self.$container.find('.fileinput-remove').removeClass('hide');
  719. }
  720. if (reset) {
  721. self.resetFileStack();
  722. }
  723. self.raise('fileunlock', [self.filestack, self.getExtraData()]);
  724. },
  725. resetFileStack: function () {
  726. var self = this, i = 0, newstack = [];
  727. self.$preview.find(PREVIEW_FRAMES).each(function () {
  728. var $thumb = $(this), ind = $thumb.attr('data-fileindex'),
  729. file = self.filestack[ind];
  730. if (ind === -1) {
  731. return;
  732. }
  733. if (file !== undefined) {
  734. newstack[i] = file;
  735. $thumb.attr({
  736. 'id': self.previewInitId + '-' + i,
  737. 'data-fileindex': i
  738. });
  739. i += 1;
  740. } else {
  741. $thumb.attr({
  742. 'id': 'uploaded-' + uniqId(),
  743. 'data-fileindex': '-1'
  744. });
  745. }
  746. });
  747. self.filestack = newstack;
  748. },
  749. refresh: function (options) {
  750. var self = this, $el = self.$element, $zone,
  751. params = (arguments.length) ? $.extend(self.options, options) : self.options;
  752. $el.off();
  753. self.init(params);
  754. $zone = self.$container.find('.file-drop-zone');
  755. $zone.off('dragenter dragover drop');
  756. $(document).off('dragenter dragover drop');
  757. self.listen();
  758. self.setFileDropZoneTitle();
  759. },
  760. initDragDrop: function () {
  761. var self = this, $zone = self.$container.find('.file-drop-zone');
  762. $zone.off('dragenter dragover drop');
  763. $(document).off('dragenter dragover drop');
  764. $zone.on('dragenter dragover', function (e) {
  765. e.stopPropagation();
  766. e.preventDefault();
  767. if (self.isDisabled) {
  768. return;
  769. }
  770. addCss($(this), 'highlighted');
  771. });
  772. $zone.on('dragleave', function (e) {
  773. e.stopPropagation();
  774. e.preventDefault();
  775. if (self.isDisabled) {
  776. return;
  777. }
  778. $(this).removeClass('highlighted');
  779. });
  780. $zone.on('drop', function (e) {
  781. e.preventDefault();
  782. if (self.isDisabled) {
  783. return;
  784. }
  785. self.change(e, 'dragdrop');
  786. $(this).removeClass('highlighted');
  787. });
  788. $(document).on('dragenter dragover drop', function (e) {
  789. e.stopPropagation();
  790. e.preventDefault();
  791. });
  792. },
  793. setFileDropZoneTitle: function () {
  794. var self = this, $zone = self.$container.find('.file-drop-zone');
  795. $zone.find('.' + self.dropZoneTitleClass).remove();
  796. if (!self.isUploadable || !self.showPreview || $zone.length === 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled) {
  797. return;
  798. }
  799. if ($zone.find('.file-preview-frame').length === 0) {
  800. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + self.dropZoneTitle + '</div>');
  801. }
  802. self.$container.removeClass('file-input-new');
  803. addCss(self.$container, 'file-input-ajax-new');
  804. },
  805. initFileActions: function () {
  806. var self = this;
  807. self.$preview.find('.kv-file-remove').each(function () {
  808. var $el = $(this), $frame = $el.closest('.file-preview-frame'),
  809. ind = $frame.attr('data-fileindex'), n, cap;
  810. $el.off('click').on('click', function () {
  811. $frame.fadeOut('slow', function () {
  812. self.filestack[ind] = undefined;
  813. self.clearObjects($frame);
  814. $frame.remove();
  815. var filestack = self.getFileStack(), len = filestack.length,
  816. chk = previewCache.count(self.id);
  817. self.clearFileInput();
  818. if (len === 0 && chk === 0) {
  819. self.reset();
  820. } else {
  821. n = chk + len;
  822. cap = n > 1 ? self.msgSelected.repl('{n}', n) : filestack[0].name;
  823. self.setCaption(cap);
  824. }
  825. });
  826. });
  827. });
  828. self.$preview.find('.kv-file-upload').each(function () {
  829. var $el = $(this);
  830. $el.off('click').on('click', function () {
  831. var $frame = $el.closest('.file-preview-frame'),
  832. ind = $frame.attr('data-fileindex');
  833. self.uploadSingle(ind, self.filestack, false);
  834. });
  835. });
  836. },
  837. renderFileFooter: function (caption, width) {
  838. var self = this, config = self.fileActionSettings, footer, out,
  839. template = self.getLayoutTemplate('footer');
  840. if (self.isUploadable) {
  841. footer = template.repl('{actions}', self.renderFileActions(true, true, false, false, false, false));
  842. out = footer.repl('{caption}', caption)
  843. .repl('{width}', width)
  844. .repl('{indicator}', config.indicatorNew)
  845. .repl('{indicatorTitle}', config.indicatorNewTitle);
  846. } else {
  847. out = template.repl('{actions}', '')
  848. .repl('{caption}', caption)
  849. .repl('{width}', width)
  850. .repl('{indicator}', '')
  851. .repl('{indicatorTitle}', '');
  852. }
  853. out = replaceTags(out, self.previewThumbTags);
  854. return out;
  855. },
  856. renderFileActions: function (showUpload, showDelete, disabled, url, key, index) {
  857. if (!showUpload && !showDelete) {
  858. return '';
  859. }
  860. var self = this,
  861. vUrl = url === false ? '' : ' data-url="' + url + '"',
  862. vKey = key === false ? '' : ' data-key="' + key + '"',
  863. btnDelete = self.getLayoutTemplate('actionDelete'),
  864. btnUpload = '',
  865. template = self.getLayoutTemplate('actions'),
  866. otherButtons = self.otherActionButtons.repl('{dataKey}', vKey),
  867. config = self.fileActionSettings,
  868. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  869. btnDelete = btnDelete
  870. .repl('{removeClass}', removeClass)
  871. .repl('{removeIcon}', config.removeIcon)
  872. .repl('{removeTitle}', config.removeTitle)
  873. .repl('{dataUrl}', vUrl)
  874. .repl('{dataKey}', vKey);
  875. if (showUpload) {
  876. btnUpload = self.getLayoutTemplate('actionUpload')
  877. .repl('{uploadClass}', config.uploadClass)
  878. .repl('{uploadIcon}', config.uploadIcon)
  879. .repl('{uploadTitle}', config.uploadTitle);
  880. }
  881. return template
  882. .repl('{delete}', btnDelete)
  883. .repl('{upload}', btnUpload)
  884. .repl('{other}', otherButtons);
  885. },
  886. initPreview: function (isInit) {
  887. var self = this, cap = self.initialCaption || '', out;
  888. if (!previewCache.count(self.id)) {
  889. self.$preview.html('');
  890. if (isInit) {
  891. self.setCaption(cap);
  892. } else {
  893. self.initCaption();
  894. }
  895. return;
  896. }
  897. out = previewCache.out(self.id);
  898. cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
  899. self.$preview.html(out.content);
  900. self.setCaption(cap);
  901. if (!isEmpty(out.content)) {
  902. self.$container.removeClass('file-input-new');
  903. }
  904. },
  905. initPreviewDeletes: function () {
  906. var self = this, deleteExtraData = self.deleteExtraData || {},
  907. resetProgress = function () {
  908. if (self.$preview.find('.kv-file-remove').length === 0) {
  909. self.reset();
  910. self.initialCaption = '';
  911. }
  912. };
  913. self.$preview.find('.kv-file-remove').each(function () {
  914. var $el = $(this), $frame = $el.closest('.file-preview-frame'),
  915. cache = previewCache.data[self.id], settings, params,
  916. vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key'),
  917. index = parseInt($frame.data('fileindex').replace('init_', '')),
  918. config = isEmpty(cache.config) && isEmpty(cache.config[index]) ? null : cache.config[index],
  919. extraData = isEmpty(config) || isEmpty(config.extra) ? deleteExtraData : config.extra;
  920. if (typeof extraData === "function") {
  921. extraData = extraData();
  922. }
  923. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  924. if (vUrl === undefined || vKey === undefined) {
  925. return;
  926. }
  927. settings = $.extend({
  928. url: vUrl,
  929. type: 'DELETE',
  930. dataType: 'json',
  931. data: $.extend({key: vKey}, extraData),
  932. beforeSend: function (jqXHR) {
  933. self.ajaxAborted = false;
  934. self.raise('filepredelete', [vKey, jqXHR, extraData]);
  935. if (self.ajaxAborted) {
  936. jqXHR.abort();
  937. } else {
  938. addCss($frame, 'file-uploading');
  939. addCss($el, 'disabled');
  940. }
  941. },
  942. success: function (data, textStatus, jqXHR) {
  943. if (data === undefined || data.error === undefined) {
  944. previewCache.unset(self.id, index);
  945. self.raise('filedeleted', [vKey, jqXHR, extraData]);
  946. } else {
  947. params.jqXHR = jqXHR;
  948. params.response = data;
  949. self.showError(data.error, params, 'filedeleteerror');
  950. $frame.removeClass('file-uploading');
  951. $el.removeClass('disabled');
  952. resetProgress();
  953. return;
  954. }
  955. $frame.removeClass('file-uploading').addClass('file-deleted');
  956. $frame.fadeOut('slow', function () {
  957. self.clearObjects($frame);
  958. $frame.remove();
  959. resetProgress();
  960. if (!previewCache.count(self.id) && self.getFileStack().length === 0) {
  961. self.reset();
  962. }
  963. });
  964. },
  965. error: function (jqXHR, textStatus, errorThrown) {
  966. var errMsg = self.parseError(jqXHR, errorThrown);
  967. params.jqXHR = jqXHR;
  968. params.response = {};
  969. self.showError(errMsg, params, 'filedeleteerror');
  970. $frame.removeClass('file-uploading');
  971. resetProgress();
  972. }
  973. }, self.ajaxDeleteSettings);
  974. $el.off('click').on('click', function () {
  975. $.ajax(settings);
  976. });
  977. });
  978. },
  979. clearObjects: function ($el) {
  980. $el.find('video audio').each(function () {
  981. this.pause();
  982. $(this).remove();
  983. });
  984. $el.find('img object div').each(function () {
  985. $(this).remove();
  986. });
  987. },
  988. clearFileInput: function () {
  989. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  990. if (isEmpty($el.val())) {
  991. return;
  992. }
  993. // Fix for IE ver < 11, that does not clear file inputs
  994. // Requires a sequence of steps to prevent IE crashing but
  995. // still allow clearing of the file input.
  996. if (self.isIE9 || self.isIE10) {
  997. $srcFrm = $el.closest('form');
  998. $tmpFrm = $(document.createElement('form'));
  999. $tmpEl = $(document.createElement('div'));
  1000. $el.before($tmpEl);
  1001. if ($srcFrm.length) {
  1002. $srcFrm.after($tmpFrm);
  1003. } else {
  1004. $tmpEl.after($tmpFrm);
  1005. }
  1006. $tmpFrm.append($el).trigger('reset');
  1007. $tmpEl.before($el).remove();
  1008. $tmpFrm.remove();
  1009. } else { // normal input clear behavior for other sane browsers
  1010. $el.val('');
  1011. }
  1012. self.fileInputCleared = true;
  1013. },
  1014. resetUpload: function () {
  1015. var self = this;
  1016. self.uploadCache = {content: [], config: [], tags: [], append: true};
  1017. self.uploadCount = 0;
  1018. self.uploadPercent = 0;
  1019. self.$btnUpload.removeAttr('disabled');
  1020. self.setProgress(0);
  1021. addCss(self.$progress, 'hide');
  1022. self.resetErrors(false);
  1023. self.ajaxAborted = false;
  1024. self.ajaxRequests = [];
  1025. },
  1026. cancel: function () {
  1027. var self = this, xhr = self.ajaxRequests, len = xhr.length, i;
  1028. if (len > 0) {
  1029. for (i = 0; i < len; i += 1) {
  1030. xhr[i].abort();
  1031. }
  1032. }
  1033. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1034. var $thumb = $(this), ind = $thumb.attr('data-fileindex');
  1035. $thumb.removeClass('file-uploading');
  1036. if (self.filestack[ind] !== undefined) {
  1037. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  1038. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  1039. }
  1040. self.unlock();
  1041. });
  1042. },
  1043. clear: function () {
  1044. var self = this, cap;
  1045. self.$btnUpload.removeAttr('disabled');
  1046. self.resetUpload();
  1047. self.filestack = [];
  1048. self.clearFileInput();
  1049. self.resetErrors(true);
  1050. self.raise('fileclear');
  1051. if (!self.overwriteInitial && previewCache.count(self.id)) {
  1052. self.showFileIcon();
  1053. self.resetPreview();
  1054. self.setEllipsis();
  1055. self.initPreviewDeletes();
  1056. self.$container.removeClass('file-input-new');
  1057. } else {
  1058. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1059. self.clearObjects($(this));
  1060. });
  1061. self.$preview.html('');
  1062. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  1063. self.setCaption(cap);
  1064. self.setEllipsis();
  1065. self.$caption.attr('title', '');
  1066. addCss(self.$container, 'file-input-new');
  1067. }
  1068. if (self.$container.find('.file-preview-frame').length === 0) {
  1069. if (!self.initCaption()) {
  1070. self.$captionContainer.find('.kv-caption-icon').hide();
  1071. }
  1072. self.setEllipsis();
  1073. }
  1074. self.hideFileIcon();
  1075. self.raise('filecleared');
  1076. self.$captionContainer.focus();
  1077. self.setFileDropZoneTitle();
  1078. },
  1079. resetPreview: function () {
  1080. var self = this, out;
  1081. if (previewCache.count(self.id)) {
  1082. out = previewCache.out(self.id);
  1083. self.$preview.html(out.content);
  1084. self.setCaption(out.caption);
  1085. } else {
  1086. self.$preview.html('');
  1087. self.initCaption();
  1088. }
  1089. },
  1090. reset: function () {
  1091. var self = this;
  1092. self.clear();
  1093. self.resetPreview();
  1094. self.setEllipsis();
  1095. self.$container.find('.fileinput-filename').text('');
  1096. self.raise('filereset');
  1097. if (self.initialPreview.length > 0) {
  1098. self.$container.removeClass('file-input-new');
  1099. }
  1100. self.setFileDropZoneTitle();
  1101. self.filestack = [];
  1102. self.formdata = {};
  1103. },
  1104. disable: function () {
  1105. var self = this;
  1106. self.isDisabled = true;
  1107. self.raise('filedisabled');
  1108. self.$element.attr('disabled', 'disabled');
  1109. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  1110. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").attr("disabled", true);
  1111. self.initDragDrop();
  1112. },
  1113. enable: function () {
  1114. var self = this;
  1115. self.isDisabled = false;
  1116. self.raise('fileenabled');
  1117. self.$element.removeAttr('disabled');
  1118. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  1119. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").removeAttr("disabled");
  1120. self.initDragDrop();
  1121. },
  1122. getExtraData: function () {
  1123. var self = this, data = self.uploadExtraData;
  1124. if (typeof self.uploadExtraData === "function") {
  1125. data = self.uploadExtraData();
  1126. }
  1127. return data;
  1128. },
  1129. uploadExtra: function () {
  1130. var self = this, data = self.getExtraData();
  1131. if (data.length === 0) {
  1132. return;
  1133. }
  1134. $.each(data, function (key, value) {
  1135. self.formdata.append(key, value);
  1136. });
  1137. },
  1138. initXhr: function (xhrobj, factor) {
  1139. var self = this;
  1140. if (xhrobj.upload) {
  1141. xhrobj.upload.addEventListener('progress', function (event) {
  1142. var pct = 0, position = event.loaded || event.position, total = event.total;
  1143. if (event.lengthComputable) {
  1144. pct = Math.ceil(position / total * factor);
  1145. }
  1146. self.uploadPercent = Math.max(pct, self.uploadPercent);
  1147. self.setProgress(self.uploadPercent);
  1148. }, false);
  1149. }
  1150. return xhrobj;
  1151. },
  1152. ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError) {
  1153. var self = this, settings;
  1154. self.uploadExtra();
  1155. settings = $.extend({
  1156. xhr: function () {
  1157. var xhrobj = $.ajaxSettings.xhr();
  1158. return self.initXhr(xhrobj, 98);
  1159. },
  1160. url: self.uploadUrl,
  1161. type: 'POST',
  1162. dataType: 'json',
  1163. data: self.formdata,
  1164. cache: false,
  1165. processData: false,
  1166. contentType: false,
  1167. beforeSend: fnBefore,
  1168. success: fnSuccess,
  1169. complete: fnComplete,
  1170. error: fnError
  1171. }, self.ajaxSettings);
  1172. self.ajaxRequests.push($.ajax(settings));
  1173. },
  1174. initUploadSuccess: function (out, $thumb, allFiles) {
  1175. var self = this, append, data, index, $newThumb, content, config, tags;
  1176. if (typeof out !== 'object' || $.isEmptyObject(out)) {
  1177. return;
  1178. }
  1179. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  1180. self.hasInitData = true;
  1181. content = out.initialPreview || [];
  1182. config = out.initialPreviewConfig || [];
  1183. tags = out.initialPreviewThumbTags || [];
  1184. append = out.append === undefined || out.append ? true : false;
  1185. self.overwriteInitial = false;
  1186. if ($thumb !== undefined && !!allFiles) {
  1187. index = previewCache.add(self.id, content, config[0], tags[0], append);
  1188. data = previewCache.get(self.id, index, false);
  1189. $newThumb = $(data).hide();
  1190. $thumb.after($newThumb).fadeOut('slow', function () {
  1191. $newThumb.fadeIn('slow').css('display:inline-block');
  1192. self.initPreviewDeletes();
  1193. });
  1194. } else {
  1195. if (allFiles) {
  1196. self.uploadCache.content.push(content[0]);
  1197. self.uploadCache.config.push(config[0]);
  1198. self.uploadCache.tags.push(tags[0]);
  1199. self.uploadCache.append = append;
  1200. } else {
  1201. previewCache.set(self.id, content, config, tags, append);
  1202. self.initPreview();
  1203. self.initPreviewDeletes();
  1204. }
  1205. }
  1206. }
  1207. },
  1208. uploadSingle: function (i, files, allFiles) {
  1209. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  1210. previewId = self.previewInitId + "-" + i, $thumb = $('#' + previewId + ':not(.file-preview-initial)'),
  1211. pct, chkComplete, $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove'),
  1212. $indicator = $thumb.find('.file-upload-indicator'), config = self.fileActionSettings,
  1213. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1214. setIndicator, updateProgress, resetActions, fnBefore, fnSuccess, fnComplete, fnError,
  1215. params = {id: previewId, index: i};
  1216. self.formdata = formdata;
  1217. if (total === 0 || !hasPostData || $btnUpload.hasClass('disabled') || self.abort(params)) {
  1218. return;
  1219. }
  1220. chkComplete = function () {
  1221. var $thumbs = self.$preview.find(PREVIEW_FRAMES + '.file-uploading');
  1222. if ($thumbs.length > 0 && self.fileBatchCompleted) {
  1223. return;
  1224. }
  1225. previewCache.set(self.id, self.uploadCache.content, self.uploadCache.config, self.uploadCache.tags,
  1226. self.uploadCache.append);
  1227. if (self.hasInitData) {
  1228. self.initPreview();
  1229. self.initPreviewDeletes();
  1230. }
  1231. self.setProgress(100);
  1232. self.unlock();
  1233. self.clearFileInput();
  1234. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1235. self.fileBatchCompleted = true;
  1236. };
  1237. setIndicator = function (icon, msg) {
  1238. $indicator.html(config[icon]);
  1239. $indicator.attr('title', config[msg]);
  1240. };
  1241. updateProgress = function () {
  1242. if (!allFiles || total === 0 || self.uploadPercent >= 100) {
  1243. return;
  1244. }
  1245. self.uploadCount += 1;
  1246. pct = 80 + Math.ceil(self.uploadCount * 20 / total);
  1247. self.uploadPercent = Math.max(pct, self.uploadPercent);
  1248. self.setProgress(self.uploadPercent);
  1249. self.initPreviewDeletes();
  1250. };
  1251. resetActions = function () {
  1252. $btnUpload.removeAttr('disabled');
  1253. $btnDelete.removeAttr('disabled');
  1254. $thumb.removeClass('file-uploading');
  1255. };
  1256. fnBefore = function (jqXHR) {
  1257. outData = self.getOutData(jqXHR);
  1258. setIndicator('indicatorLoading', 'indicatorLoadingTitle');
  1259. addCss($thumb, 'file-uploading');
  1260. $btnUpload.attr('disabled', true);
  1261. $btnDelete.attr('disabled', true);
  1262. if (!allFiles) {
  1263. self.lock();
  1264. }
  1265. self.raise('filepreupload', [outData, previewId, i]);
  1266. params = $.extend(params, outData);
  1267. if (self.abort(params)) {
  1268. jqXHR.abort();
  1269. self.setProgress(100);
  1270. }
  1271. };
  1272. fnSuccess = function (data, textStatus, jqXHR) {
  1273. outData = self.getOutData(jqXHR, data);
  1274. params = $.extend(params, outData);
  1275. setTimeout(function () {
  1276. if (data.error === undefined) {
  1277. setIndicator('indicatorSuccess', 'indicatorSuccessTitle');
  1278. $btnUpload.hide();
  1279. $btnDelete.hide();
  1280. self.filestack[i] = undefined;
  1281. self.raise('fileuploaded', [outData, previewId, i]);
  1282. self.initUploadSuccess(data, $thumb, allFiles);
  1283. if (!allFiles) {
  1284. self.resetFileStack();
  1285. }
  1286. } else {
  1287. setIndicator('indicatorError', 'indicatorErrorTitle');
  1288. self.showUploadError(data.error, params);
  1289. }
  1290. }, 100);
  1291. };
  1292. fnComplete = function () {
  1293. setTimeout(function () {
  1294. updateProgress();
  1295. resetActions();
  1296. if (!allFiles) {
  1297. self.unlock(false);
  1298. } else {
  1299. setTimeout(function () {
  1300. chkComplete();
  1301. }, 500);
  1302. }
  1303. }, 100);
  1304. };
  1305. fnError = function (jqXHR, textStatus, errorThrown) {
  1306. var errMsg = self.parseError(jqXHR, errorThrown, (allFiles ? files[i].name : null));
  1307. setIndicator('indicatorError', 'indicatorErrorTitle');
  1308. params = $.extend(params, self.getOutData(jqXHR));
  1309. self.showUploadError(errMsg, params);
  1310. };
  1311. formdata.append(self.uploadFileAttr, files[i]);
  1312. formdata.append('file_id', i);
  1313. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1314. },
  1315. uploadBatch: function () {
  1316. var self = this, files = self.filestack, total = files.length, config,
  1317. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1318. setIndicator, setAllUploaded, enableActions, fnBefore, fnSuccess, fnComplete, fnError,
  1319. params = {};
  1320. self.formdata = new FormData();
  1321. if (total === 0 || !hasPostData || self.abort(params)) {
  1322. return;
  1323. }
  1324. config = self.fileActionSettings;
  1325. setIndicator = function (i, icon, msg) {
  1326. var $indicator = $('#' + self.previewInitId + "-" + i).find('.file-upload-indicator');
  1327. $indicator.html(config[icon]);
  1328. $indicator.attr('title', config[msg]);
  1329. };
  1330. enableActions = function (i) {
  1331. var $thumb = $('#' + self.previewInitId + "-" + i + ':not(.file-preview-initial)'),
  1332. $btnUpload = $thumb.find('.kv-file-upload'),
  1333. $btnDelete = $thumb.find('.kv-file-delete');
  1334. $thumb.removeClass('file-uploading');
  1335. $btnUpload.removeAttr('disabled');
  1336. $btnDelete.removeAttr('disabled');
  1337. };
  1338. setAllUploaded = function () {
  1339. $.each(files, function (key, data) {
  1340. self.filestack[key] = undefined;
  1341. });
  1342. self.clearFileInput();
  1343. };
  1344. fnBefore = function (jqXHR) {
  1345. self.lock();
  1346. var outData = self.getOutData(jqXHR);
  1347. if (self.showPreview) {
  1348. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1349. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove');
  1350. addCss($thumb, 'file-uploading');
  1351. $btnUpload.attr('disabled', true);
  1352. $btnDelete.attr('disabled', true);
  1353. });
  1354. }
  1355. self.raise('filebatchpreupload', [outData]);
  1356. if (self.abort(outData)) {
  1357. jqXHR.abort();
  1358. }
  1359. };
  1360. fnSuccess = function (data, textStatus, jqXHR) {
  1361. var outData = self.getOutData(jqXHR, data),
  1362. keys = isEmpty(data.errorkeys) ? [] : data.errorkeys;
  1363. if (data.error === undefined || isEmpty(data.error)) {
  1364. self.raise('filebatchuploadsuccess', [outData]);
  1365. setAllUploaded();
  1366. if (self.showPreview) {
  1367. self.$preview.find('.kv-file-upload').hide();
  1368. self.$preview.find('.kv-file-remove').hide();
  1369. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1370. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1371. setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle');
  1372. enableActions(key);
  1373. });
  1374. self.initUploadSuccess(data);
  1375. } else {
  1376. self.reset();
  1377. }
  1378. } else {
  1379. if (self.showPreview) {
  1380. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1381. var $thumb = $(this), key = parseInt($thumb.attr('data-fileindex'), 10);
  1382. enableActions(key);
  1383. if (keys.length === 0) {
  1384. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1385. return;
  1386. }
  1387. if ($.inArray(key, keys) !== -1) {
  1388. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1389. } else {
  1390. $thumb.find('.kv-file-upload').hide();
  1391. $thumb.find('.kv-file-remove').hide();
  1392. setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle');
  1393. self.filestack[key] = undefined;
  1394. }
  1395. });
  1396. self.initUploadSuccess(data);
  1397. }
  1398. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1399. }
  1400. };
  1401. fnComplete = function () {
  1402. self.setProgress(100);
  1403. self.unlock();
  1404. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1405. self.clearFileInput();
  1406. };
  1407. fnError = function (jqXHR, textStatus, errorThrown) {
  1408. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1409. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1410. self.uploadFileCount = total - 1;
  1411. if (!self.showPreview) {
  1412. return;
  1413. }
  1414. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1415. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1416. $thumb.removeClass('file-uploading');
  1417. if (self.filestack[key] !== undefined) {
  1418. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1419. }
  1420. });
  1421. self.$preview.find(PREVIEW_FRAMES).removeClass('file-uploading');
  1422. self.$preview.find(PREVIEW_FRAMES + ' .kv-file-upload').removeAttr('disabled');
  1423. self.$preview.find(PREVIEW_FRAMES + ' .kv-file-delete').removeAttr('disabled');
  1424. };
  1425. $.each(files, function (key, data) {
  1426. if (!isEmpty(files[key])) {
  1427. self.formdata.append(self.uploadFileAttr, data);
  1428. }
  1429. });
  1430. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1431. },
  1432. uploadExtraOnly: function () {
  1433. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  1434. self.formdata = new FormData();
  1435. if (self.abort(params)) {
  1436. return;
  1437. }
  1438. fnBefore = function (jqXHR) {
  1439. self.lock();
  1440. var outData = self.getOutData(jqXHR);
  1441. self.raise('filebatchpreupload', [outData]);
  1442. self.setProgress(50);
  1443. params.data = outData;
  1444. params.xhr = jqXHR;
  1445. if (self.abort(params)) {
  1446. jqXHR.abort();
  1447. self.setProgress(100);
  1448. }
  1449. };
  1450. fnSuccess = function (data, textStatus, jqXHR) {
  1451. var outData = self.getOutData(jqXHR, data);
  1452. if (data.error === undefined || isEmpty(data.error)) {
  1453. self.raise('filebatchuploadsuccess', [outData]);
  1454. self.clearFileInput();
  1455. self.initUploadSuccess(data);
  1456. } else {
  1457. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1458. }
  1459. };
  1460. fnComplete = function () {
  1461. self.setProgress(100);
  1462. self.unlock();
  1463. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1464. self.clearFileInput();
  1465. };
  1466. fnError = function (jqXHR, textStatus, errorThrown) {
  1467. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1468. params.data = outData;
  1469. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1470. };
  1471. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1472. },
  1473. hideFileIcon: function () {
  1474. if (this.overwriteInitial) {
  1475. this.$captionContainer.find('.kv-caption-icon').hide();
  1476. }
  1477. },
  1478. showFileIcon: function () {
  1479. this.$captionContainer.find('.kv-caption-icon').show();
  1480. },
  1481. resetErrors: function (fade) {
  1482. var self = this, $error = self.$errorContainer;
  1483. self.isError = false;
  1484. self.$container.removeClass('has-error');
  1485. $error.html('');
  1486. if (fade) {
  1487. $error.fadeOut('slow');
  1488. } else {
  1489. $error.hide();
  1490. }
  1491. },
  1492. showFolderError: function (folders) {
  1493. var self = this, $error = self.$errorContainer;
  1494. if (!folders) {
  1495. return;
  1496. }
  1497. $error.html(self.msgFoldersNotAllowed.repl('{n}', folders));
  1498. $error.fadeIn(800);
  1499. addCss(self.$container, 'has-error');
  1500. self.raise('filefoldererror', [folders]);
  1501. },
  1502. showUploadError: function (msg, params, event) {
  1503. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror';
  1504. if ($error.find('ul').length === 0) {
  1505. $error.html('<ul><li>' + msg + '</li></ul>');
  1506. } else {
  1507. $error.find('ul').append('<li>' + msg + '</li>');
  1508. }
  1509. $error.fadeIn(800);
  1510. self.raise(ev, [params]);
  1511. addCss(self.$container, 'has-error');
  1512. return true;
  1513. },
  1514. showError: function (msg, params, event) {
  1515. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  1516. params = params || {};
  1517. params.reader = self.reader;
  1518. $error.html(msg);
  1519. $error.fadeIn(800);
  1520. self.raise(ev, [params]);
  1521. if (!self.isUploadable) {
  1522. self.clearFileInput();
  1523. }
  1524. addCss(self.$container, 'has-error');
  1525. self.$btnUpload.attr('disabled', true);
  1526. return true;
  1527. },
  1528. errorHandler: function (evt, caption) {
  1529. var self = this, err = evt.target.error;
  1530. switch (err.code) {
  1531. case err.NOT_FOUND_ERR:
  1532. self.showError(self.msgFileNotFound.repl('{name}', caption));
  1533. break;
  1534. case err.SECURITY_ERR:
  1535. self.showError(self.msgFileSecured.repl('{name}', caption));
  1536. break;
  1537. case err.NOT_READABLE_ERR:
  1538. self.showError(self.msgFileNotReadable.repl('{name}', caption));
  1539. break;
  1540. case err.ABORT_ERR:
  1541. self.showError(self.msgFilePreviewAborted.repl('{name}', caption));
  1542. break;
  1543. default:
  1544. self.showError(self.msgFilePreviewError.repl('{name}', caption));
  1545. }
  1546. },
  1547. parseFileType: function (file) {
  1548. var self = this, isValid, vType, cat, i;
  1549. for (i = 0; i < defaultPreviewTypes.length; i += 1) {
  1550. cat = defaultPreviewTypes[i];
  1551. isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  1552. vType = isValid(file.type, file.name) ? cat : '';
  1553. if (!isEmpty(vType)) {
  1554. return vType;
  1555. }
  1556. }
  1557. return 'other';
  1558. },
  1559. previewDefault: function (file, previewId, isDisabled) {
  1560. if (!this.showPreview) {
  1561. return;
  1562. }
  1563. var self = this, data = objUrl.createObjectURL(file), $obj = $('#' + previewId),
  1564. config = self.previewSettings.other,
  1565. footer = self.renderFileFooter(file.name, config.width),
  1566. previewOtherTemplate = self.getPreviewTemplate('other'),
  1567. ind = previewId.slice(previewId.lastIndexOf('-') + 1),
  1568. frameClass = '';
  1569. if (isDisabled === true) {
  1570. frameClass = ' btn disabled';
  1571. footer += '<div class="file-other-error text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i></div>';
  1572. }
  1573. self.$preview.append("\n" + previewOtherTemplate
  1574. .repl('{previewId}', previewId)
  1575. .repl('{frameClass}', frameClass)
  1576. .repl('{fileindex}', ind)
  1577. .repl('{caption}', self.slug(file.name))
  1578. .repl('{width}', config.width)
  1579. .repl('{height}', config.height)
  1580. .repl('{type}', file.type)
  1581. .repl('{data}', data)
  1582. .repl('{footer}', footer));
  1583. $obj.on('load', function () {
  1584. objUrl.revokeObjectURL($obj.attr('data'));
  1585. });
  1586. },
  1587. previewFile: function (file, theFile, previewId, data) {
  1588. if (!this.showPreview) {
  1589. return;
  1590. }
  1591. var self = this, cat = self.parseFileType(file), caption = self.slug(file.name), content, strText,
  1592. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes,
  1593. tmplt = self.getPreviewTemplate(cat),
  1594. config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat],
  1595. wrapLen = parseInt(self.wrapTextLength, 10), wrapInd = self.wrapIndicator,
  1596. chkTypes = types.indexOf(cat) >= 0, id, height,
  1597. chkMimes = isEmpty(mimes) || (!isEmpty(mimes) && mimes.indexOf(file.type) !== -1),
  1598. footer = self.renderFileFooter(caption, config.width), modal = '',
  1599. ind = previewId.slice(previewId.lastIndexOf('-') + 1);
  1600. if (chkTypes && chkMimes) {
  1601. if (cat === 'text') {
  1602. strText = htmlEncode(theFile.target.result);
  1603. objUrl.revokeObjectURL(data);
  1604. if (strText.length > wrapLen) {
  1605. id = 'text-' + uniqId();
  1606. height = window.innerHeight * 0.75;
  1607. modal = self.getLayoutTemplate('modal').repl('{id}', id)
  1608. .repl('{title}', caption)
  1609. .repl('{height}', height)
  1610. .repl('{body}', strText);
  1611. wrapInd = wrapInd
  1612. .repl('{title}', caption)
  1613. .repl('{dialog}', "$('#" + id + "').modal('show')");
  1614. strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
  1615. }
  1616. content = tmplt.repl('{previewId}', previewId).repl('{caption}', caption)
  1617. .repl('{frameClass}', '')
  1618. .repl('{type}', file.type).repl('{width}', config.width)
  1619. .repl('{height}', config.height).repl('{data}', strText)
  1620. .repl('{footer}', footer).repl('{fileindex}', ind) + modal;
  1621. } else {
  1622. content = tmplt.repl('{previewId}', previewId).repl('{caption}', caption)
  1623. .repl('{frameClass}', '')
  1624. .repl('{type}', file.type).repl('{data}', data)
  1625. .repl('{width}', config.width).repl('{height}', config.height)
  1626. .repl('{footer}', footer).repl('{fileindex}', ind);
  1627. }
  1628. self.$preview.append("\n" + content);
  1629. self.autoSizeImage(previewId);
  1630. } else {
  1631. self.previewDefault(file, previewId);
  1632. }
  1633. },
  1634. slugDefault: function (text) {
  1635. return isEmpty(text) ? '' : text.split(/(\\|\/)/g).pop().replace(/[^\w\u00C0-\u017F\-.\\\/ ]+/g, '');
  1636. },
  1637. getFileStack: function () {
  1638. var self = this;
  1639. return self.filestack.filter(function (n) {
  1640. return n !== undefined;
  1641. });
  1642. },
  1643. readFiles: function (files) {
  1644. this.reader = new FileReader();
  1645. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  1646. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  1647. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  1648. settings = self.fileTypeSettings, ctr = self.filestack.length,
  1649. throwError = function (msg, file, previewId, index) {
  1650. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  1651. p2 = {id: previewId, index: index, file: file, files: files};
  1652. self.previewDefault(file, previewId, true);
  1653. return self.isUploadable ? self.showUploadError(msg, p1) : self.showError(msg, p2);
  1654. };
  1655. function readFile(i) {
  1656. if (isEmpty($el.attr('multiple'))) {
  1657. numFiles = 1;
  1658. }
  1659. if (i >= numFiles) {
  1660. if (self.isUploadable && self.filestack.length > 0) {
  1661. self.raise('filebatchselected', [self.getFileStack()]);
  1662. } else {
  1663. self.raise('filebatchselected', [files]);
  1664. }
  1665. $container.removeClass('loading');
  1666. $status.html('');
  1667. return;
  1668. }
  1669. var node = ctr + i, previewId = previewInitId + "-" + node, isText, file = files[i],
  1670. caption = self.slug(file.name), fileSize = (file.size || 0) / 1000, checkFile, fileExtExpr = '',
  1671. previewData = objUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk,
  1672. fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '),
  1673. fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', ');
  1674. if (!isEmpty(fileExt)) {
  1675. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  1676. }
  1677. fileSize = fileSize.toFixed(2);
  1678. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  1679. msg = self.msgSizeTooLarge.repl('{name}', caption)
  1680. .repl('{size}', fileSize)
  1681. .repl('{maxSize}', self.maxFileSize);
  1682. self.isError = throwError(msg, file, previewId, i);
  1683. return;
  1684. }
  1685. if (!isEmpty(fileTypes) && isArray(fileTypes)) {
  1686. for (j = 0; j < fileTypes.length; j += 1) {
  1687. typ = fileTypes[j];
  1688. checkFile = settings[typ];
  1689. chk = (checkFile !== undefined && checkFile(file.type, caption));
  1690. fileCount += isEmpty(chk) ? 0 : chk.length;
  1691. }
  1692. if (fileCount === 0) {
  1693. msg = self.msgInvalidFileType.repl('{name}', caption).repl('{types}', strTypes);
  1694. self.isError = throwError(msg, file, previewId, i);
  1695. return;
  1696. }
  1697. }
  1698. if (fileCount === 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) {
  1699. chk = caption.match(fileExtExpr);
  1700. fileCount += isEmpty(chk) ? 0 : chk.length;
  1701. if (fileCount === 0) {
  1702. msg = self.msgInvalidFileExtension.repl('{name}', caption).repl('{extensions}',
  1703. strExt);
  1704. self.isError = throwError(msg, file, previewId, i);
  1705. return;
  1706. }
  1707. }
  1708. if (!self.showPreview) {
  1709. self.filestack.push(file);
  1710. setTimeout(readFile(i + 1), 100);
  1711. self.raise('fileloaded', [file, previewId, i, reader]);
  1712. return;
  1713. }
  1714. if ($preview.length > 0 && FileReader !== undefined) {
  1715. $status.html(msgLoading.repl('{index}', i + 1).repl('{files}', numFiles));
  1716. $container.addClass('loading');
  1717. reader.onerror = function (evt) {
  1718. self.errorHandler(evt, caption);
  1719. };
  1720. reader.onload = function (theFile) {
  1721. self.previewFile(file, theFile, previewId, previewData);
  1722. self.initFileActions();
  1723. };
  1724. reader.onloadend = function () {
  1725. msg = msgProgress
  1726. .repl('{index}', i + 1).repl('{files}', numFiles)
  1727. .repl('{percent}', 50).repl('{name}', caption);
  1728. setTimeout(function () {
  1729. $status.html(msg);
  1730. objUrl.revokeObjectURL(previewData);
  1731. }, 100);
  1732. setTimeout(function () {
  1733. readFile(i + 1);
  1734. self.updateFileDetails(numFiles);
  1735. }, 100);
  1736. self.raise('fileloaded', [file, previewId, i, reader]);
  1737. };
  1738. reader.onprogress = function (data) {
  1739. if (data.lengthComputable) {
  1740. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  1741. msg = msgProgress.repl('{index}', i + 1).repl('{files}', numFiles)
  1742. .repl('{percent}', progress).repl('{name}', caption);
  1743. setTimeout(function () {
  1744. $status.html(msg);
  1745. }, 100);
  1746. }
  1747. };
  1748. isText = isSet('text', settings) ? settings.text : defaultFileTypeSettings.text;
  1749. if (isText(file.type, caption)) {
  1750. reader.readAsText(file, self.textEncoding);
  1751. } else {
  1752. reader.readAsArrayBuffer(file);
  1753. }
  1754. } else {
  1755. self.previewDefault(file, previewId);
  1756. setTimeout(function () {
  1757. readFile(i + 1);
  1758. self.updateFileDetails(numFiles);
  1759. }, 100);
  1760. self.raise('fileloaded', [file, previewId, i, reader]);
  1761. }
  1762. self.filestack.push(file);
  1763. }
  1764. readFile(0);
  1765. self.updateFileDetails(numFiles, false);
  1766. },
  1767. updateFileDetails: function (numFiles) {
  1768. var self = this, msgSelected = self.msgSelected, $el = self.$element, fileStack = self.getFileStack(),
  1769. name = $el.val() || (fileStack.length && fileStack[0].name) || '', label = self.slug(name),
  1770. n = self.isUploadable ? fileStack.length : numFiles,
  1771. nFiles = previewCache.count(self.id) + n,
  1772. log = n > 1 ? msgSelected.repl('{n}', nFiles) : label;
  1773. if (self.isError) {
  1774. self.$previewContainer.removeClass('loading');
  1775. self.$previewStatus.html('');
  1776. self.$captionContainer.find('.kv-caption-icon').hide();
  1777. } else {
  1778. self.showFileIcon();
  1779. }
  1780. self.setCaption(log, self.isError);
  1781. self.$container.removeClass('file-input-new file-input-ajax-new');
  1782. if (arguments.length === 1) {
  1783. self.raise('fileselect', [numFiles, label]);
  1784. }
  1785. if (previewCache.count(self.id)) {
  1786. self.initPreviewDeletes();
  1787. }
  1788. },
  1789. change: function (e) {
  1790. var self = this, $el = self.$element;
  1791. if (!self.isUploadable && isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix
  1792. self.fileInputCleared = false;
  1793. return;
  1794. }
  1795. self.fileInputCleared = false;
  1796. var tfiles, msg, total, $preview = self.$preview, isDragDrop = arguments.length > 1,
  1797. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files,
  1798. isSingleUpload = isEmpty($el.attr('multiple')), i = 0, f, m, folders = 0,
  1799. ctr = self.filestack.length, isAjaxUpload = self.isUploadable,
  1800. throwError = function (mesg, file, previewId, index) {
  1801. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  1802. p2 = {id: previewId, index: index, file: file, files: files};
  1803. return self.isUploadable ? self.showUploadError(mesg, p1) : self.showError(mesg, p2);
  1804. };
  1805. self.reader = null;
  1806. self.resetUpload();
  1807. self.hideFileIcon();
  1808. if (self.isUploadable) {
  1809. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  1810. }
  1811. if (isDragDrop) {
  1812. tfiles = [];
  1813. while (files[i]) {
  1814. f = files[i];
  1815. if (!f.type && f.size % 4096 === 0) {
  1816. folders++;
  1817. } else {
  1818. tfiles.push(f);
  1819. }
  1820. i++;
  1821. }
  1822. } else {
  1823. if (e.target.files === undefined) {
  1824. tfiles = e.target && e.target.value ? [
  1825. {name: e.target.value.replace(/^.+\\/, '')}
  1826. ] : [];
  1827. } else {
  1828. tfiles = e.target.files;
  1829. }
  1830. }
  1831. if (isEmpty(tfiles) || tfiles.length === 0) {
  1832. if (!isAjaxUpload) {
  1833. self.clear();
  1834. }
  1835. self.showFolderError(folders);
  1836. self.raise('fileselectnone');
  1837. return;
  1838. }
  1839. self.resetErrors();
  1840. if (!isAjaxUpload || (isSingleUpload && ctr > 0)) {
  1841. if (!self.overwriteInitial && previewCache.count(self.id)) {
  1842. var out = previewCache.out(self.id);
  1843. $preview.html(out.content);
  1844. self.setCaption(out.caption);
  1845. self.initPreviewDeletes();
  1846. } else {
  1847. $preview.html('');
  1848. }
  1849. if (isSingleUpload && ctr > 0) {
  1850. self.filestack = [];
  1851. }
  1852. }
  1853. total = self.isUploadable ? self.getFileStack().length + tfiles.length : tfiles.length;
  1854. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  1855. msg = self.msgFilesTooMany.repl('{m}', self.maxFileCount).repl('{n}', total);
  1856. self.isError = throwError(msg, null, null, null);
  1857. self.$captionContainer.find('.kv-caption-icon').hide();
  1858. self.$caption.html(self.msgValidationError);
  1859. self.setEllipsis();
  1860. self.$container.removeClass('file-input-new file-input-ajax-new');
  1861. return;
  1862. }
  1863. if (!self.isIE9) {
  1864. self.readFiles(tfiles);
  1865. } else {
  1866. self.updateFileDetails(1);
  1867. }
  1868. self.showFolderError(folders);
  1869. },
  1870. autoSizeImage: function (previewId) {
  1871. var self = this, $preview = self.$preview,
  1872. $thumb = $preview.find("#" + previewId),
  1873. $img = $thumb.find('img'), w1, w2, $cap;
  1874. if (!$img.length) {
  1875. return;
  1876. }
  1877. $img.on('load', function () {
  1878. w1 = $thumb.width();
  1879. w2 = $preview.width();
  1880. if (w1 > w2) {
  1881. $img.css('width', '100%');
  1882. $thumb.css('width', '97%');
  1883. }
  1884. $cap = $img.closest('.file-preview-frame').find('.file-caption-name');
  1885. if ($cap.length) {
  1886. $cap.width($img.width());
  1887. $cap.attr('title', $cap.text());
  1888. }
  1889. self.raise('fileimageloaded', previewId);
  1890. });
  1891. },
  1892. initCaption: function () {
  1893. var self = this, cap;
  1894. if (self.overwriteInitial) {
  1895. self.$caption.html('');
  1896. return false;
  1897. }
  1898. cap = self.initialCaption || '';
  1899. self.setCaption(cap);
  1900. return true;
  1901. },
  1902. setCaption: function (content, isError) {
  1903. var self = this, err = isError || false, title, out;
  1904. if (err) {
  1905. title = $('<div>' + self.msgValidationError + '</div>').text();
  1906. out = '<span class="' + self.msgValidationErrorClass + '">' +
  1907. self.msgValidationErrorIcon + title + '</span>';
  1908. } else {
  1909. if (isEmpty(content) || self.$caption.length === 0) {
  1910. return;
  1911. }
  1912. title = $('<div>' + content + '</div>').text();
  1913. out = self.getLayoutTemplate('icon') + title;
  1914. }
  1915. self.$caption.html(out);
  1916. self.$caption.attr('title', title);
  1917. self.$captionContainer.find('.file-caption-ellipsis').attr('title', title);
  1918. self.setEllipsis();
  1919. },
  1920. initBrowse: function ($container) {
  1921. var self = this;
  1922. self.$btnFile = $container.find('.btn-file');
  1923. self.$btnFile.append(self.$element);
  1924. },
  1925. createContainer: function () {
  1926. var self = this,
  1927. $container = $(document.createElement("span"))
  1928. .attr({"class": 'file-input file-input-new'})
  1929. .html(self.renderMain());
  1930. self.$element.before($container);
  1931. self.initBrowse($container);
  1932. return $container;
  1933. },
  1934. refreshContainer: function () {
  1935. var self = this, $container = self.$container;
  1936. $container.before(self.$element);
  1937. $container.html(self.renderMain());
  1938. self.initBrowse($container);
  1939. },
  1940. renderMain: function () {
  1941. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : '',
  1942. preview = self.showPreview ? self.getLayoutTemplate('preview').repl('{class}', self.previewClass)
  1943. .repl('{dropClass}', dropCss) : '',
  1944. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  1945. caption = self.captionTemplate.repl('{class}', css + ' kv-fileinput-caption');
  1946. return self.mainTemplate.repl('{class}', self.mainClass)
  1947. .repl('{preview}', preview)
  1948. .repl('{caption}', caption)
  1949. .repl('{upload}', self.renderUpload())
  1950. .repl('{remove}', self.renderRemove())
  1951. .repl('{cancel}', self.renderCancel())
  1952. .repl('{browse}', self.renderBrowse());
  1953. },
  1954. renderBrowse: function () {
  1955. var self = this, css = self.browseClass + ' btn-file', status = '';
  1956. if (self.isDisabled) {
  1957. status = ' disabled ';
  1958. }
  1959. return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>';
  1960. },
  1961. renderRemove: function () {
  1962. var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
  1963. if (!self.showRemove) {
  1964. return '';
  1965. }
  1966. if (self.isDisabled) {
  1967. status = ' disabled ';
  1968. }
  1969. return '<button type="button" title="' + self.removeTitle + '" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
  1970. },
  1971. renderCancel: function () {
  1972. var self = this, css = self.cancelClass + ' fileinput-cancel fileinput-cancel-button';
  1973. if (!self.showCancel) {
  1974. return '';
  1975. }
  1976. return '<button type="button" title="' + self.cancelTitle + '" class="hide ' + css + '">' + self.cancelIcon + self.cancelLabel + '</button>';
  1977. },
  1978. renderUpload: function () {
  1979. var self = this, css = self.uploadClass + ' kv-fileinput-upload fileinput-upload-button', content = '', status = '';
  1980. if (!self.showUpload) {
  1981. return '';
  1982. }
  1983. if (self.isDisabled) {
  1984. status = ' disabled ';
  1985. }
  1986. if (!self.isUploadable || self.isDisabled) {
  1987. content = '<button type="submit" title="' + self.uploadTitle + '"class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
  1988. } else {
  1989. content = '<a href="' + self.uploadUrl + '" title="' + self.uploadTitle + '" class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>';
  1990. }
  1991. return content;
  1992. }
  1993. };
  1994. //FileInput plugin definition
  1995. $.fn.fileinput = function (option) {
  1996. if (!hasFileAPISupport() && !isIE(9)) {
  1997. return;
  1998. }
  1999. var args = Array.apply(null, arguments);
  2000. args.shift();
  2001. return this.each(function () {
  2002. var $this = $(this),
  2003. data = $this.data('fileinput'),
  2004. options = typeof option === 'object' && option;
  2005. if (!data) {
  2006. data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data()));
  2007. $this.data('fileinput', data);
  2008. }
  2009. if (typeof option === 'string') {
  2010. data[option].apply(data, args);
  2011. }
  2012. });
  2013. };
  2014. $.fn.fileinput.defaults = {
  2015. showCaption: true,
  2016. showPreview: true,
  2017. showRemove: true,
  2018. showUpload: true,
  2019. showCancel: true,
  2020. mainClass: '',
  2021. previewClass: '',
  2022. captionClass: '',
  2023. mainTemplate: null,
  2024. initialCaption: '',
  2025. initialPreview: [],
  2026. initialPreviewDelimiter: '*$$*',
  2027. initialPreviewConfig: [],
  2028. initialPreviewThumbTags: [],
  2029. previewThumbTags: {},
  2030. initialPreviewShowDelete: true,
  2031. deleteUrl: '',
  2032. deleteExtraData: {},
  2033. overwriteInitial: true,
  2034. layoutTemplates: defaultLayoutTemplates,
  2035. previewTemplates: defaultPreviewTemplates,
  2036. allowedPreviewTypes: defaultPreviewTypes,
  2037. allowedPreviewMimeTypes: null,
  2038. allowedFileTypes: null,
  2039. allowedFileExtensions: null,
  2040. customLayoutTags: {},
  2041. customPreviewTags: {},
  2042. previewSettings: defaultPreviewSettings,
  2043. fileTypeSettings: defaultFileTypeSettings,
  2044. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  2045. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  2046. browseClass: 'btn btn-primary',
  2047. removeIcon: '<i class="glyphicon glyphicon-trash"></i> ',
  2048. removeClass: 'btn btn-default',
  2049. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  2050. cancelClass: 'btn btn-default',
  2051. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  2052. uploadClass: 'btn btn-default',
  2053. uploadUrl: null,
  2054. uploadAsync: true,
  2055. uploadExtraData: {},
  2056. maxFileSize: 0,
  2057. minFileCount: 0,
  2058. maxFileCount: 0,
  2059. msgValidationErrorClass: 'text-danger',
  2060. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  2061. msgErrorClass: 'file-error-message',
  2062. progressClass: "progress-bar progress-bar-success progress-bar-striped active",
  2063. progressCompleteClass: "progress-bar progress-bar-success",
  2064. previewFileType: 'image',
  2065. wrapTextLength: 250,
  2066. wrapIndicator: ' <span class="wrap-indicator" title="{title}" onclick="{dialog}">[&hellip;]</span>',
  2067. elCaptionContainer: null,
  2068. elCaptionText: null,
  2069. elPreviewContainer: null,
  2070. elPreviewImage: null,
  2071. elPreviewStatus: null,
  2072. elErrorContainer: null,
  2073. slugCallback: null,
  2074. dropZoneEnabled: true,
  2075. dropZoneTitleClass: 'file-drop-zone-title',
  2076. fileActionSettings: {},
  2077. otherActionButtons: '',
  2078. textEncoding: 'UTF-8',
  2079. ajaxSettings: {},
  2080. ajaxDeleteSettings: {},
  2081. showAjaxErrorDetails: true
  2082. };
  2083. $.fn.fileinput.locales = {};
  2084. $.fn.fileinput.locales.en = {
  2085. fileSingle: 'file',
  2086. filePlural: 'files',
  2087. browseLabel: 'Browse &hellip;',
  2088. removeLabel: 'Remove',
  2089. removeTitle: 'Clear selected files',
  2090. cancelLabel: 'Cancel',
  2091. cancelTitle: 'Abort ongoing upload',
  2092. uploadLabel: 'Upload',
  2093. uploadTitle: 'Upload selected files',
  2094. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>. Please retry your upload!',
  2095. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload. Please retry your upload!',
  2096. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>. Please retry your upload!',
  2097. msgFileNotFound: 'File "{name}" not found!',
  2098. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  2099. msgFileNotReadable: 'File "{name}" is not readable.',
  2100. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  2101. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  2102. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  2103. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  2104. msgValidationError: 'File Upload Error',
  2105. msgLoading: 'Loading file {index} of {files} &hellip;',
  2106. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  2107. msgSelected: '{n} files selected',
  2108. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  2109. dropZoneTitle: 'Drag & drop files here &hellip;'
  2110. };
  2111. $.extend($.fn.fileinput.defaults, $.fn.fileinput.locales.en);
  2112. $.fn.fileinput.Constructor = FileInput;
  2113. /**
  2114. * Convert automatically file inputs with class 'file'
  2115. * into a bootstrap fileinput control.
  2116. */
  2117. $(document).ready(function () {
  2118. var $input = $('input.file[type=file]'), count = $input.attr('type') ? $input.length : 0;
  2119. if (count > 0) {
  2120. $input.fileinput();
  2121. }
  2122. });
  2123. })(window.jQuery);