fileinput.js 96 KB

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