fileinput.js 95 KB

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