fileinput.js 95 KB

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