fileinput.js 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108
  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. self.hasInitData = false;
  675. if (self.uploadAsync && self.showPreview) {
  676. outData = self.getOutData();
  677. self.raise('filebatchpreupload', [outData]);
  678. self.fileBatchCompleted = false;
  679. self.uploadCache = {content: [], config: [], append: true};
  680. for (i = 0; i < len; i += 1) {
  681. if (self.filestack[i] !== undefined) {
  682. self.uploadSingle(i, self.filestack, true);
  683. }
  684. }
  685. return;
  686. }
  687. self.uploadBatch();
  688. },
  689. lock: function () {
  690. var self = this;
  691. self.resetErrors();
  692. self.disable();
  693. if (self.showRemove) {
  694. addCss(self.$container.find('.fileinput-remove'), 'hide');
  695. }
  696. if (self.showCancel) {
  697. self.$container.find('.fileinput-cancel').removeClass('hide');
  698. }
  699. self.raise('filelock', [self.filestack, self.getExtraData()]);
  700. },
  701. unlock: function (reset) {
  702. var self = this;
  703. if (reset === undefined) {
  704. reset = true;
  705. }
  706. self.enable();
  707. if (self.showCancel) {
  708. addCss(self.$container.find('.fileinput-cancel'), 'hide');
  709. }
  710. if (self.showRemove) {
  711. self.$container.find('.fileinput-remove').removeClass('hide');
  712. }
  713. if (reset) {
  714. self.resetFileStack();
  715. }
  716. self.raise('fileunlock', [self.filestack, self.getExtraData()]);
  717. },
  718. resetFileStack: function () {
  719. var self = this, i = 0, newstack = [];
  720. self.$preview.find(PREVIEW_FRAMES).each(function () {
  721. var $thumb = $(this), ind = $thumb.attr('data-fileindex'),
  722. file = self.filestack[ind];
  723. if (ind === -1) {
  724. return;
  725. }
  726. if (file !== undefined) {
  727. newstack[i] = file;
  728. $thumb.attr({
  729. 'id': self.previewInitId + '-' + i,
  730. 'data-fileindex': i
  731. });
  732. i += 1;
  733. } else {
  734. $thumb.attr({
  735. 'id': 'uploaded-' + uniqId(),
  736. 'data-fileindex': '-1'
  737. });
  738. }
  739. });
  740. self.filestack = newstack;
  741. },
  742. refresh: function (options) {
  743. var self = this, $el = self.$element, $zone,
  744. params = (arguments.length) ? $.extend(self.options, options) : self.options;
  745. $el.off();
  746. self.init(params);
  747. $zone = self.$container.find('.file-drop-zone');
  748. $zone.off('dragenter dragover drop');
  749. $(document).off('dragenter dragover drop');
  750. self.listen();
  751. self.setFileDropZoneTitle();
  752. },
  753. initDragDrop: function () {
  754. var self = this, $zone = self.$container.find('.file-drop-zone');
  755. $zone.off('dragenter dragover drop');
  756. $(document).off('dragenter dragover drop');
  757. $zone.on('dragenter dragover', function (e) {
  758. e.stopPropagation();
  759. e.preventDefault();
  760. if (self.isDisabled) {
  761. return;
  762. }
  763. addCss($(this), 'highlighted');
  764. });
  765. $zone.on('dragleave', function (e) {
  766. e.stopPropagation();
  767. e.preventDefault();
  768. if (self.isDisabled) {
  769. return;
  770. }
  771. $(this).removeClass('highlighted');
  772. });
  773. $zone.on('drop', function (e) {
  774. e.preventDefault();
  775. if (self.isDisabled) {
  776. return;
  777. }
  778. self.change(e, 'dragdrop');
  779. $(this).removeClass('highlighted');
  780. });
  781. $(document).on('dragenter dragover drop', function (e) {
  782. e.stopPropagation();
  783. e.preventDefault();
  784. });
  785. },
  786. setFileDropZoneTitle: function () {
  787. var self = this, $zone = self.$container.find('.file-drop-zone');
  788. $zone.find('.' + self.dropZoneTitleClass).remove();
  789. if (!self.isUploadable || !self.showPreview || $zone.length === 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled) {
  790. return;
  791. }
  792. if ($zone.find('.file-preview-frame').length === 0) {
  793. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + self.dropZoneTitle + '</div>');
  794. }
  795. self.$container.removeClass('file-input-new');
  796. addCss(self.$container, 'file-input-ajax-new');
  797. },
  798. initFileActions: function () {
  799. var self = this;
  800. self.$preview.find('.kv-file-remove').each(function () {
  801. var $el = $(this), $frame = $el.closest('.file-preview-frame'),
  802. ind = $frame.attr('data-fileindex'), n, cap;
  803. $el.off('click').on('click', function () {
  804. $frame.fadeOut('slow', function () {
  805. self.filestack[ind] = undefined;
  806. self.clearObjects($frame);
  807. $frame.remove();
  808. var filestack = self.getFileStack(), len = filestack.length,
  809. chk = previewCache.count(self.id);
  810. self.clearFileInput();
  811. if (len === 0 && chk === 0) {
  812. self.reset();
  813. } else {
  814. n = chk + len;
  815. cap = n > 1 ? self.msgSelected.repl('{n}', n) : filestack[0].name;
  816. self.setCaption(cap);
  817. }
  818. });
  819. });
  820. });
  821. self.$preview.find('.kv-file-upload').each(function () {
  822. var $el = $(this);
  823. $el.off('click').on('click', function () {
  824. var $frame = $el.closest('.file-preview-frame'),
  825. ind = $frame.attr('data-fileindex');
  826. self.uploadSingle(ind, self.filestack, false);
  827. });
  828. });
  829. },
  830. renderFileFooter: function (caption, width) {
  831. var self = this, config = self.fileActionSettings, footer,
  832. template = self.getLayoutTemplate('footer');
  833. if (self.isUploadable) {
  834. footer = template.repl('{actions}', self.renderFileActions(true, true, false, false, false, false));
  835. return footer.repl('{caption}', caption)
  836. .repl('{width}', width)
  837. .repl('{indicator}', config.indicatorNew)
  838. .repl('{indicatorTitle}', config.indicatorNewTitle);
  839. }
  840. return template.repl('{actions}', '')
  841. .repl('{caption}', caption)
  842. .repl('{width}', width)
  843. .repl('{indicator}', '')
  844. .repl('{indicatorTitle}', '');
  845. },
  846. renderFileActions: function (showUpload, showDelete, disabled, url, key, index) {
  847. if (!showUpload && !showDelete) {
  848. return '';
  849. }
  850. var self = this,
  851. vUrl = url === false ? '' : ' data-url="' + url + '"',
  852. vKey = key === false ? '' : ' data-key="' + key + '"',
  853. btnDelete = self.getLayoutTemplate('actionDelete'),
  854. btnUpload = '',
  855. template = self.getLayoutTemplate('actions'),
  856. otherButtons = self.otherActionButtons.repl('{dataKey}', vKey),
  857. config = self.fileActionSettings,
  858. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  859. btnDelete = btnDelete
  860. .repl('{removeClass}', removeClass)
  861. .repl('{removeIcon}', config.removeIcon)
  862. .repl('{removeTitle}', config.removeTitle)
  863. .repl('{dataUrl}', vUrl)
  864. .repl('{dataKey}', vKey);
  865. if (showUpload) {
  866. btnUpload = self.getLayoutTemplate('actionUpload')
  867. .repl('{uploadClass}', config.uploadClass)
  868. .repl('{uploadIcon}', config.uploadIcon)
  869. .repl('{uploadTitle}', config.uploadTitle);
  870. }
  871. return template
  872. .repl('{delete}', btnDelete)
  873. .repl('{upload}', btnUpload)
  874. .repl('{other}', otherButtons);
  875. },
  876. initPreview: function (isInit) {
  877. var self = this, cap, out;
  878. if (!previewCache.count(self.id)) {
  879. self.$preview.html('');
  880. self.setCaption('');
  881. return;
  882. }
  883. out = previewCache.out(self.id);
  884. cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
  885. self.$preview.html(out.content);
  886. self.setCaption(cap);
  887. if (!isEmpty(out.content)) {
  888. self.$container.removeClass('file-input-new');
  889. }
  890. },
  891. initPreviewDeletes: function () {
  892. var self = this, deleteExtraData = self.deleteExtraData || {},
  893. resetProgress = function () {
  894. if (self.$preview.find('.kv-file-remove').length === 0) {
  895. self.reset();
  896. }
  897. };
  898. self.$preview.find('.kv-file-remove').each(function () {
  899. var $el = $(this), $frame = $el.closest('.file-preview-frame'),
  900. cache = previewCache.data[self.id], index, config, extraData,
  901. vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key'), settings,
  902. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  903. if (typeof extraData === "function") {
  904. extraData = extraData();
  905. }
  906. if (vUrl === undefined || vKey === undefined) {
  907. return;
  908. }
  909. settings = $.extend({
  910. url: vUrl,
  911. type: 'DELETE',
  912. dataType: 'json',
  913. data: $.extend({key: vKey}, extraData),
  914. beforeSend: function (jqXHR) {
  915. addCss($frame, 'file-uploading');
  916. addCss($el, 'disabled');
  917. self.raise('filepredelete', [vKey, jqXHR, extraData]);
  918. },
  919. success: function (data, textStatus, jqXHR) {
  920. index = parseInt($frame.data('fileindex').replace('init_', ''));
  921. config = isEmpty(cache.config) && isEmpty(cache.config[index]) ? null : cache.config[index];
  922. extraData = isEmpty(config) || isEmpty(config.extra) ? deleteExtraData : config.extra;
  923. if (data === undefined || data.error === undefined) {
  924. previewCache.unset(self.id, index);
  925. self.raise('filedeleted', [vKey, jqXHR, extraData]);
  926. } else {
  927. params.jqXHR = jqXHR;
  928. params.response = data;
  929. self.showError(data.error, params, 'filedeleteerror');
  930. $frame.removeClass('file-uploading');
  931. $el.removeClass('disabled');
  932. resetProgress();
  933. return;
  934. }
  935. $frame.removeClass('file-uploading').addClass('file-deleted');
  936. $frame.fadeOut('slow', function () {
  937. self.clearObjects($frame);
  938. $frame.remove();
  939. resetProgress();
  940. if (!previewCache.count(self.id)) {
  941. self.reset();
  942. }
  943. });
  944. },
  945. error: function (jqXHR, textStatus, errorThrown) {
  946. var errMsg = self.parseError(jqXHR, errorThrown);
  947. params.jqXHR = jqXHR;
  948. params.response = {};
  949. self.showError(errMsg, params, 'filedeleteerror');
  950. $frame.removeClass('file-uploading');
  951. resetProgress();
  952. }
  953. }, self.ajaxDeleteSettings);
  954. $el.off('click').on('click', function () {
  955. $.ajax(settings);
  956. });
  957. });
  958. },
  959. clearObjects: function ($el) {
  960. $el.find('video audio').each(function () {
  961. this.pause();
  962. $(this).remove();
  963. });
  964. $el.find('img object div').each(function () {
  965. $(this).remove();
  966. });
  967. },
  968. clearFileInput: function () {
  969. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  970. if (isEmpty($el.val())) {
  971. return;
  972. }
  973. // Fix for IE ver < 11, that does not clear file inputs
  974. // Requires a sequence of steps to prevent IE crashing but
  975. // still allow clearing of the file input.
  976. if (self.isIE9 || self.isIE10) {
  977. $srcFrm = $el.closest('form');
  978. $tmpFrm = $(document.createElement('form'));
  979. $tmpEl = $(document.createElement('div'));
  980. $el.before($tmpEl);
  981. if ($srcFrm.length) {
  982. $srcFrm.after($tmpFrm);
  983. } else {
  984. $tmpEl.after($tmpFrm);
  985. }
  986. $tmpFrm.append($el).trigger('reset');
  987. $tmpEl.before($el).remove();
  988. $tmpFrm.remove();
  989. } else { // normal input clear behavior for other sane browsers
  990. $el.val('');
  991. }
  992. self.fileInputCleared = true;
  993. },
  994. resetUpload: function () {
  995. var self = this;
  996. self.uploadCache = {content: [], config: [], append: true};
  997. self.uploadCount = 0;
  998. self.uploadPercent = 0;
  999. self.$btnUpload.removeAttr('disabled');
  1000. self.setProgress(0);
  1001. addCss(self.$progress, 'hide');
  1002. self.resetErrors(false);
  1003. self.uploadAborted = false;
  1004. self.ajaxRequests = [];
  1005. },
  1006. cancel: function () {
  1007. var self = this, xhr = self.ajaxRequests, len = xhr.length, i;
  1008. if (len > 0) {
  1009. for (i = 0; i < len; i += 1) {
  1010. xhr[i].abort();
  1011. }
  1012. }
  1013. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1014. var $thumb = $(this), ind = $thumb.attr('data-fileindex');
  1015. $thumb.removeClass('file-uploading');
  1016. if (self.filestack[ind] !== undefined) {
  1017. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  1018. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  1019. }
  1020. self.unlock();
  1021. });
  1022. },
  1023. clear: function () {
  1024. var self = this, cap;
  1025. if (!self.isIE9 && self.reader instanceof FileReader) {
  1026. self.reader.abort();
  1027. }
  1028. self.$btnUpload.removeAttr('disabled');
  1029. self.resetUpload();
  1030. self.filestack = [];
  1031. self.clearFileInput();
  1032. self.resetErrors(true);
  1033. self.raise('fileclear');
  1034. if (!self.overwriteInitial && previewCache.count(self.id)) {
  1035. self.showFileIcon();
  1036. self.resetPreview();
  1037. self.setEllipsis();
  1038. self.initPreviewDeletes();
  1039. self.$container.removeClass('file-input-new');
  1040. } else {
  1041. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1042. self.clearObjects($(this));
  1043. });
  1044. self.$preview.html('');
  1045. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  1046. self.$caption.html(cap);
  1047. self.setEllipsis();
  1048. self.$caption.attr('title', '');
  1049. addCss(self.$container, 'file-input-new');
  1050. }
  1051. if (self.$container.find('.file-preview-frame').length === 0) {
  1052. self.initialCaption = '';
  1053. self.$caption.html('');
  1054. self.setEllipsis();
  1055. self.$captionContainer.find('.kv-caption-icon').hide();
  1056. }
  1057. self.hideFileIcon();
  1058. self.raise('filecleared');
  1059. self.$captionContainer.focus();
  1060. self.setFileDropZoneTitle();
  1061. },
  1062. resetPreview: function () {
  1063. var self = this, out;
  1064. if (previewCache.count(self.id)) {
  1065. out = previewCache.out(self.id);
  1066. self.$preview.html(out.content);
  1067. self.setCaption(out.caption);
  1068. } else {
  1069. self.$preview.html('');
  1070. self.$caption.html('');
  1071. }
  1072. },
  1073. reset: function () {
  1074. var self = this;
  1075. self.clear();
  1076. self.resetPreview();
  1077. self.setEllipsis();
  1078. self.$container.find('.fileinput-filename').text('');
  1079. self.raise('filereset');
  1080. if (self.initialPreview.length > 0) {
  1081. self.$container.removeClass('file-input-new');
  1082. }
  1083. self.setFileDropZoneTitle();
  1084. if (self.isUploadable) {
  1085. self.resetUpload();
  1086. }
  1087. self.filestack = [];
  1088. self.formdata = {};
  1089. },
  1090. disable: function () {
  1091. var self = this;
  1092. self.isDisabled = true;
  1093. self.raise('filedisabled');
  1094. self.$element.attr('disabled', 'disabled');
  1095. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  1096. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").attr("disabled", true);
  1097. self.initDragDrop();
  1098. },
  1099. enable: function () {
  1100. var self = this;
  1101. self.isDisabled = false;
  1102. self.raise('fileenabled');
  1103. self.$element.removeAttr('disabled');
  1104. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  1105. self.$container.find(".btn-file, .fileinput-remove, .kv-fileinput-upload").removeAttr("disabled");
  1106. self.initDragDrop();
  1107. },
  1108. getExtraData: function () {
  1109. var self = this, data = self.uploadExtraData;
  1110. if (typeof self.uploadExtraData === "function") {
  1111. data = self.uploadExtraData();
  1112. }
  1113. return data;
  1114. },
  1115. uploadExtra: function () {
  1116. var self = this, data = self.getExtraData();
  1117. if (data.length === 0) {
  1118. return;
  1119. }
  1120. $.each(data, function (key, value) {
  1121. self.formdata.append(key, value);
  1122. });
  1123. },
  1124. initXhr: function (xhrobj, factor) {
  1125. var self = this;
  1126. if (xhrobj.upload) {
  1127. xhrobj.upload.addEventListener('progress', function (event) {
  1128. var pct = 0, position = event.loaded || event.position, total = event.total;
  1129. if (event.lengthComputable) {
  1130. pct = Math.ceil(position / total * factor);
  1131. }
  1132. self.uploadPercent = Math.max(pct, self.uploadPercent);
  1133. self.setProgress(self.uploadPercent);
  1134. }, false);
  1135. }
  1136. return xhrobj;
  1137. },
  1138. ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError) {
  1139. var self = this, settings;
  1140. self.uploadExtra();
  1141. settings = $.extend({
  1142. xhr: function () {
  1143. var xhrobj = $.ajaxSettings.xhr();
  1144. return self.initXhr(xhrobj, 98);
  1145. },
  1146. url: self.uploadUrl,
  1147. type: 'POST',
  1148. dataType: 'json',
  1149. data: self.formdata,
  1150. cache: false,
  1151. processData: false,
  1152. contentType: false,
  1153. beforeSend: fnBefore,
  1154. success: fnSuccess,
  1155. complete: fnComplete,
  1156. error: fnError
  1157. }, self.ajaxSettings);
  1158. self.ajaxRequests.push($.ajax(settings));
  1159. },
  1160. initUploadSuccess: function (out, $thumb, allFiles) {
  1161. var self = this, append, data, index, $newThumb, content, config;
  1162. if (typeof out !== 'object' || $.isEmptyObject(out)) {
  1163. return;
  1164. }
  1165. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  1166. self.hasInitData = true;
  1167. content = out.initialPreview || [];
  1168. config = out.initialPreviewConfig || [];
  1169. append = out.append === undefined || out.append ? true : false;
  1170. self.overwriteInitial = false;
  1171. if ($thumb !== undefined && !!allFiles) {
  1172. index = previewCache.add(self.id, content, config[0], append);
  1173. data = previewCache.get(self.id, index, false);
  1174. $newThumb = $(data).hide();
  1175. $thumb.after($newThumb).fadeOut('slow', function () {
  1176. $newThumb.fadeIn('slow').css('display:inline-block');
  1177. self.initPreviewDeletes();
  1178. });
  1179. } else {
  1180. if (allFiles) {
  1181. self.uploadCache.content.push(content[0]);
  1182. self.uploadCache.config.push(config[0]);
  1183. self.uploadCache.append = append;
  1184. } else {
  1185. previewCache.set(self.id, content, config, append);
  1186. self.initPreview();
  1187. self.initPreviewDeletes();
  1188. }
  1189. }
  1190. }
  1191. },
  1192. uploadSingle: function (i, files, allFiles) {
  1193. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  1194. previewId = self.previewInitId + "-" + i, $thumb = $('#' + previewId + ':not(.file-preview-initial)'),
  1195. pct, chkComplete, $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove'),
  1196. $indicator = $thumb.find('.file-upload-indicator'), config = self.fileActionSettings,
  1197. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1198. setIndicator, updateProgress, resetActions, fnBefore, fnSuccess, fnComplete, fnError,
  1199. params = {id: previewId, index: i};
  1200. self.formdata = formdata;
  1201. if (total === 0 || !hasPostData || $btnUpload.hasClass('disabled') || self.abort(params)) {
  1202. return;
  1203. }
  1204. chkComplete = function () {
  1205. var $thumbs = self.$preview.find(PREVIEW_FRAMES + '.file-uploading');
  1206. if ($thumbs.length > 0 && self.fileBatchCompleted) {
  1207. return;
  1208. }
  1209. previewCache.set(self.id, self.uploadCache.content, self.uploadCache.config, self.uploadCache.append);
  1210. if (self.hasInitData) {
  1211. self.initPreview();
  1212. self.initPreviewDeletes();
  1213. }
  1214. self.setProgress(100);
  1215. self.unlock();
  1216. self.clearFileInput();
  1217. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1218. self.fileBatchCompleted = true;
  1219. };
  1220. setIndicator = function (icon, msg) {
  1221. $indicator.html(config[icon]);
  1222. $indicator.attr('title', config[msg]);
  1223. };
  1224. updateProgress = function () {
  1225. if (!allFiles || total === 0 || self.uploadPercent >= 100) {
  1226. return;
  1227. }
  1228. self.uploadCount += 1;
  1229. pct = 80 + Math.ceil(self.uploadCount * 20 / total);
  1230. self.uploadPercent = Math.max(pct, self.uploadPercent);
  1231. self.setProgress(self.uploadPercent);
  1232. self.initPreviewDeletes();
  1233. };
  1234. resetActions = function () {
  1235. $btnUpload.removeAttr('disabled');
  1236. $btnDelete.removeAttr('disabled');
  1237. $thumb.removeClass('file-uploading');
  1238. };
  1239. fnBefore = function (jqXHR) {
  1240. outData = self.getOutData(jqXHR);
  1241. setIndicator('indicatorLoading', 'indicatorLoadingTitle');
  1242. addCss($thumb, 'file-uploading');
  1243. $btnUpload.attr('disabled', true);
  1244. $btnDelete.attr('disabled', true);
  1245. if (!allFiles) {
  1246. self.lock();
  1247. }
  1248. self.raise('filepreupload', [outData, previewId, i]);
  1249. params = $.extend(params, outData);
  1250. if (self.abort(params)) {
  1251. jqXHR.abort();
  1252. self.setProgress(100);
  1253. }
  1254. };
  1255. fnSuccess = function (data, textStatus, jqXHR) {
  1256. outData = self.getOutData(jqXHR, data);
  1257. params = $.extend(params, outData);
  1258. setTimeout(function () {
  1259. if (data.error === undefined) {
  1260. setIndicator('indicatorSuccess', 'indicatorSuccessTitle');
  1261. $btnUpload.hide();
  1262. $btnDelete.hide();
  1263. self.filestack[i] = undefined;
  1264. self.raise('fileuploaded', [outData, previewId, i]);
  1265. self.initUploadSuccess(data, $thumb, allFiles);
  1266. if (!allFiles) {
  1267. self.resetFileStack();
  1268. }
  1269. } else {
  1270. setIndicator('indicatorError', 'indicatorErrorTitle');
  1271. self.showUploadError(data.error, params);
  1272. }
  1273. }, 100);
  1274. };
  1275. fnComplete = function () {
  1276. setTimeout(function () {
  1277. updateProgress();
  1278. resetActions();
  1279. if (!allFiles) {
  1280. self.unlock(false);
  1281. } else {
  1282. setTimeout(function () {
  1283. chkComplete();
  1284. }, 500);
  1285. }
  1286. }, 100);
  1287. };
  1288. fnError = function (jqXHR, textStatus, errorThrown) {
  1289. var errMsg = self.parseError(jqXHR, errorThrown, (allFiles ? files[i].name : null));
  1290. setIndicator('indicatorError', 'indicatorErrorTitle');
  1291. params = $.extend(params, self.getOutData(jqXHR));
  1292. self.showUploadError(errMsg, params);
  1293. };
  1294. formdata.append(self.uploadFileAttr, files[i]);
  1295. formdata.append('file_id', i);
  1296. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1297. },
  1298. uploadBatch: function () {
  1299. var self = this, files = self.filestack, total = files.length, config,
  1300. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1301. setIndicator, setAllUploaded, enableActions, fnBefore, fnSuccess, fnComplete, fnError,
  1302. params = {};
  1303. self.formdata = new FormData();
  1304. if (total === 0 || !hasPostData || self.abort(params)) {
  1305. return;
  1306. }
  1307. config = self.fileActionSettings;
  1308. setIndicator = function (i, icon, msg) {
  1309. var $indicator = $('#' + self.previewInitId + "-" + i).find('.file-upload-indicator');
  1310. $indicator.html(config[icon]);
  1311. $indicator.attr('title', config[msg]);
  1312. };
  1313. enableActions = function (i) {
  1314. var $thumb = $('#' + self.previewInitId + "-" + i + ':not(.file-preview-initial)'),
  1315. $btnUpload = $thumb.find('.kv-file-upload'),
  1316. $btnDelete = $thumb.find('.kv-file-delete');
  1317. $thumb.removeClass('file-uploading');
  1318. $btnUpload.removeAttr('disabled');
  1319. $btnDelete.removeAttr('disabled');
  1320. };
  1321. setAllUploaded = function () {
  1322. $.each(files, function (key, data) {
  1323. self.filestack[key] = undefined;
  1324. });
  1325. self.clearFileInput();
  1326. };
  1327. fnBefore = function (jqXHR) {
  1328. self.lock();
  1329. var outData = self.getOutData(jqXHR);
  1330. if (self.showPreview) {
  1331. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1332. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove');
  1333. addCss($thumb, 'file-uploading');
  1334. $btnUpload.attr('disabled', true);
  1335. $btnDelete.attr('disabled', true);
  1336. });
  1337. }
  1338. self.raise('filebatchpreupload', [outData]);
  1339. if (self.abort(outData)) {
  1340. jqXHR.abort();
  1341. }
  1342. };
  1343. fnSuccess = function (data, textStatus, jqXHR) {
  1344. var outData = self.getOutData(jqXHR, data),
  1345. keys = isEmpty(data.errorkeys) ? [] : data.errorkeys;
  1346. if (data.error === undefined || isEmpty(data.error)) {
  1347. self.raise('filebatchuploadsuccess', [outData]);
  1348. setAllUploaded();
  1349. if (self.showPreview) {
  1350. self.$preview.find('.kv-file-upload').hide();
  1351. self.$preview.find('.kv-file-remove').hide();
  1352. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1353. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1354. setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle');
  1355. enableActions(key);
  1356. });
  1357. self.initUploadSuccess(data);
  1358. } else {
  1359. self.reset();
  1360. }
  1361. } else {
  1362. if (self.showPreview) {
  1363. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1364. var $thumb = $(this), key = parseInt($thumb.attr('data-fileindex'), 10);
  1365. enableActions(key);
  1366. if (keys.length === 0) {
  1367. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1368. return;
  1369. }
  1370. if ($.inArray(key, keys) !== -1) {
  1371. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1372. } else {
  1373. $thumb.find('.kv-file-upload').hide();
  1374. $thumb.find('.kv-file-remove').hide();
  1375. setIndicator(key, 'indicatorSuccess', 'indicatorSuccessTitle');
  1376. self.filestack[key] = undefined;
  1377. }
  1378. });
  1379. self.initUploadSuccess(data);
  1380. }
  1381. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1382. }
  1383. };
  1384. fnComplete = function () {
  1385. self.setProgress(100);
  1386. self.unlock();
  1387. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1388. self.clearFileInput();
  1389. };
  1390. fnError = function (jqXHR, textStatus, errorThrown) {
  1391. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1392. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1393. self.uploadFileCount = total - 1;
  1394. if (!self.showPreview) {
  1395. return;
  1396. }
  1397. self.$preview.find(PREVIEW_FRAMES).each(function () {
  1398. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1399. $thumb.removeClass('file-uploading');
  1400. if (self.filestack[key] !== undefined) {
  1401. setIndicator(key, 'indicatorError', 'indicatorErrorTitle');
  1402. }
  1403. });
  1404. self.$preview.find(PREVIEW_FRAMES).removeClass('file-uploading');
  1405. self.$preview.find(PREVIEW_FRAMES + ' .kv-file-upload').removeAttr('disabled');
  1406. self.$preview.find(PREVIEW_FRAMES + ' .kv-file-delete').removeAttr('disabled');
  1407. };
  1408. $.each(files, function (key, data) {
  1409. if (!isEmpty(files[key])) {
  1410. self.formdata.append(self.uploadFileAttr, data);
  1411. }
  1412. });
  1413. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1414. },
  1415. uploadExtraOnly: function () {
  1416. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  1417. self.formdata = new FormData();
  1418. if (self.abort(params)) {
  1419. return;
  1420. }
  1421. fnBefore = function (jqXHR) {
  1422. self.lock();
  1423. var outData = self.getOutData(jqXHR);
  1424. self.raise('filebatchpreupload', [outData]);
  1425. self.setProgress(50);
  1426. params.data = outData;
  1427. params.xhr = jqXHR;
  1428. if (self.abort(params)) {
  1429. jqXHR.abort();
  1430. self.setProgress(100);
  1431. }
  1432. };
  1433. fnSuccess = function (data, textStatus, jqXHR) {
  1434. var outData = self.getOutData(jqXHR, data);
  1435. if (data.error === undefined || isEmpty(data.error)) {
  1436. self.raise('filebatchuploadsuccess', [outData]);
  1437. self.clearFileInput();
  1438. self.initUploadSuccess(data);
  1439. } else {
  1440. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1441. }
  1442. };
  1443. fnComplete = function () {
  1444. self.setProgress(100);
  1445. self.unlock();
  1446. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1447. self.clearFileInput();
  1448. };
  1449. fnError = function (jqXHR, textStatus, errorThrown) {
  1450. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1451. params.data = outData;
  1452. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1453. };
  1454. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1455. },
  1456. hideFileIcon: function () {
  1457. if (this.overwriteInitial) {
  1458. this.$captionContainer.find('.kv-caption-icon').hide();
  1459. }
  1460. },
  1461. showFileIcon: function () {
  1462. this.$captionContainer.find('.kv-caption-icon').show();
  1463. },
  1464. resetErrors: function (fade) {
  1465. var self = this, $error = self.$errorContainer;
  1466. self.isError = false;
  1467. self.$container.removeClass('has-error');
  1468. $error.html('');
  1469. if (fade) {
  1470. $error.fadeOut('slow');
  1471. } else {
  1472. $error.hide();
  1473. }
  1474. },
  1475. showFolderError: function (folders) {
  1476. var self = this, $error = self.$errorContainer;
  1477. if (!folders) {
  1478. return;
  1479. }
  1480. $error.html(self.msgFoldersNotAllowed.repl('{n}', folders));
  1481. $error.fadeIn(800);
  1482. addCss(self.$container, 'has-error');
  1483. self.raise('filefoldererror', [folders]);
  1484. },
  1485. showUploadError: function (msg, params, event) {
  1486. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror';
  1487. if ($error.find('ul').length === 0) {
  1488. $error.html('<ul class="text-left"><br><li>' + msg + '</li></ul>');
  1489. } else {
  1490. $error.find('ul').append('<br><li>' + msg + '</li>');
  1491. }
  1492. $error.fadeIn(800);
  1493. self.raise(ev, [params]);
  1494. addCss(self.$container, 'has-error');
  1495. return true;
  1496. },
  1497. showError: function (msg, params, event) {
  1498. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  1499. params = params || {};
  1500. params.reader = self.reader;
  1501. $error.html(msg);
  1502. $error.fadeIn(800);
  1503. self.raise(ev, [params]);
  1504. if (!self.isUploadable) {
  1505. self.clearFileInput();
  1506. }
  1507. addCss(self.$container, 'has-error');
  1508. self.$btnUpload.attr('disabled', true);
  1509. return true;
  1510. },
  1511. errorHandler: function (evt, caption) {
  1512. var self = this, err = evt.target.error;
  1513. switch (err.code) {
  1514. case err.NOT_FOUND_ERR:
  1515. self.showError(self.msgFileNotFound.repl('{name}', caption));
  1516. break;
  1517. case err.SECURITY_ERR:
  1518. self.showError(self.msgFileSecured.repl('{name}', caption));
  1519. break;
  1520. case err.NOT_READABLE_ERR:
  1521. self.showError(self.msgFileNotReadable.repl('{name}', caption));
  1522. break;
  1523. case err.ABORT_ERR:
  1524. self.showError(self.msgFilePreviewAborted.repl('{name}', caption));
  1525. break;
  1526. default:
  1527. self.showError(self.msgFilePreviewError.repl('{name}', caption));
  1528. }
  1529. },
  1530. parseFileType: function (file) {
  1531. var self = this, isValid, vType, cat, i;
  1532. for (i = 0; i < defaultPreviewTypes.length; i += 1) {
  1533. cat = defaultPreviewTypes[i];
  1534. isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  1535. vType = isValid(file.type, file.name) ? cat : '';
  1536. if (!isEmpty(vType)) {
  1537. return vType;
  1538. }
  1539. }
  1540. return 'other';
  1541. },
  1542. previewDefault: function (file, previewId, isDisabled) {
  1543. if (!this.showPreview) {
  1544. return;
  1545. }
  1546. var self = this, data = objUrl.createObjectURL(file), $obj = $('#' + previewId),
  1547. config = self.previewSettings.other,
  1548. footer = self.renderFileFooter(file.name, config.width),
  1549. previewOtherTemplate = self.getPreviewTemplate('other'),
  1550. ind = previewId.slice(previewId.lastIndexOf('-') + 1),
  1551. frameClass = '';
  1552. if (isDisabled === true) {
  1553. frameClass = ' btn disabled';
  1554. footer += '<div class="file-other-error text-danger"><i class="glyphicon glyphicon-exclamation-sign"></i></div>';
  1555. }
  1556. self.$preview.append("\n" + previewOtherTemplate
  1557. .repl('{previewId}', previewId)
  1558. .repl('{frameClass}', frameClass)
  1559. .repl('{fileindex}', ind)
  1560. .repl('{caption}', self.slug(file.name))
  1561. .repl('{width}', config.width)
  1562. .repl('{height}', config.height)
  1563. .repl('{type}', file.type)
  1564. .repl('{data}', data)
  1565. .repl('{footer}', footer));
  1566. $obj.on('load', function () {
  1567. objUrl.revokeObjectURL($obj.attr('data'));
  1568. });
  1569. },
  1570. previewFile: function (file, theFile, previewId, data) {
  1571. if (!this.showPreview) {
  1572. return;
  1573. }
  1574. var self = this, cat = self.parseFileType(file), caption = self.slug(file.name), content, strText,
  1575. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes,
  1576. tmplt = self.getPreviewTemplate(cat),
  1577. config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat],
  1578. wrapLen = parseInt(self.wrapTextLength, 10), wrapInd = self.wrapIndicator,
  1579. chkTypes = types.indexOf(cat) >= 0, id, height,
  1580. chkMimes = isEmpty(mimes) || (!isEmpty(mimes) && isSet(file.type, mimes)),
  1581. footer = self.renderFileFooter(caption, config.width), modal = '',
  1582. ind = previewId.slice(previewId.lastIndexOf('-') + 1);
  1583. if (chkTypes && chkMimes) {
  1584. if (cat === 'text') {
  1585. strText = htmlEncode(theFile.target.result);
  1586. objUrl.revokeObjectURL(data);
  1587. if (strText.length > wrapLen) {
  1588. id = 'text-' + uniqId();
  1589. height = window.innerHeight * 0.75;
  1590. modal = self.getLayoutTemplate('modal').repl('{id}', id)
  1591. .repl('{title}', caption)
  1592. .repl('{height}', height)
  1593. .repl('{body}', strText);
  1594. wrapInd = wrapInd
  1595. .repl('{title}', caption)
  1596. .repl('{dialog}', "$('#" + id + "').modal('show')");
  1597. strText = strText.substring(0, (wrapLen - 1)) + wrapInd;
  1598. }
  1599. content = tmplt.repl('{previewId}', previewId).repl('{caption}', caption)
  1600. .repl('{frameClass}', '')
  1601. .repl('{type}', file.type).repl('{width}', config.width)
  1602. .repl('{height}', config.height).repl('{data}', strText)
  1603. .repl('{footer}', footer).repl('{fileindex}', ind) + modal;
  1604. } else {
  1605. content = tmplt.repl('{previewId}', previewId).repl('{caption}', caption)
  1606. .repl('{frameClass}', '')
  1607. .repl('{type}', file.type).repl('{data}', data)
  1608. .repl('{width}', config.width).repl('{height}', config.height)
  1609. .repl('{footer}', footer).repl('{fileindex}', ind);
  1610. }
  1611. self.$preview.append("\n" + content);
  1612. self.autoSizeImage(previewId);
  1613. } else {
  1614. self.previewDefault(file, previewId);
  1615. }
  1616. },
  1617. slugDefault: function (text) {
  1618. return isEmpty(text) ? '' : text.split(/(\\|\/)/g).pop().replace(/[^\w\-.\\\/ ]+/g, '');
  1619. },
  1620. getFileStack: function () {
  1621. var self = this;
  1622. return self.filestack.filter(function (n) {
  1623. return n !== undefined;
  1624. });
  1625. },
  1626. readFiles: function (files) {
  1627. this.reader = new FileReader();
  1628. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  1629. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  1630. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  1631. settings = self.fileTypeSettings, ctr = self.filestack.length,
  1632. throwError = function (msg, file, previewId, index) {
  1633. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  1634. p2 = {id: previewId, index: index, file: file, files: files};
  1635. self.previewDefault(file, previewId, true);
  1636. return self.isUploadable ? self.showUploadError(msg, p1) : self.showError(msg, p2);
  1637. };
  1638. function readFile(i) {
  1639. if (isEmpty($el.attr('multiple'))) {
  1640. numFiles = 1;
  1641. }
  1642. if (i >= numFiles) {
  1643. $container.removeClass('loading');
  1644. $status.html('');
  1645. return;
  1646. }
  1647. var node = ctr + i, previewId = previewInitId + "-" + node, isText, file = files[i],
  1648. caption = self.slug(file.name), fileSize = (file.size || 0) / 1000, checkFile, fileExtExpr = '',
  1649. previewData = objUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk,
  1650. fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '),
  1651. fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', ');
  1652. if (!isEmpty(fileExt)) {
  1653. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  1654. }
  1655. fileSize = fileSize.toFixed(2);
  1656. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  1657. msg = self.msgSizeTooLarge.repl('{name}', caption)
  1658. .repl('{size}', fileSize)
  1659. .repl('{maxSize}', self.maxFileSize);
  1660. self.isError = throwError(msg, file, previewId, i);
  1661. return;
  1662. }
  1663. if (!isEmpty(fileTypes) && isArray(fileTypes)) {
  1664. for (j = 0; j < fileTypes.length; j += 1) {
  1665. typ = fileTypes[j];
  1666. checkFile = settings[typ];
  1667. chk = (checkFile !== undefined && checkFile(file.type, caption));
  1668. fileCount += isEmpty(chk) ? 0 : chk.length;
  1669. }
  1670. if (fileCount === 0) {
  1671. msg = self.msgInvalidFileType.repl('{name}', caption).repl('{types}', strTypes);
  1672. self.isError = throwError(msg, file, previewId, i);
  1673. return;
  1674. }
  1675. }
  1676. if (fileCount === 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) {
  1677. chk = caption.match(fileExtExpr);
  1678. fileCount += isEmpty(chk) ? 0 : chk.length;
  1679. if (fileCount === 0) {
  1680. msg = self.msgInvalidFileExtension.repl('{name}', caption).repl('{extensions}',
  1681. strExt);
  1682. self.isError = throwError(msg, file, previewId, i);
  1683. return;
  1684. }
  1685. }
  1686. if (!self.showPreview) {
  1687. self.filestack.push(file);
  1688. setTimeout(readFile(i + 1), 100);
  1689. self.raise('fileloaded', [file, previewId, i, reader]);
  1690. return;
  1691. }
  1692. if ($preview.length > 0 && FileReader !== undefined) {
  1693. $status.html(msgLoading.repl('{index}', i + 1).repl('{files}', numFiles));
  1694. $container.addClass('loading');
  1695. reader.onerror = function (evt) {
  1696. self.errorHandler(evt, caption);
  1697. };
  1698. reader.onload = function (theFile) {
  1699. self.previewFile(file, theFile, previewId, previewData);
  1700. self.initFileActions();
  1701. };
  1702. reader.onloadend = function () {
  1703. msg = msgProgress
  1704. .repl('{index}', i + 1).repl('{files}', numFiles)
  1705. .repl('{percent}', 50).repl('{name}', caption);
  1706. setTimeout(function () {
  1707. $status.html(msg);
  1708. objUrl.revokeObjectURL(previewData);
  1709. }, 100);
  1710. setTimeout(function () {
  1711. readFile(i + 1);
  1712. self.updateFileDetails(numFiles);
  1713. }, 100);
  1714. self.raise('fileloaded', [file, previewId, i, reader]);
  1715. };
  1716. reader.onprogress = function (data) {
  1717. if (data.lengthComputable) {
  1718. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  1719. msg = msgProgress.repl('{index}', i + 1).repl('{files}', numFiles)
  1720. .repl('{percent}', progress).repl('{name}', caption);
  1721. setTimeout(function () {
  1722. $status.html(msg);
  1723. }, 100);
  1724. }
  1725. };
  1726. isText = isSet('text', settings) ? settings.text : defaultFileTypeSettings.text;
  1727. if (isText(file.type, caption)) {
  1728. reader.readAsText(file, self.textEncoding);
  1729. } else {
  1730. reader.readAsArrayBuffer(file);
  1731. }
  1732. } else {
  1733. self.previewDefault(file, previewId);
  1734. setTimeout(function () {
  1735. readFile(i + 1);
  1736. self.updateFileDetails(numFiles);
  1737. }, 100);
  1738. self.raise('fileloaded', [file, previewId, i, reader]);
  1739. }
  1740. self.filestack.push(file);
  1741. }
  1742. readFile(0);
  1743. self.updateFileDetails(numFiles, false);
  1744. },
  1745. updateFileDetails: function (numFiles) {
  1746. var self = this, msgSelected = self.msgSelected, $el = self.$element, fileStack = self.getFileStack(),
  1747. name = $el.val() || (fileStack.length && fileStack[0].name) || '', label = self.slug(name),
  1748. n = self.isUploadable ? fileStack.length : numFiles,
  1749. nFiles = previewCache.count(self.id) + n,
  1750. log = n > 1 ? msgSelected.repl('{n}', nFiles) : label;
  1751. if (self.isError) {
  1752. self.$previewContainer.removeClass('loading');
  1753. self.$previewStatus.html('');
  1754. self.$captionContainer.find('.kv-caption-icon').hide();
  1755. } else {
  1756. self.showFileIcon();
  1757. }
  1758. self.setCaption(log, self.isError);
  1759. self.$container.removeClass('file-input-new file-input-ajax-new');
  1760. if (arguments.length === 1) {
  1761. self.raise('fileselect', [numFiles, label]);
  1762. }
  1763. if (previewCache.count(self.id)) {
  1764. self.initPreviewDeletes();
  1765. }
  1766. },
  1767. change: function (e) {
  1768. var self = this, $el = self.$element;
  1769. if (!self.isUploadable && isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix
  1770. self.fileInputCleared = false;
  1771. return;
  1772. }
  1773. self.fileInputCleared = false;
  1774. var tfiles, msg, total, $preview = self.$preview, isDragDrop = arguments.length > 1,
  1775. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files,
  1776. isSingleUpload = isEmpty($el.attr('multiple')), i = 0, f, m, folders = 0,
  1777. ctr = self.filestack.length, isAjaxUpload = (self.isUploadable && ctr !== 0),
  1778. throwError = function (mesg, file, previewId, index) {
  1779. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  1780. p2 = {id: previewId, index: index, file: file, files: files};
  1781. return self.isUploadable ? self.showUploadError(mesg, p1) : self.showError(mesg, p2);
  1782. };
  1783. self.resetUpload();
  1784. self.hideFileIcon();
  1785. if (self.isUploadable) {
  1786. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  1787. }
  1788. if (isDragDrop) {
  1789. tfiles = [];
  1790. while (files[i]) {
  1791. f = files[i];
  1792. if (!f.type && f.size % 4096 === 0) {
  1793. folders++;
  1794. } else {
  1795. tfiles.push(f);
  1796. }
  1797. i++;
  1798. }
  1799. } else {
  1800. if (e.target.files === undefined) {
  1801. tfiles = e.target && e.target.value ? [
  1802. {name: e.target.value.replace(/^.+\\/, '')}
  1803. ] : [];
  1804. } else {
  1805. tfiles = e.target.files;
  1806. }
  1807. }
  1808. if (isEmpty(tfiles) || tfiles.length === 0) {
  1809. if (!isAjaxUpload) {
  1810. self.clear();
  1811. }
  1812. self.showFolderError(folders);
  1813. self.raise('fileselectnone');
  1814. return;
  1815. }
  1816. self.resetErrors();
  1817. if (!isAjaxUpload || (isSingleUpload && ctr > 0)) {
  1818. if (!self.overwriteInitial && previewCache.count(self.id)) {
  1819. var out = previewCache.out(self.id);
  1820. $preview.html(out.content);
  1821. self.setCaption(out.caption);
  1822. self.initPreviewDeletes();
  1823. } else {
  1824. $preview.html('');
  1825. }
  1826. if (isSingleUpload && ctr > 0) {
  1827. self.filestack = [];
  1828. }
  1829. }
  1830. total = self.isUploadable ? self.getFileStack().length + tfiles.length : tfiles.length;
  1831. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  1832. msg = self.msgFilesTooMany.repl('{m}', self.maxFileCount).repl('{n}', total);
  1833. self.isError = throwError(msg, null, null, null);
  1834. self.$captionContainer.find('.kv-caption-icon').hide();
  1835. self.$caption.html(self.msgValidationError);
  1836. self.setEllipsis();
  1837. self.$container.removeClass('file-input-new file-input-ajax-new');
  1838. return;
  1839. }
  1840. if (!self.isIE9) {
  1841. self.readFiles(tfiles);
  1842. } else {
  1843. self.updateFileDetails(1);
  1844. }
  1845. self.showFolderError(folders);
  1846. if (isAjaxUpload) {
  1847. self.raise('filebatchselected', [self.getFileStack()]);
  1848. } else {
  1849. self.raise('filebatchselected', [tfiles]);
  1850. }
  1851. self.reader = null;
  1852. },
  1853. autoSizeImage: function (previewId) {
  1854. var self = this, $preview = self.$preview,
  1855. $thumb = $preview.find("#" + previewId),
  1856. $img = $thumb.find('img'), w1, w2, $cap;
  1857. if (!$img.length) {
  1858. return;
  1859. }
  1860. $img.on('load', function () {
  1861. w1 = $thumb.width();
  1862. w2 = $preview.width();
  1863. if (w1 > w2) {
  1864. $img.css('width', '100%');
  1865. $thumb.css('width', '97%');
  1866. }
  1867. $cap = $img.closest('.file-preview-frame').find('.file-caption-name');
  1868. if ($cap.length) {
  1869. $cap.width($img.width());
  1870. $cap.attr('title', $cap.text());
  1871. }
  1872. self.raise('fileimageloaded', previewId);
  1873. });
  1874. },
  1875. setCaption: function (content, isError) {
  1876. var self = this, err = isError || false, title, out;
  1877. if (isEmpty(content) || self.$caption.length === 0) {
  1878. return;
  1879. }
  1880. if (err) {
  1881. title = $('<div>' + self.msgValidationError + '</div>').text();
  1882. out = '<span class="' + self.msgValidationErrorClass + '">' +
  1883. self.msgValidationErrorIcon + title + '</span>';
  1884. } else {
  1885. title = $('<div>' + content + '</div>').text();
  1886. out = title + self.getLayoutTemplate('icon');
  1887. }
  1888. self.$caption.html(out);
  1889. self.$caption.attr('title', title);
  1890. self.$captionContainer.find('.file-caption-ellipsis').attr('title', title);
  1891. self.setEllipsis();
  1892. },
  1893. initBrowse: function ($container) {
  1894. var self = this;
  1895. self.$btnFile = $container.find('.btn-file');
  1896. self.$btnFile.append(self.$element);
  1897. },
  1898. createContainer: function () {
  1899. var self = this,
  1900. $container = $(document.createElement("span"))
  1901. .attr({"class": 'file-input file-input-new'})
  1902. .html(self.renderMain());
  1903. self.$element.before($container);
  1904. self.initBrowse($container);
  1905. return $container;
  1906. },
  1907. refreshContainer: function () {
  1908. var self = this, $container = self.$container;
  1909. $container.before(self.$element);
  1910. $container.html(self.renderMain());
  1911. self.initBrowse($container);
  1912. },
  1913. renderMain: function () {
  1914. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : '',
  1915. preview = self.showPreview ? self.getLayoutTemplate('preview').repl('{class}', self.previewClass)
  1916. .repl('{dropClass}', dropCss) : '',
  1917. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  1918. caption = self.captionTemplate.repl('{class}', css + ' kv-fileinput-caption');
  1919. return self.mainTemplate.repl('{class}', self.mainClass)
  1920. .repl('{preview}', preview)
  1921. .repl('{caption}', caption)
  1922. .repl('{upload}', self.renderUpload())
  1923. .repl('{remove}', self.renderRemove())
  1924. .repl('{cancel}', self.renderCancel())
  1925. .repl('{browse}', self.renderBrowse());
  1926. },
  1927. renderBrowse: function () {
  1928. var self = this, css = self.browseClass + ' btn-file', status = '';
  1929. if (self.isDisabled) {
  1930. status = ' disabled ';
  1931. }
  1932. return '<div class="' + css + '"' + status + '> ' + self.browseIcon + self.browseLabel + ' </div>';
  1933. },
  1934. renderRemove: function () {
  1935. var self = this, css = self.removeClass + ' fileinput-remove fileinput-remove-button', status = '';
  1936. if (!self.showRemove) {
  1937. return '';
  1938. }
  1939. if (self.isDisabled) {
  1940. status = ' disabled ';
  1941. }
  1942. return '<button type="button" title="' + self.removeTitle + '" class="' + css + '"' + status + '>' + self.removeIcon + self.removeLabel + '</button>';
  1943. },
  1944. renderCancel: function () {
  1945. var self = this, css = self.cancelClass + ' fileinput-cancel fileinput-cancel-button';
  1946. if (!self.showCancel) {
  1947. return '';
  1948. }
  1949. return '<button type="button" title="' + self.cancelTitle + '" class="hide ' + css + '">' + self.cancelIcon + self.cancelLabel + '</button>';
  1950. },
  1951. renderUpload: function () {
  1952. var self = this, css = self.uploadClass + ' kv-fileinput-upload fileinput-upload-button', content = '', status = '';
  1953. if (!self.showUpload) {
  1954. return '';
  1955. }
  1956. if (self.isDisabled) {
  1957. status = ' disabled ';
  1958. }
  1959. if (!self.isUploadable || self.isDisabled) {
  1960. content = '<button type="submit" title="' + self.uploadTitle + '"class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</button>';
  1961. } else {
  1962. content = '<a href="' + self.uploadUrl + '" title="' + self.uploadTitle + '" class="' + css + '"' + status + '>' + self.uploadIcon + self.uploadLabel + '</a>';
  1963. }
  1964. return content;
  1965. }
  1966. };
  1967. //FileInput plugin definition
  1968. $.fn.fileinput = function (option) {
  1969. if (!hasFileAPISupport() && !isIE(9)) {
  1970. return;
  1971. }
  1972. var args = Array.apply(null, arguments);
  1973. args.shift();
  1974. return this.each(function () {
  1975. var $this = $(this),
  1976. data = $this.data('fileinput'),
  1977. options = typeof option === 'object' && option;
  1978. if (!data) {
  1979. data = new FileInput(this, $.extend({}, $.fn.fileinput.defaults, options, $(this).data()));
  1980. $this.data('fileinput', data);
  1981. }
  1982. if (typeof option === 'string') {
  1983. data[option].apply(data, args);
  1984. }
  1985. });
  1986. };
  1987. $.fn.fileinput.defaults = {
  1988. showCaption: true,
  1989. showPreview: true,
  1990. showRemove: true,
  1991. showUpload: true,
  1992. showCancel: true,
  1993. mainClass: '',
  1994. previewClass: '',
  1995. captionClass: '',
  1996. mainTemplate: null,
  1997. initialCaption: '',
  1998. initialPreview: [],
  1999. initialPreviewDelimiter: '*$$*',
  2000. initialPreviewConfig: [],
  2001. initialPreviewShowDelete: true,
  2002. deleteUrl: '',
  2003. deleteExtraData: {},
  2004. overwriteInitial: true,
  2005. layoutTemplates: defaultLayoutTemplates,
  2006. previewTemplates: defaultPreviewTemplates,
  2007. allowedPreviewTypes: defaultPreviewTypes,
  2008. allowedPreviewMimeTypes: null,
  2009. allowedFileTypes: null,
  2010. allowedFileExtensions: null,
  2011. customLayoutTags: {},
  2012. customPreviewTags: {},
  2013. previewSettings: defaultPreviewSettings,
  2014. fileTypeSettings: defaultFileTypeSettings,
  2015. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  2016. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  2017. browseClass: 'btn btn-primary',
  2018. removeIcon: '<i class="glyphicon glyphicon-trash"></i> ',
  2019. removeClass: 'btn btn-default',
  2020. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  2021. cancelClass: 'btn btn-default',
  2022. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  2023. uploadClass: 'btn btn-default',
  2024. uploadUrl: null,
  2025. uploadAsync: true,
  2026. uploadExtraData: {},
  2027. maxFileSize: 0,
  2028. minFileCount: 0,
  2029. maxFileCount: 0,
  2030. msgValidationErrorClass: 'text-danger',
  2031. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  2032. msgErrorClass: 'file-error-message',
  2033. progressClass: "progress-bar progress-bar-success progress-bar-striped active",
  2034. progressCompleteClass: "progress-bar progress-bar-success",
  2035. previewFileType: 'image',
  2036. wrapTextLength: 250,
  2037. wrapIndicator: ' <span class="wrap-indicator" title="{title}" onclick="{dialog}">[&hellip;]</span>',
  2038. elCaptionContainer: null,
  2039. elCaptionText: null,
  2040. elPreviewContainer: null,
  2041. elPreviewImage: null,
  2042. elPreviewStatus: null,
  2043. elErrorContainer: null,
  2044. slugCallback: null,
  2045. dropZoneEnabled: true,
  2046. dropZoneTitleClass: 'file-drop-zone-title',
  2047. fileActionSettings: {},
  2048. otherActionButtons: '',
  2049. textEncoding: 'UTF-8',
  2050. ajaxSettings: {},
  2051. ajaxDeleteSettings: {},
  2052. showAjaxErrorDetails: true
  2053. };
  2054. $.fn.fileinput.locales = {};
  2055. $.fn.fileinput.locales.en = {
  2056. fileSingle: 'file',
  2057. filePlural: 'files',
  2058. browseLabel: 'Browse &hellip;',
  2059. removeLabel: 'Remove',
  2060. removeTitle: 'Clear selected files',
  2061. cancelLabel: 'Cancel',
  2062. cancelTitle: 'Abort ongoing upload',
  2063. uploadLabel: 'Upload',
  2064. uploadTitle: 'Upload selected files',
  2065. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>. Please retry your upload!',
  2066. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload. Please retry your upload!',
  2067. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>. Please retry your upload!',
  2068. msgFileNotFound: 'File "{name}" not found!',
  2069. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  2070. msgFileNotReadable: 'File "{name}" is not readable.',
  2071. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  2072. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  2073. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  2074. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  2075. msgValidationError: 'File Upload Error',
  2076. msgLoading: 'Loading file {index} of {files} &hellip;',
  2077. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  2078. msgSelected: '{n} files selected',
  2079. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  2080. dropZoneTitle: 'Drag & drop files here &hellip;'
  2081. };
  2082. $.extend($.fn.fileinput.defaults, $.fn.fileinput.locales.en);
  2083. $.fn.fileinput.Constructor = FileInput;
  2084. /**
  2085. * Convert automatically file inputs with class 'file'
  2086. * into a bootstrap fileinput control.
  2087. */
  2088. $(document).ready(function () {
  2089. var $input = $('input.file[type=file]'), count = $input.attr('type') ? $input.length : 0;
  2090. if (count > 0) {
  2091. $input.fileinput();
  2092. }
  2093. });
  2094. })(window.jQuery);