fileinput.js 95 KB

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