fileinput.js 113 KB

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