fileinput.js 97 KB

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