fileinput.js 110 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387
  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. var div = document.createElement("div"), status;
  26. div.innerHTML = "<!--[if IE " + ver + "]> <i></i> <![endif]-->";
  27. status = div.getElementsByTagName("i").length;
  28. document.body.appendChild(div);
  29. div.parentNode.removeChild(div);
  30. if (status) {
  31. return status;
  32. }
  33. return RegExp('msie\\s' + ver, 'i').test(navigator.userAgent);
  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'),
  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. ' {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.ajaxRequests = [];
  511. self.isError = false;
  512. self.ajaxAborted = false;
  513. self.dropZoneEnabled = hasDragDropSupport() && self.dropZoneEnabled;
  514. self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly');
  515. self.isUploadable = hasFileUploadSupport() && !isEmpty(self.uploadUrl);
  516. self.slug = typeof options.slugCallback === "function" ? options.slugCallback : self.slugDefault;
  517. self.mainTemplate = self.showCaption ? self.getLayoutTemplate('main1') : self.getLayoutTemplate('main2');
  518. self.captionTemplate = self.getLayoutTemplate('caption');
  519. self.previewGenericTemplate = self.getPreviewTemplate('generic');
  520. if (isEmpty(self.$element.attr('id'))) {
  521. self.$element.attr('id', uniqId());
  522. }
  523. if (self.$container === undefined) {
  524. self.$container = self.createContainer();
  525. } else {
  526. self.refreshContainer();
  527. }
  528. self.$progress = self.$container.find('.kv-upload-progress');
  529. self.$btnUpload = self.$container.find('.fileinput-upload');
  530. self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption'));
  531. self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name'));
  532. self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview'));
  533. self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails'));
  534. self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status'));
  535. self.$errorContainer = getElement(options, 'elErrorContainer',
  536. self.$previewContainer.find('.kv-fileinput-error'));
  537. if (!isEmpty(self.msgErrorClass)) {
  538. addCss(self.$errorContainer, self.msgErrorClass);
  539. }
  540. self.$errorContainer.hide();
  541. self.fileActionSettings = $.extend(defaultFileActionSettings, options.fileActionSettings);
  542. self.previewInitId = "preview-" + uniqId();
  543. self.id = self.$element.attr('id');
  544. previewCache.init(self);
  545. self.initPreview(true);
  546. self.initPreviewDeletes();
  547. self.options = options;
  548. self.setFileDropZoneTitle();
  549. self.uploadCount = 0;
  550. self.uploadPercent = 0;
  551. self.$element.removeClass('file-loading');
  552. t = self.getLayoutTemplate('progress');
  553. self.progressTemplate = t.replace('{class}', self.progressClass);
  554. self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass);
  555. if (self.$element.attr('disabled')) {
  556. self.disable();
  557. }
  558. },
  559. parseError: function (jqXHR, errorThrown, fileName) {
  560. var self = this, errMsg = $.trim(errorThrown + ''),
  561. dot = errMsg.slice(-1) === '.' ? '' : '.',
  562. text = jqXHR.responseJSON !== undefined && jqXHR.responseJSON.error !== undefined ?
  563. jqXHR.responseJSON.error : jqXHR.responseText;
  564. if (self.showAjaxErrorDetails && text) {
  565. text = $.trim(text.replace(/\n\s*\n/g, '\n'));
  566. text = text.length > 0 ? '<pre>' + text + '</pre>' : '';
  567. errMsg += dot + text;
  568. } else {
  569. errMsg += dot;
  570. }
  571. return fileName ? '<b>' + fileName + ': </b>' + jqXHR : errMsg;
  572. },
  573. raise: function (event, params) {
  574. var self = this, e = $.Event(event);
  575. if (params !== undefined) {
  576. self.$element.trigger(e, params);
  577. } else {
  578. self.$element.trigger(e);
  579. }
  580. if (e.isDefaultPrevented()) {
  581. return false;
  582. }
  583. if (!e.result) {
  584. return e.result;
  585. }
  586. switch (event) {
  587. // ignore these events
  588. case 'filebatchuploadcomplete':
  589. case 'filebatchuploadsuccess':
  590. case 'fileuploaded':
  591. case 'fileclear':
  592. case 'filecleared':
  593. case 'filereset':
  594. case 'fileerror':
  595. case 'filefoldererror':
  596. case 'fileuploaderror':
  597. case 'filebatchuploaderror':
  598. case 'filedeleteerror':
  599. case 'filecustomerror':
  600. case 'filesuccessremove':
  601. break;
  602. // receive data response via `filecustomerror` event`
  603. default:
  604. self.ajaxAborted = e.result;
  605. break;
  606. }
  607. return true;
  608. },
  609. getLayoutTemplate: function (t) {
  610. var self = this,
  611. template = isSet(t, self.layoutTemplates) ? self.layoutTemplates[t] : defaultLayoutTemplates[t];
  612. if (isEmpty(self.customLayoutTags)) {
  613. return template;
  614. }
  615. return replaceTags(template, self.customLayoutTags);
  616. },
  617. getPreviewTemplate: function (t) {
  618. var self = this,
  619. template = isSet(t, self.previewTemplates) ? self.previewTemplates[t] : defaultPreviewTemplates[t];
  620. if (isEmpty(self.customPreviewTags)) {
  621. return template;
  622. }
  623. return replaceTags(template, self.customPreviewTags);
  624. },
  625. parseFilePreviewIcon: function (content, fname) {
  626. var self = this, ext, icn = self.previewFileIcon;
  627. if (fname && fname.indexOf('.') > -1) {
  628. ext = fname.split('.').pop();
  629. if (self.previewFileIconSettings && self.previewFileIconSettings[ext]) {
  630. icn = self.previewFileIconSettings[ext];
  631. }
  632. if (self.previewFileExtSettings) {
  633. $.each(self.previewFileExtSettings, function (key, func) {
  634. if (self.previewFileIconSettings[key] && func(ext)) {
  635. icn = self.previewFileIconSettings[key];
  636. }
  637. });
  638. }
  639. }
  640. if (content.indexOf('{previewFileIcon}') > -1) {
  641. return content.replace(/\{previewFileIconClass\}/g, self.previewFileIconClass).replace(/\{previewFileIcon\}/g, icn);
  642. }
  643. return content;
  644. },
  645. getOutData: function (jqXHR, responseData, filesData) {
  646. var self = this;
  647. jqXHR = jqXHR || {};
  648. responseData = responseData || {};
  649. filesData = filesData || self.filestack.slice(0) || {};
  650. return {
  651. form: self.formdata,
  652. files: filesData,
  653. extra: self.getExtraData(),
  654. response: responseData,
  655. reader: self.reader,
  656. jqXHR: jqXHR
  657. };
  658. },
  659. listen: function () {
  660. var self = this, $el = self.$element, $cap = self.$captionContainer, $btnFile = self.$btnFile,
  661. $form = $el.closest('form'), $cont = self.$container;
  662. handler($el, 'change', $.proxy(self.change, self));
  663. handler($btnFile, 'click', function () {
  664. self.raise('filebrowse');
  665. if (self.isError && !self.isUploadable) {
  666. self.clear();
  667. }
  668. $cap.focus();
  669. });
  670. handler($form, 'reset', $.proxy(self.reset, self));
  671. handler($cont.find('.fileinput-remove:not([disabled])'), 'click', $.proxy(self.clear, self));
  672. handler($cont.find('.fileinput-cancel'), 'click', $.proxy(self.cancel, self));
  673. if (self.isUploadable && self.dropZoneEnabled && self.showPreview) {
  674. self.initDragDrop();
  675. }
  676. if (!self.isUploadable) {
  677. handler($form, 'submit', $.proxy(self.submitForm, self));
  678. }
  679. handler(self.$container.find('.fileinput-upload'), 'click', function (e) {
  680. var $btn = $(this), $form, isEnabled = !$btn.hasClass('disabled') && isEmpty($btn.attr('disabled'));
  681. if (!self.isUploadable) {
  682. if (isEnabled && $btn.attr('type') !== 'submit') {
  683. $form = $btn.closest('form');
  684. // downgrade to normal form submit if possible
  685. if ($form.length) {
  686. $form.trigger('submit');
  687. }
  688. e.preventDefault();
  689. }
  690. return;
  691. }
  692. e.preventDefault();
  693. if (isEnabled) {
  694. self.upload();
  695. }
  696. });
  697. },
  698. submitForm: function () {
  699. var self = this, $el = self.$element, files = $el.get(0).files;
  700. if (files && self.minFileCount > 0 && self.getFileCount(files.length) < self.minFileCount) {
  701. self.noFilesError({});
  702. return false;
  703. }
  704. return !self.abort({});
  705. },
  706. abort: function (params) {
  707. var self = this, data;
  708. if (self.ajaxAborted && typeof self.ajaxAborted === "object" && self.ajaxAborted.message !== undefined) {
  709. data = $.extend(self.getOutData(), params);
  710. data.abortData = self.ajaxAborted.data || {};
  711. data.abortMessage = self.ajaxAborted.message;
  712. self.cancel();
  713. self.setProgress(100);
  714. self.showUploadError(self.ajaxAborted.message, data, 'filecustomerror');
  715. return true;
  716. }
  717. return false;
  718. },
  719. noFilesError: function (params) {
  720. var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle,
  721. msg = self.msgFilesTooLess.replace('{n}', self.minFileCount).replace('{files}', label),
  722. $error = self.$errorContainer;
  723. self.addError(msg);
  724. self.isError = true;
  725. self.updateFileDetails(0);
  726. $error.fadeIn(800);
  727. self.raise('fileerror', [params]);
  728. self.clearFileInput();
  729. addCss(self.$container, 'has-error');
  730. },
  731. setProgress: function (p) {
  732. var self = this, pct = Math.min(p, 100),
  733. template = pct < 100 ? self.progressTemplate : self.progressCompleteTemplate;
  734. if (!isEmpty(template)) {
  735. self.$progress.html(template.replace(/\{percent\}/g, pct));
  736. }
  737. },
  738. upload: function () {
  739. var self = this, totLen = self.getFileStack().length, params = {},
  740. i, outData, len, hasExtraData = !$.isEmptyObject(self.getExtraData());
  741. if (self.minFileCount > 0 && self.getFileCount(totLen) < self.minFileCount) {
  742. self.noFilesError(params);
  743. return;
  744. }
  745. if (!self.isUploadable || self.isDisabled || (totLen === 0 && !hasExtraData)) {
  746. return;
  747. }
  748. self.resetUpload();
  749. self.$progress.removeClass('hide');
  750. self.uploadCount = 0;
  751. self.uploadPercent = 0;
  752. self.lock();
  753. self.setProgress(0);
  754. if (totLen === 0 && hasExtraData) {
  755. self.uploadExtraOnly();
  756. return;
  757. }
  758. len = self.filestack.length;
  759. self.hasInitData = false;
  760. if (self.uploadAsync && self.showPreview) {
  761. outData = self.getOutData();
  762. self.raise('filebatchpreupload', [outData]);
  763. self.fileBatchCompleted = false;
  764. self.uploadCache = {content: [], config: [], tags: [], append: true};
  765. for (i = 0; i < len; i += 1) {
  766. if (self.filestack[i] !== undefined) {
  767. self.uploadSingle(i, self.filestack, true);
  768. }
  769. }
  770. return;
  771. }
  772. self.uploadBatch();
  773. },
  774. lock: function () {
  775. var self = this;
  776. self.resetErrors();
  777. self.disable();
  778. if (self.showRemove) {
  779. addCss(self.$container.find('.fileinput-remove'), 'hide');
  780. }
  781. if (self.showCancel) {
  782. self.$container.find('.fileinput-cancel').removeClass('hide');
  783. }
  784. self.raise('filelock', [self.filestack, self.getExtraData()]);
  785. },
  786. unlock: function (reset) {
  787. var self = this;
  788. if (reset === undefined) {
  789. reset = true;
  790. }
  791. self.enable();
  792. if (self.showCancel) {
  793. addCss(self.$container.find('.fileinput-cancel'), 'hide');
  794. }
  795. if (self.showRemove) {
  796. self.$container.find('.fileinput-remove').removeClass('hide');
  797. }
  798. if (reset) {
  799. self.resetFileStack();
  800. }
  801. self.raise('fileunlock', [self.filestack, self.getExtraData()]);
  802. },
  803. resetFileStack: function () {
  804. var self = this, i = 0, newstack = [];
  805. self.getThumbs().each(function () {
  806. var $thumb = $(this), ind = $thumb.attr('data-fileindex'),
  807. file = self.filestack[ind];
  808. if (ind === -1) {
  809. return;
  810. }
  811. if (file !== undefined) {
  812. newstack[i] = file;
  813. $thumb.attr({
  814. 'id': self.previewInitId + '-' + i,
  815. 'data-fileindex': i
  816. });
  817. i += 1;
  818. } else {
  819. $thumb.attr({
  820. 'id': 'uploaded-' + uniqId(),
  821. 'data-fileindex': '-1'
  822. });
  823. }
  824. });
  825. self.filestack = newstack;
  826. },
  827. destroy: function () {
  828. var self = this, $cont = self.$container;
  829. $cont.find('.file-drop-zone').off();
  830. self.$element.insertBefore($cont).off('.fileinput').removeData();
  831. $cont.off().remove();
  832. },
  833. refresh: function (options) {
  834. var self = this, $el = self.$element;
  835. options = options ? $.extend(self.options, options) : self.options;
  836. self.destroy();
  837. $el.fileinput(options);
  838. if ($el.val()) {
  839. $el.trigger('change.fileinput');
  840. }
  841. },
  842. initDragDrop: function () {
  843. var self = this, $zone = self.$container.find('.file-drop-zone'),
  844. allEvents = 'dragenter.fileinput dragover.fileinput drop.fileinput';
  845. handler($zone, 'dragenter.fileinput dragover.fileinput', function (e) {
  846. var hasFiles = $.inArray('Files', e.originalEvent.dataTransfer.types) > -1;
  847. e.stopPropagation();
  848. e.preventDefault();
  849. if (self.isDisabled || !hasFiles) {
  850. e.originalEvent.dataTransfer.effectAllowed = 'none';
  851. e.originalEvent.dataTransfer.dropEffect = 'none';
  852. return;
  853. }
  854. addCss($(this), 'highlighted');
  855. }, true);
  856. handler($zone, 'dragleave', function (e) {
  857. e.stopPropagation();
  858. e.preventDefault();
  859. if (self.isDisabled) {
  860. return;
  861. }
  862. $(this).removeClass('highlighted');
  863. });
  864. handler($zone, 'drop', function (e) {
  865. e.preventDefault();
  866. if (self.isDisabled || isEmpty(e.originalEvent.dataTransfer.files)) {
  867. return;
  868. }
  869. self.change(e, 'dragdrop');
  870. $(this).removeClass('highlighted');
  871. });
  872. handler($(document), allEvents, function (e) {
  873. e.stopPropagation();
  874. e.preventDefault();
  875. }, true);
  876. },
  877. setFileDropZoneTitle: function () {
  878. var self = this, $zone = self.$container.find('.file-drop-zone');
  879. $zone.find('.' + self.dropZoneTitleClass).remove();
  880. if (!self.isUploadable || !self.showPreview || $zone.length === 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled) {
  881. return;
  882. }
  883. if ($zone.find('.file-preview-frame').length === 0) {
  884. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + self.dropZoneTitle + '</div>');
  885. }
  886. self.$container.removeClass('file-input-new');
  887. addCss(self.$container, 'file-input-ajax-new');
  888. },
  889. initFileActions: function () {
  890. var self = this;
  891. self.$preview.find('.kv-file-remove').each(function () {
  892. var $el = $(this), $frame = $el.closest('.file-preview-frame'), hasError,
  893. id = $frame.attr('id'), ind = $frame.attr('data-fileindex'), n, cap, status;
  894. handler($el, 'click', function (event) {
  895. status = self.raise('filepreremove', [id, ind]);
  896. if (status === false || !self.validateMinCount()) {
  897. return false;
  898. }
  899. hasError = $frame.hasClass('file-preview-error');
  900. self.cleanMemory($frame);
  901. $frame.fadeOut('slow', function () {
  902. self.filestack[ind] = undefined;
  903. self.clearObjects($frame);
  904. $frame.remove();
  905. if (id && hasError) {
  906. self.$errorContainer.find('li[data-file-id="' + id + '"]').fadeOut('fast', function() {
  907. $(this).remove();
  908. if (!self.$errorContainer.find('li').length &&
  909. !self.$preview.find('.file-preview-frame.file-preview-error').length) {
  910. self.resetErrors();
  911. }
  912. });
  913. }
  914. var filestack = self.getFileStack(true), len = filestack.length, chk = previewCache.count(self.id),
  915. hasThumb = self.showPreview && self.$preview.find('.file-preview-frame').length;
  916. self.clearFileInput();
  917. if (len === 0 && chk === 0 && !hasThumb) {
  918. self.reset();
  919. } else {
  920. n = chk + len;
  921. cap = n > 1 ? self.getMsgSelected(n) : (filestack[0] ? filestack[0].name : '');
  922. self.setCaption(cap);
  923. }
  924. self.raise('fileremoved', [id, ind]);
  925. });
  926. });
  927. });
  928. self.$preview.find('.kv-file-upload').each(function () {
  929. var $el = $(this);
  930. handler($el, 'click', function () {
  931. var $frame = $el.closest('.file-preview-frame'),
  932. ind = $frame.attr('data-fileindex');
  933. if (!$frame.hasClass('file-preview-error')) {
  934. self.uploadSingle(ind, self.filestack, false);
  935. }
  936. });
  937. });
  938. },
  939. getMsgSelected: function (n) {
  940. var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural;
  941. return self.msgSelected.replace('{n}', n).replace('{files}', strFiles);
  942. },
  943. renderFileFooter: function (caption, width) {
  944. var self = this, config = self.fileActionSettings, footer, out,
  945. template = self.getLayoutTemplate('footer');
  946. if (self.isUploadable) {
  947. footer = template.replace(/\{actions\}/g, self.renderFileActions(true, true, false, false, false));
  948. out = footer.replace(/\{caption\}/g, caption)
  949. .replace(/\{width\}/g, width)
  950. .replace(/\{indicator\}/g, config.indicatorNew)
  951. .replace(/\{indicatorTitle\}/g, config.indicatorNewTitle);
  952. } else {
  953. out = template.replace(/\{actions\}/g, '')
  954. .replace(/\{caption\}/g, caption)
  955. .replace(/\{width\}/g, width)
  956. .replace(/\{indicator\}/g, '')
  957. .replace(/\{indicatorTitle\}/g, '');
  958. }
  959. out = replaceTags(out, self.previewThumbTags);
  960. return out;
  961. },
  962. renderFileActions: function (showUpload, showDelete, disabled, url, key) {
  963. if (!showUpload && !showDelete) {
  964. return '';
  965. }
  966. var self = this,
  967. vUrl = url === false ? '' : ' data-url="' + url + '"',
  968. vKey = key === false ? '' : ' data-key="' + key + '"',
  969. btnDelete = self.getLayoutTemplate('actionDelete'),
  970. btnUpload = '',
  971. template = self.getLayoutTemplate('actions'),
  972. otherButtons = self.otherActionButtons.replace(/\{dataKey\}/g, vKey),
  973. config = self.fileActionSettings,
  974. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  975. btnDelete = btnDelete
  976. .replace(/\{removeClass\}/g, removeClass)
  977. .replace(/\{removeIcon\}/g, config.removeIcon)
  978. .replace(/\{removeTitle\}/g, config.removeTitle)
  979. .replace(/\{dataUrl\}/g, vUrl)
  980. .replace(/\{dataKey\}/g, vKey);
  981. if (showUpload) {
  982. btnUpload = self.getLayoutTemplate('actionUpload')
  983. .replace(/\{uploadClass\}/g, config.uploadClass)
  984. .replace(/\{uploadIcon\}/g, config.uploadIcon)
  985. .replace(/\{uploadTitle\}/g, config.uploadTitle);
  986. }
  987. return template
  988. .replace(/\{delete\}/g, btnDelete)
  989. .replace(/\{upload\}/g, btnUpload)
  990. .replace(/\{other\}/g, otherButtons);
  991. },
  992. setThumbStatus: function ($thumb, status) {
  993. var self = this, icon = 'indicator' + status, msg = icon + 'Title',
  994. css = 'file-preview-' + status.toLowerCase(),
  995. $indicator = $thumb.find('.file-upload-indicator'),
  996. config = self.fileActionSettings;
  997. $thumb.removeClass('file-preview-success file-preview-error file-preview-loading');
  998. if (status === 'Error') {
  999. $thumb.find('.kv-file-upload').attr('disabled', true);
  1000. addCss($thumb, 'btn disabled');
  1001. }
  1002. $indicator.html(config[icon]);
  1003. $indicator.attr('title', config[msg]);
  1004. $thumb.addClass(css);
  1005. },
  1006. clearPreview: function () {
  1007. var self = this, $thumbs = !self.showUploadedThumbs ? self.$preview.find('.file-preview-frame') :
  1008. self.$preview.find('.file-preview-frame:not(.file-preview-success)');
  1009. $thumbs.remove();
  1010. if (!self.$preview.find('.file-preview-frame').length || !self.showPreview) {
  1011. self.resetUpload();
  1012. }
  1013. },
  1014. initPreview: function (isInit) {
  1015. var self = this, cap = self.initialCaption || '', out;
  1016. if (!previewCache.count(self.id)) {
  1017. self.clearPreview();
  1018. if (isInit) {
  1019. self.setCaption(cap);
  1020. } else {
  1021. self.initCaption();
  1022. }
  1023. return;
  1024. }
  1025. out = previewCache.out(self.id);
  1026. cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
  1027. self.$preview.html(out.content);
  1028. self.setCaption(cap);
  1029. if (!isEmpty(out.content)) {
  1030. self.$container.removeClass('file-input-new');
  1031. }
  1032. },
  1033. initPreviewDeletes: function () {
  1034. var self = this, deleteExtraData = self.deleteExtraData || {},
  1035. resetProgress = function () {
  1036. var hasFiles = self.isUploadable ? previewCache.count(self.id) : self.$element.get(0).files.length;
  1037. if (self.$preview.find('.kv-file-remove').length === 0 && !hasFiles) {
  1038. self.reset();
  1039. self.initialCaption = '';
  1040. }
  1041. };
  1042. self.$preview.find('.kv-file-remove').each(function () {
  1043. var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key');
  1044. if (isEmpty(vUrl) || vKey === undefined) {
  1045. return;
  1046. }
  1047. var $frame = $el.closest('.file-preview-frame'), cache = previewCache.data[self.id],
  1048. settings, params, index = $frame.data('fileindex'), config, extraData;
  1049. index = parseInt(index.replace('init_', ''));
  1050. config = isEmpty(cache.config) && isEmpty(cache.config[index]) ? null : cache.config[index];
  1051. extraData = isEmpty(config) || isEmpty(config.extra) ? deleteExtraData : config.extra;
  1052. if (typeof extraData === "function") {
  1053. extraData = extraData();
  1054. }
  1055. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  1056. settings = $.extend({
  1057. url: vUrl,
  1058. type: 'POST',
  1059. dataType: 'json',
  1060. data: $.extend({key: vKey}, extraData),
  1061. beforeSend: function (jqXHR) {
  1062. self.ajaxAborted = false;
  1063. self.raise('filepredelete', [vKey, jqXHR, extraData]);
  1064. if (self.ajaxAborted) {
  1065. jqXHR.abort();
  1066. } else {
  1067. addCss($frame, 'file-uploading');
  1068. addCss($el, 'disabled');
  1069. }
  1070. },
  1071. success: function (data, textStatus, jqXHR) {
  1072. var n, cap;
  1073. if (isEmpty(data) || isEmpty(data.error)) {
  1074. previewCache.unset(self.id, index);
  1075. n = previewCache.count(self.id);
  1076. cap = n > 0 ? self.getMsgSelected(n) : '';
  1077. self.raise('filedeleted', [vKey, jqXHR, extraData]);
  1078. self.setCaption(cap);
  1079. } else {
  1080. params.jqXHR = jqXHR;
  1081. params.response = data;
  1082. self.showError(data.error, params, 'filedeleteerror');
  1083. $frame.removeClass('file-uploading');
  1084. $el.removeClass('disabled');
  1085. resetProgress();
  1086. return;
  1087. }
  1088. $frame.removeClass('file-uploading').addClass('file-deleted');
  1089. $frame.fadeOut('slow', function () {
  1090. self.clearObjects($frame);
  1091. $frame.remove();
  1092. resetProgress();
  1093. if (!n && self.getFileStack().length === 0) {
  1094. self.setCaption('');
  1095. self.reset();
  1096. }
  1097. });
  1098. },
  1099. error: function (jqXHR, textStatus, errorThrown) {
  1100. var errMsg = self.parseError(jqXHR, errorThrown);
  1101. params.jqXHR = jqXHR;
  1102. params.response = {};
  1103. self.showError(errMsg, params, 'filedeleteerror');
  1104. $frame.removeClass('file-uploading');
  1105. resetProgress();
  1106. }
  1107. }, self.ajaxDeleteSettings);
  1108. handler($el, 'click', function () {
  1109. if (!self.validateMinCount()) {
  1110. return false;
  1111. }
  1112. $.ajax(settings);
  1113. });
  1114. });
  1115. },
  1116. clearObjects: function ($el) {
  1117. $el.find('video audio').each(function () {
  1118. this.pause();
  1119. $(this).remove();
  1120. });
  1121. $el.find('img object div').each(function () {
  1122. $(this).remove();
  1123. });
  1124. },
  1125. clearFileInput: function () {
  1126. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  1127. if (isEmpty($el.val())) {
  1128. return;
  1129. }
  1130. // Fix for IE ver < 11, that does not clear file inputs
  1131. // Requires a sequence of steps to prevent IE crashing but
  1132. // still allow clearing of the file input.
  1133. if (self.isIE9 || self.isIE10) {
  1134. $srcFrm = $el.closest('form');
  1135. $tmpFrm = $(document.createElement('form'));
  1136. $tmpEl = $(document.createElement('div'));
  1137. $el.before($tmpEl);
  1138. if ($srcFrm.length) {
  1139. $srcFrm.after($tmpFrm);
  1140. } else {
  1141. $tmpEl.after($tmpFrm);
  1142. }
  1143. $tmpFrm.append($el).trigger('reset');
  1144. $tmpEl.before($el).remove();
  1145. $tmpFrm.remove();
  1146. } else { // normal input clear behavior for other sane browsers
  1147. $el.val('');
  1148. }
  1149. self.fileInputCleared = true;
  1150. },
  1151. resetUpload: function () {
  1152. var self = this;
  1153. self.uploadCache = {content: [], config: [], tags: [], append: true};
  1154. self.uploadCount = 0;
  1155. self.uploadPercent = 0;
  1156. self.$btnUpload.removeAttr('disabled');
  1157. self.setProgress(0);
  1158. addCss(self.$progress, 'hide');
  1159. self.resetErrors(false);
  1160. self.ajaxAborted = false;
  1161. self.ajaxRequests = [];
  1162. },
  1163. cancel: function () {
  1164. var self = this, xhr = self.ajaxRequests, len = xhr.length, i;
  1165. if (len > 0) {
  1166. for (i = 0; i < len; i += 1) {
  1167. xhr[i].abort();
  1168. }
  1169. }
  1170. self.getThumbs().each(function () {
  1171. var $thumb = $(this), ind = $thumb.attr('data-fileindex');
  1172. $thumb.removeClass('file-uploading');
  1173. if (self.filestack[ind] !== undefined) {
  1174. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  1175. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  1176. }
  1177. self.unlock();
  1178. });
  1179. },
  1180. cleanMemory: function ($thumb) {
  1181. var data = $thumb.is('img') ? $thumb.attr('src') : $thumb.find('source').attr('src');
  1182. objUrl.revokeObjectURL(data);
  1183. },
  1184. hasInitialPreview: function () {
  1185. var self = this;
  1186. return !self.overwriteInitial && previewCache.count(self.id);
  1187. },
  1188. clear: function () {
  1189. var self = this, cap;
  1190. self.$btnUpload.removeAttr('disabled');
  1191. self.getThumbs().find('video,audio,img').each(function () {
  1192. self.cleanMemory($(this));
  1193. });
  1194. self.resetUpload();
  1195. self.filestack = [];
  1196. self.clearFileInput();
  1197. self.resetErrors(true);
  1198. self.raise('fileclear');
  1199. if (self.hasInitialPreview()) {
  1200. self.showFileIcon();
  1201. self.resetPreview();
  1202. self.initPreviewDeletes();
  1203. self.$container.removeClass('file-input-new');
  1204. } else {
  1205. self.getThumbs().each(function () {
  1206. self.clearObjects($(this));
  1207. });
  1208. if (self.isUploadable) {
  1209. previewCache.data[self.id] = {};
  1210. }
  1211. self.$preview.html('');
  1212. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  1213. self.setCaption(cap);
  1214. self.$caption.attr('title', '');
  1215. addCss(self.$container, 'file-input-new');
  1216. }
  1217. if (self.$container.find('.file-preview-frame').length === 0) {
  1218. if (!self.initCaption()) {
  1219. self.$captionContainer.find('.kv-caption-icon').hide();
  1220. }
  1221. }
  1222. self.hideFileIcon();
  1223. self.raise('filecleared');
  1224. self.$captionContainer.focus();
  1225. self.setFileDropZoneTitle();
  1226. },
  1227. resetPreview: function () {
  1228. var self = this, out, cap;
  1229. if (previewCache.count(self.id)) {
  1230. out = previewCache.out(self.id);
  1231. self.$preview.html(out.content);
  1232. cap = self.initialCaption ? self.initialCaption : out.caption;
  1233. self.setCaption(cap);
  1234. } else {
  1235. self.clearPreview();
  1236. self.initCaption();
  1237. }
  1238. },
  1239. resetPreviewThumbs: function (isAjax) {
  1240. var self = this, out;
  1241. if (isAjax) {
  1242. self.clearPreview();
  1243. self.filestack = [];
  1244. return;
  1245. }
  1246. if (self.hasInitialPreview()) {
  1247. out = previewCache.out(self.id);
  1248. self.$preview.html(out.content);
  1249. self.setCaption(out.caption);
  1250. self.initPreviewDeletes();
  1251. } else {
  1252. self.clearPreview();
  1253. }
  1254. },
  1255. reset: function () {
  1256. var self = this;
  1257. self.resetPreview();
  1258. self.$container.find('.fileinput-filename').text('');
  1259. self.raise('filereset');
  1260. addCss(self.$container, 'file-input-new');
  1261. if (self.$preview.find('.file-preview-frame').length || self.isUploadable && self.dropZoneEnabled) {
  1262. self.$container.removeClass('file-input-new');
  1263. }
  1264. self.setFileDropZoneTitle();
  1265. self.filestack = [];
  1266. self.formdata = {};
  1267. },
  1268. disable: function () {
  1269. var self = this;
  1270. self.isDisabled = true;
  1271. self.raise('filedisabled');
  1272. self.$element.attr('disabled', 'disabled');
  1273. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  1274. self.$container.find(".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").attr("disabled",
  1275. true);
  1276. self.initDragDrop();
  1277. },
  1278. enable: function () {
  1279. var self = this;
  1280. self.isDisabled = false;
  1281. self.raise('fileenabled');
  1282. self.$element.removeAttr('disabled');
  1283. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  1284. self.$container.find(".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").removeAttr("disabled");
  1285. self.initDragDrop();
  1286. },
  1287. getThumbs: function (css) {
  1288. css = css || '';
  1289. return this.$preview.find('.file-preview-frame:not(.file-preview-initial)' + css);
  1290. },
  1291. getExtraData: function (previewId, index) {
  1292. var self = this, data = self.uploadExtraData;
  1293. if (typeof self.uploadExtraData === "function") {
  1294. data = self.uploadExtraData(previewId, index);
  1295. }
  1296. return data;
  1297. },
  1298. uploadExtra: function (previewId, index) {
  1299. var self = this, data = self.getExtraData(previewId, index);
  1300. if (data.length === 0) {
  1301. return;
  1302. }
  1303. $.each(data, function (key, value) {
  1304. self.formdata.append(key, value);
  1305. });
  1306. },
  1307. initXhr: function (xhrobj, factor) {
  1308. var self = this;
  1309. if (xhrobj.upload) {
  1310. xhrobj.upload.addEventListener('progress', function (event) {
  1311. var pct = 0, position = event.loaded || event.position, total = event.total;
  1312. if (event.lengthComputable) {
  1313. pct = Math.ceil(position / total * factor);
  1314. }
  1315. self.uploadPercent = Math.max(pct, self.uploadPercent);
  1316. self.setProgress(self.uploadPercent);
  1317. }, false);
  1318. }
  1319. return xhrobj;
  1320. },
  1321. ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, previewId, index) {
  1322. var self = this, settings;
  1323. self.raise('filepreajax', [previewId, index]);
  1324. self.uploadExtra(previewId, index);
  1325. settings = $.extend({
  1326. xhr: function () {
  1327. var xhrobj = $.ajaxSettings.xhr();
  1328. return self.initXhr(xhrobj, 98);
  1329. },
  1330. url: self.uploadUrl,
  1331. type: 'POST',
  1332. dataType: 'json',
  1333. data: self.formdata,
  1334. cache: false,
  1335. processData: false,
  1336. contentType: false,
  1337. beforeSend: fnBefore,
  1338. success: fnSuccess,
  1339. complete: fnComplete,
  1340. error: fnError
  1341. }, self.ajaxSettings);
  1342. self.ajaxRequests.push($.ajax(settings));
  1343. },
  1344. initUploadSuccess: function (out, $thumb, allFiles) {
  1345. var self = this, append, data, index, $newThumb, content, config, tags;
  1346. if (typeof out !== 'object' || $.isEmptyObject(out)) {
  1347. return;
  1348. }
  1349. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  1350. self.hasInitData = true;
  1351. content = out.initialPreview || [];
  1352. config = out.initialPreviewConfig || [];
  1353. tags = out.initialPreviewThumbTags || [];
  1354. append = out.append === undefined || out.append ? true : false;
  1355. self.overwriteInitial = false;
  1356. if ($thumb !== undefined && !allFiles) {
  1357. index = previewCache.add(self.id, content, config[0], tags[0], append);
  1358. data = previewCache.get(self.id, index, false);
  1359. $newThumb = $(data).hide();
  1360. $thumb.after($newThumb).fadeOut('slow', function () {
  1361. $newThumb.fadeIn('slow').css('display:inline-block');
  1362. self.initPreviewDeletes();
  1363. self.clearFileInput();
  1364. $thumb.remove();
  1365. });
  1366. } else {
  1367. if (allFiles) {
  1368. self.uploadCache.content.push(content[0]);
  1369. self.uploadCache.config.push(config[0]);
  1370. self.uploadCache.tags.push(tags[0]);
  1371. self.uploadCache.append = append;
  1372. } else {
  1373. previewCache.set(self.id, content, config, tags, append);
  1374. self.initPreview();
  1375. self.initPreviewDeletes();
  1376. }
  1377. }
  1378. }
  1379. },
  1380. initSuccessThumbs: function () {
  1381. var self = this;
  1382. self.getThumbs('.file-preview-success').each(function () {
  1383. var $thumb = $(this), $remove = $thumb.find('.kv-file-remove');
  1384. $remove.removeAttr('disabled');
  1385. handler($remove, 'click', function () {
  1386. var out = self.raise('filesuccessremove', [$thumb.attr('id'), $thumb.data('fileindex')]);
  1387. self.cleanMemory($thumb);
  1388. if (out === false) {
  1389. return;
  1390. }
  1391. $thumb.fadeOut('slow', function () {
  1392. $thumb.remove();
  1393. if (!self.$preview.find('.file-preview-frame').length) {
  1394. self.reset();
  1395. }
  1396. });
  1397. });
  1398. });
  1399. },
  1400. uploadSingle: function (i, files, allFiles) {
  1401. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  1402. previewId = self.previewInitId + "-" + i, $thumb = $('#' + previewId + ':not(.file-preview-initial)'),
  1403. pct, chkComplete, $btnUpload = $thumb.find('.kv-file-upload'), $btnDelete = $thumb.find('.kv-file-remove'),
  1404. updateProgress, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1405. resetActions, fnBefore, fnSuccess, fnComplete, fnError, params = {id: previewId, index: i};
  1406. self.formdata = formdata;
  1407. if (total === 0 || !hasPostData || $btnUpload.hasClass('disabled') || self.abort(params)) {
  1408. return;
  1409. }
  1410. chkComplete = function () {
  1411. var $thumbs = self.getThumbs('.file-uploading');
  1412. if ($thumbs.length > 0 || self.fileBatchCompleted) {
  1413. return;
  1414. }
  1415. self.fileBatchCompleted = true;
  1416. setTimeout(function () {
  1417. previewCache.set(self.id, self.uploadCache.content, self.uploadCache.config, self.uploadCache.tags,
  1418. self.uploadCache.append);
  1419. if (self.hasInitData) {
  1420. self.initPreview();
  1421. self.initPreviewDeletes();
  1422. }
  1423. self.setProgress(100);
  1424. self.unlock();
  1425. self.clearFileInput();
  1426. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1427. }, 100);
  1428. };
  1429. updateProgress = function () {
  1430. if (!allFiles || total === 0 || self.uploadPercent >= 100) {
  1431. return;
  1432. }
  1433. self.uploadCount += 1;
  1434. pct = 80 + Math.ceil(self.uploadCount * 20 / total);
  1435. self.uploadPercent = Math.max(pct, self.uploadPercent);
  1436. self.setProgress(self.uploadPercent);
  1437. self.initPreviewDeletes();
  1438. };
  1439. resetActions = function () {
  1440. $btnUpload.removeAttr('disabled');
  1441. $btnDelete.removeAttr('disabled');
  1442. $thumb.removeClass('file-uploading');
  1443. };
  1444. fnBefore = function (jqXHR) {
  1445. outData = self.getOutData(jqXHR);
  1446. if (!$thumb.hasClass('file-preview-success')) {
  1447. self.setThumbStatus($thumb, 'Loading');
  1448. addCss($thumb, 'file-uploading');
  1449. }
  1450. $btnUpload.attr('disabled', true);
  1451. $btnDelete.attr('disabled', true);
  1452. if (!allFiles) {
  1453. self.lock();
  1454. }
  1455. self.raise('filepreupload', [outData, previewId, i]);
  1456. params = $.extend(params, outData);
  1457. if (self.abort(params)) {
  1458. jqXHR.abort();
  1459. self.setProgress(100);
  1460. }
  1461. };
  1462. fnSuccess = function (data, textStatus, jqXHR) {
  1463. outData = self.getOutData(jqXHR, data);
  1464. params = $.extend(params, outData);
  1465. setTimeout(function () {
  1466. if (isEmpty(data) || isEmpty(data.error)) {
  1467. self.setThumbStatus($thumb, 'Success');
  1468. $btnUpload.hide();
  1469. self.filestack[i] = undefined;
  1470. self.raise('fileuploaded', [outData, previewId, i]);
  1471. self.initUploadSuccess(data, $thumb, allFiles);
  1472. if (!allFiles) {
  1473. self.resetFileStack();
  1474. }
  1475. } else {
  1476. self.setThumbStatus($thumb, 'Error');
  1477. self.showUploadError(data.error, params);
  1478. }
  1479. }, 100);
  1480. };
  1481. fnComplete = function () {
  1482. setTimeout(function () {
  1483. updateProgress();
  1484. resetActions();
  1485. if (!allFiles) {
  1486. self.unlock(false);
  1487. } else {
  1488. chkComplete();
  1489. }
  1490. self.initSuccessThumbs();
  1491. }, 100);
  1492. };
  1493. fnError = function (jqXHR, textStatus, errorThrown) {
  1494. var errMsg = self.parseError(jqXHR, errorThrown, (allFiles ? files[i].name : null));
  1495. self.setThumbStatus($thumb, 'Error');
  1496. params = $.extend(params, self.getOutData(jqXHR));
  1497. self.showUploadError(errMsg, params);
  1498. };
  1499. formdata.append(self.uploadFileAttr, files[i]);
  1500. formdata.append('file_id', i);
  1501. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, previewId, i);
  1502. },
  1503. uploadBatch: function () {
  1504. var self = this, files = self.filestack, total = files.length, params = {},
  1505. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1506. setAllUploaded, fnBefore, fnSuccess, fnComplete, fnError;
  1507. self.formdata = new FormData();
  1508. if (total === 0 || !hasPostData || self.abort(params)) {
  1509. return;
  1510. }
  1511. setAllUploaded = function () {
  1512. $.each(files, function (key) {
  1513. self.filestack[key] = undefined;
  1514. });
  1515. self.clearFileInput();
  1516. };
  1517. fnBefore = function (jqXHR) {
  1518. self.lock();
  1519. var outData = self.getOutData(jqXHR);
  1520. if (self.showPreview) {
  1521. self.getThumbs().each(function () {
  1522. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  1523. $btnDelete = $thumb.find('.kv-file-remove');
  1524. if (!$thumb.hasClass('file-preview-success')) {
  1525. self.setThumbStatus($thumb, 'Loading');
  1526. addCss($thumb, 'file-uploading');
  1527. }
  1528. $btnUpload.attr('disabled', true);
  1529. $btnDelete.attr('disabled', true);
  1530. });
  1531. }
  1532. self.raise('filebatchpreupload', [outData]);
  1533. if (self.abort(outData)) {
  1534. jqXHR.abort();
  1535. self.setProgress(100);
  1536. }
  1537. };
  1538. fnSuccess = function (data, textStatus, jqXHR) {
  1539. var outData = self.getOutData(jqXHR, data), $thumbs = self.getThumbs(), key = 0;
  1540. keys = isEmpty(data) || isEmpty(data.errorkeys) ? [] : data.errorkeys;
  1541. if (isEmpty(data) || isEmpty(data.error)) {
  1542. self.raise('filebatchuploadsuccess', [outData]);
  1543. setAllUploaded();
  1544. if (self.showPreview) {
  1545. $thumbs.each(function () {
  1546. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload');
  1547. $thumb.find('.kv-file-upload').hide();
  1548. self.setThumbStatus($thumb, 'Success');
  1549. $thumb.removeClass('file-uploading');
  1550. $btnUpload.removeAttr('disabled');
  1551. });
  1552. self.initUploadSuccess(data);
  1553. } else {
  1554. self.reset();
  1555. }
  1556. } else {
  1557. if (self.showPreview) {
  1558. $thumbs.each(function () {
  1559. var $thumb = $(this), $btnDelete = $thumb.find('.kv-file-remove'),
  1560. $btnUpload = $thumb.find('.kv-file-upload');
  1561. $thumb.removeClass('file-uploading');
  1562. $btnUpload.removeAttr('disabled');
  1563. $btnDelete.removeAttr('disabled');
  1564. if (keys.length === 0) {
  1565. self.setThumbStatus($thumb, 'Error');
  1566. return;
  1567. }
  1568. if ($.inArray(key, keys) !== -1) {
  1569. self.setThumbStatus($thumb, 'Error');
  1570. } else {
  1571. $thumb.find('.kv-file-upload').hide();
  1572. self.setThumbStatus($thumb, 'Success');
  1573. self.filestack[key] = undefined;
  1574. }
  1575. key++;
  1576. });
  1577. self.initUploadSuccess(data);
  1578. }
  1579. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1580. }
  1581. };
  1582. fnComplete = function () {
  1583. self.setProgress(100);
  1584. self.unlock();
  1585. self.initSuccessThumbs();
  1586. self.clearFileInput();
  1587. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1588. };
  1589. fnError = function (jqXHR, textStatus, errorThrown) {
  1590. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1591. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1592. self.uploadFileCount = total - 1;
  1593. if (!self.showPreview) {
  1594. return;
  1595. }
  1596. self.getThumbs().each(function () {
  1597. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  1598. $thumb.removeClass('file-uploading');
  1599. if (self.filestack[key] !== undefined) {
  1600. self.setThumbStatus($thumb, 'Error');
  1601. }
  1602. });
  1603. self.getThumbs().removeClass('file-uploading');
  1604. self.getThumbs(' .kv-file-upload').removeAttr('disabled');
  1605. self.getThumbs(' .kv-file-delete').removeAttr('disabled');
  1606. };
  1607. $.each(files, function (key, data) {
  1608. if (!isEmpty(files[key])) {
  1609. self.formdata.append(self.uploadFileAttr, data);
  1610. }
  1611. });
  1612. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1613. },
  1614. uploadExtraOnly: function () {
  1615. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  1616. self.formdata = new FormData();
  1617. if (self.abort(params)) {
  1618. return;
  1619. }
  1620. fnBefore = function (jqXHR) {
  1621. self.lock();
  1622. var outData = self.getOutData(jqXHR);
  1623. self.raise('filebatchpreupload', [outData]);
  1624. self.setProgress(50);
  1625. params.data = outData;
  1626. params.xhr = jqXHR;
  1627. if (self.abort(params)) {
  1628. jqXHR.abort();
  1629. self.setProgress(100);
  1630. }
  1631. };
  1632. fnSuccess = function (data, textStatus, jqXHR) {
  1633. var outData = self.getOutData(jqXHR, data);
  1634. if (isEmpty(data) || isEmpty(data.error)) {
  1635. self.raise('filebatchuploadsuccess', [outData]);
  1636. self.clearFileInput();
  1637. self.initUploadSuccess(data);
  1638. } else {
  1639. self.showUploadError(data.error, outData, 'filebatchuploaderror');
  1640. }
  1641. };
  1642. fnComplete = function () {
  1643. self.setProgress(100);
  1644. self.unlock();
  1645. self.clearFileInput();
  1646. self.raise('filebatchuploadcomplete', [self.filestack, self.getExtraData()]);
  1647. };
  1648. fnError = function (jqXHR, textStatus, errorThrown) {
  1649. var outData = self.getOutData(jqXHR), errMsg = self.parseError(jqXHR, errorThrown);
  1650. params.data = outData;
  1651. self.showUploadError(errMsg, outData, 'filebatchuploaderror');
  1652. };
  1653. self.ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  1654. },
  1655. hideFileIcon: function () {
  1656. if (this.overwriteInitial) {
  1657. this.$captionContainer.find('.kv-caption-icon').hide();
  1658. }
  1659. },
  1660. showFileIcon: function () {
  1661. this.$captionContainer.find('.kv-caption-icon').show();
  1662. },
  1663. addError: function (msg) {
  1664. var self = this, $error = self.$errorContainer;
  1665. if (msg && $error.length) {
  1666. $error.html(self.errorCloseButton + msg);
  1667. $error.find('.kv-error-close').off('click').on('click', function () {
  1668. $error.fadeOut('slow');
  1669. });
  1670. }
  1671. },
  1672. resetErrors: function (fade) {
  1673. var self = this, $error = self.$errorContainer;
  1674. self.isError = false;
  1675. self.$container.removeClass('has-error');
  1676. $error.html('');
  1677. if (fade) {
  1678. $error.fadeOut('slow');
  1679. } else {
  1680. $error.hide();
  1681. }
  1682. },
  1683. showFolderError: function (folders) {
  1684. var self = this, $error = self.$errorContainer;
  1685. if (!folders) {
  1686. return;
  1687. }
  1688. self.addError(self.msgFoldersNotAllowed.replace(/\{n\}/g, folders));
  1689. $error.fadeIn(800);
  1690. addCss(self.$container, 'has-error');
  1691. self.raise('filefoldererror', [folders]);
  1692. },
  1693. showUploadError: function (msg, params, event) {
  1694. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror',
  1695. e = params && params.id ? '<li data-file-id="' + params.id + '">' + msg + '</li>' : '<li>' + msg + '</li>';
  1696. if ($error.find('ul').length === 0) {
  1697. self.addError('<ul>' + e + '</ul>');
  1698. } else {
  1699. $error.find('ul').append(e);
  1700. }
  1701. $error.fadeIn(800);
  1702. self.raise(ev, [params]);
  1703. self.$container.removeClass('file-input-new');
  1704. addCss(self.$container, 'has-error');
  1705. return true;
  1706. },
  1707. showError: function (msg, params, event) {
  1708. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  1709. params = params || {};
  1710. params.reader = self.reader;
  1711. self.addError(msg);
  1712. $error.fadeIn(800);
  1713. self.raise(ev, [params]);
  1714. if (!self.isUploadable) {
  1715. self.clearFileInput();
  1716. }
  1717. self.$container.removeClass('file-input-new');
  1718. addCss(self.$container, 'has-error');
  1719. self.$btnUpload.attr('disabled', true);
  1720. return true;
  1721. },
  1722. errorHandler: function (evt, caption) {
  1723. var self = this, err = evt.target.error;
  1724. switch (err.code) {
  1725. case err.NOT_FOUND_ERR:
  1726. self.showError(self.msgFileNotFound.replace('{name}', caption));
  1727. break;
  1728. case err.SECURITY_ERR:
  1729. self.showError(self.msgFileSecured.replace('{name}', caption));
  1730. break;
  1731. case err.NOT_READABLE_ERR:
  1732. self.showError(self.msgFileNotReadable.replace('{name}', caption));
  1733. break;
  1734. case err.ABORT_ERR:
  1735. self.showError(self.msgFilePreviewAborted.replace('{name}', caption));
  1736. break;
  1737. default:
  1738. self.showError(self.msgFilePreviewError.replace('{name}', caption));
  1739. }
  1740. },
  1741. parseFileType: function (file) {
  1742. var self = this, isValid, vType, cat, i;
  1743. for (i = 0; i < defaultPreviewTypes.length; i += 1) {
  1744. cat = defaultPreviewTypes[i];
  1745. isValid = isSet(cat, self.fileTypeSettings) ? self.fileTypeSettings[cat] : defaultFileTypeSettings[cat];
  1746. vType = isValid(file.type, file.name) ? cat : '';
  1747. if (!isEmpty(vType)) {
  1748. return vType;
  1749. }
  1750. }
  1751. return 'other';
  1752. },
  1753. previewDefault: function (file, previewId, isDisabled) {
  1754. if (!this.showPreview) {
  1755. return;
  1756. }
  1757. var self = this, data = objUrl.createObjectURL(file), frameClass = '', fname = file ? file.name : '',
  1758. config = self.previewSettings.other || defaultPreviewSettings.other,
  1759. footer = self.renderFileFooter(file.name, config.width),
  1760. ind = previewId.slice(previewId.lastIndexOf('-') + 1),
  1761. previewOtherTemplate = self.parseFilePreviewIcon(self.getPreviewTemplate('other'), fname);
  1762. if (isDisabled === true) {
  1763. frameClass = ' btn disabled';
  1764. if (!self.isUploadable) {
  1765. footer += '<div class="file-other-error" title="' + self.fileActionSettings.indicatorErrorTitle +
  1766. '">' + self.fileActionSettings.indicatorError + '</div>';
  1767. }
  1768. }
  1769. self.$preview.append("\n" + previewOtherTemplate
  1770. .replace(/\{previewId\}/g, previewId)
  1771. .replace(/\{frameClass\}/g, frameClass)
  1772. .replace(/\{fileindex\}/g, ind)
  1773. .replace(/\{caption\}/g, self.slug(file.name))
  1774. .replace(/\{width\}/g, config.width)
  1775. .replace(/\{height\}/g, config.height)
  1776. .replace(/\{type\}/g, file.type)
  1777. .replace(/\{data\}/g, data)
  1778. .replace(/\{footer\}/g, footer));
  1779. if (isDisabled === true && self.isUploadable) {
  1780. self.setThumbStatus($('#' + previewId), 'Error');
  1781. }
  1782. },
  1783. previewFile: function (i, file, theFile, previewId, data) {
  1784. if (!this.showPreview) {
  1785. return;
  1786. }
  1787. var self = this, cat = self.parseFileType(file), fname = file ? file.name : '', caption = self.slug(fname),
  1788. content, strText, types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes,
  1789. tmplt = self.getPreviewTemplate(cat), chkTypes = types && types.indexOf(cat) >= 0, id,
  1790. config = isSet(cat, self.previewSettings) ? self.previewSettings[cat] : defaultPreviewSettings[cat],
  1791. chkMimes = mimes && mimes.indexOf(file.type) !== -1,
  1792. footer = self.renderFileFooter(caption, config.width), modal = '',
  1793. ind = previewId.slice(previewId.lastIndexOf('-') + 1);
  1794. if (chkTypes || chkMimes) {
  1795. tmplt = self.parseFilePreviewIcon(tmplt, fname.split('.').pop());
  1796. if (cat === 'text') {
  1797. strText = htmlEncode(theFile.target.result);
  1798. id = 'text-' + uniqId();
  1799. content = tmplt.replace(/\{zoom\}/g, self.getLayoutTemplate('zoom'));
  1800. modal = self.getLayoutTemplate('modal').replace('{id}', id)
  1801. .replace(/\{title\}/g, caption)
  1802. .replace(/\{body\}/g, strText).replace(/\{heading\}/g, self.msgZoomModalHeading);
  1803. content = content.replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption)
  1804. .replace(/\{width\}/g, config.width).replace(/\{height\}/g, config.height)
  1805. .replace(/\{frameClass\}/g, '').replace(/\{zoomInd\}/g, self.zoomIndicator)
  1806. .replace(/\{footer\}/g, footer).replace(/\{fileindex\}/g, ind)
  1807. .replace(/\{type\}/g, file.type).replace(/\{zoomTitle\}/g, self.msgZoomTitle)
  1808. .replace(/\{dialog\}/g, "$('#" + id + "').modal('show')")
  1809. .replace(/\{data\}/g, strText) + modal;
  1810. } else {
  1811. content = tmplt.replace(/\{previewId\}/g, previewId).replace(/\{caption\}/g, caption)
  1812. .replace(/\{frameClass\}/g, '').replace(/\{type\}/g, file.type).replace(/\{fileindex\}/g, ind)
  1813. .replace(/\{width\}/g, config.width).replace(/\{height\}/g, config.height)
  1814. .replace(/\{footer\}/g, footer).replace(/\{data\}/g, data);
  1815. }
  1816. self.$preview.append("\n" + content);
  1817. self.validateImage(i, previewId, caption);
  1818. } else {
  1819. self.previewDefault(file, previewId);
  1820. }
  1821. },
  1822. slugDefault: function (text) {
  1823. return isEmpty(text) ? '' : text.split(/(\\|\/)/g).pop().replace(/[^\w\u00C0-\u017F\-.\\\/ ]+/g, '');
  1824. },
  1825. getFileStack: function (skipNull) {
  1826. var self = this;
  1827. return self.filestack.filter(function (n) {
  1828. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  1829. });
  1830. },
  1831. readFiles: function (files) {
  1832. this.reader = new FileReader();
  1833. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  1834. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  1835. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  1836. settings = self.fileTypeSettings, ctr = self.filestack.length, readFile,
  1837. throwError = function (msg, file, previewId, index) {
  1838. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  1839. p2 = {id: previewId, index: index, file: file, files: files};
  1840. self.previewDefault(file, previewId, true);
  1841. if (self.isUploadable) {
  1842. self.filestack.push(undefined);
  1843. }
  1844. setTimeout(readFile(index + 1), 100);
  1845. self.initFileActions();
  1846. return self.isUploadable ? self.showUploadError(msg, p1) : self.showError(msg, p2);
  1847. };
  1848. readFile = function (i) {
  1849. if (isEmpty($el.attr('multiple'))) {
  1850. numFiles = 1;
  1851. }
  1852. if (i >= numFiles) {
  1853. if (self.isUploadable && self.filestack.length > 0) {
  1854. self.raise('filebatchselected', [self.getFileStack()]);
  1855. } else {
  1856. self.raise('filebatchselected', [files]);
  1857. }
  1858. $container.removeClass('loading');
  1859. $status.html('');
  1860. return;
  1861. }
  1862. var node = ctr + i, previewId = previewInitId + "-" + node, isText, file = files[i],
  1863. caption = self.slug(file.name), fileSize = (file.size || 0) / 1000, checkFile, fileExtExpr = '',
  1864. previewData = objUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk,
  1865. fileTypes = self.allowedFileTypes, strTypes = isEmpty(fileTypes) ? '' : fileTypes.join(', '),
  1866. fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', ');
  1867. if (!isEmpty(fileExt)) {
  1868. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  1869. }
  1870. fileSize = fileSize.toFixed(2);
  1871. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  1872. msg = self.msgSizeTooLarge.replace('{name}', caption)
  1873. .replace('{size}', fileSize)
  1874. .replace('{maxSize}', self.maxFileSize);
  1875. self.isError = throwError(msg, file, previewId, i);
  1876. return;
  1877. }
  1878. if (!isEmpty(fileTypes) && isArray(fileTypes)) {
  1879. for (j = 0; j < fileTypes.length; j += 1) {
  1880. typ = fileTypes[j];
  1881. checkFile = settings[typ];
  1882. chk = (checkFile !== undefined && checkFile(file.type, caption));
  1883. fileCount += isEmpty(chk) ? 0 : chk.length;
  1884. }
  1885. if (fileCount === 0) {
  1886. msg = self.msgInvalidFileType.replace('{name}', caption).replace('{types}', strTypes);
  1887. self.isError = throwError(msg, file, previewId, i);
  1888. return;
  1889. }
  1890. }
  1891. if (fileCount === 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) {
  1892. chk = caption.match(fileExtExpr);
  1893. fileCount += isEmpty(chk) ? 0 : chk.length;
  1894. if (fileCount === 0) {
  1895. msg = self.msgInvalidFileExtension.replace('{name}', caption).replace('{extensions}',
  1896. strExt);
  1897. self.isError = throwError(msg, file, previewId, i);
  1898. return;
  1899. }
  1900. }
  1901. if (!self.showPreview) {
  1902. self.filestack.push(file);
  1903. setTimeout(readFile(i + 1), 100);
  1904. self.raise('fileloaded', [file, previewId, i, reader]);
  1905. return;
  1906. }
  1907. if ($preview.length > 0 && FileReader !== undefined) {
  1908. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  1909. $container.addClass('loading');
  1910. reader.onerror = function (evt) {
  1911. self.errorHandler(evt, caption);
  1912. };
  1913. reader.onload = function (theFile) {
  1914. self.previewFile(i, file, theFile, previewId, previewData);
  1915. self.initFileActions();
  1916. };
  1917. reader.onloadend = function () {
  1918. msg = msgProgress
  1919. .replace('{index}', i + 1).replace('{files}', numFiles)
  1920. .replace('{percent}', 50).replace('{name}', caption);
  1921. setTimeout(function () {
  1922. $status.html(msg);
  1923. self.updateFileDetails(numFiles);
  1924. readFile(i + 1);
  1925. }, 100);
  1926. self.raise('fileloaded', [file, previewId, i, reader]);
  1927. };
  1928. reader.onprogress = function (data) {
  1929. if (data.lengthComputable) {
  1930. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  1931. msg = msgProgress.replace('{index}', i + 1).replace('{files}', numFiles)
  1932. .replace('{percent}', progress).replace('{name}', caption);
  1933. setTimeout(function () {
  1934. $status.html(msg);
  1935. }, 100);
  1936. }
  1937. };
  1938. isText = isSet('text', settings) ? settings.text : defaultFileTypeSettings.text;
  1939. if (isText(file.type, caption)) {
  1940. reader.readAsText(file, self.textEncoding);
  1941. } else {
  1942. reader.readAsArrayBuffer(file);
  1943. }
  1944. } else {
  1945. self.previewDefault(file, previewId);
  1946. setTimeout(function () {
  1947. readFile(i + 1);
  1948. self.updateFileDetails(numFiles);
  1949. }, 100);
  1950. self.raise('fileloaded', [file, previewId, i, reader]);
  1951. }
  1952. self.filestack.push(file);
  1953. }
  1954. readFile(0);
  1955. self.updateFileDetails(numFiles, false);
  1956. },
  1957. updateFileDetails: function (numFiles) {
  1958. var self = this, $el = self.$element, fileStack = self.getFileStack(),
  1959. name = $el.val() || (fileStack.length && fileStack[0].name) || '', label = self.slug(name),
  1960. n = self.isUploadable ? fileStack.length : numFiles,
  1961. nFiles = previewCache.count(self.id) + n,
  1962. log = n > 1 ? self.getMsgSelected(nFiles) : label;
  1963. if (self.isError) {
  1964. self.$previewContainer.removeClass('loading');
  1965. self.$previewStatus.html('');
  1966. self.$captionContainer.find('.kv-caption-icon').hide();
  1967. } else {
  1968. self.showFileIcon();
  1969. }
  1970. self.setCaption(log, self.isError);
  1971. self.$container.removeClass('file-input-new file-input-ajax-new');
  1972. if (arguments.length === 1) {
  1973. self.raise('fileselect', [numFiles, label]);
  1974. }
  1975. if (previewCache.count(self.id)) {
  1976. self.initPreviewDeletes();
  1977. }
  1978. },
  1979. validateMinCount: function () {
  1980. var self = this, len = self.isUploadable ? self.getFileStack().length : self.$element.get(0).files.length;
  1981. if (self.validateInitialCount && self.minFileCount > 0 && self.getFileCount(len - 1) < self.minFileCount) {
  1982. self.noFilesError({});
  1983. return false;
  1984. }
  1985. return true;
  1986. },
  1987. getFileCount: function (fileCount) {
  1988. var self = this, addCount = 0;
  1989. if (self.validateInitialCount && !self.overwriteInitial) {
  1990. addCount = previewCache.count(self.id);
  1991. fileCount += addCount;
  1992. }
  1993. return fileCount;
  1994. },
  1995. change: function (e) {
  1996. var self = this, $el = self.$element;
  1997. if (!self.isUploadable && isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix
  1998. self.fileInputCleared = false;
  1999. return;
  2000. }
  2001. self.fileInputCleared = false;
  2002. var tfiles, msg, total, isDragDrop = arguments.length > 1,
  2003. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files,
  2004. isSingleUpload = isEmpty($el.attr('multiple')), i = 0, f, n, folders = 0,
  2005. ctr = self.filestack.length, isAjaxUpload = self.isUploadable, len,
  2006. flagSingle = (isSingleUpload && ctr > 0),
  2007. throwError = function (mesg, file, previewId, index) {
  2008. var p1 = $.extend(self.getOutData({}, {}, files), {id: previewId, index: index}),
  2009. p2 = {id: previewId, index: index, file: file, files: files};
  2010. return self.isUploadable ? self.showUploadError(mesg, p1) : self.showError(mesg, p2);
  2011. };
  2012. self.reader = null;
  2013. self.resetUpload();
  2014. self.hideFileIcon();
  2015. if (self.isUploadable) {
  2016. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  2017. }
  2018. if (isDragDrop) {
  2019. tfiles = [];
  2020. while (files[i]) {
  2021. f = files[i];
  2022. if (!f.type && f.size % 4096 === 0) {
  2023. folders++;
  2024. } else {
  2025. tfiles.push(f);
  2026. }
  2027. i++;
  2028. }
  2029. } else {
  2030. if (e.target.files === undefined) {
  2031. tfiles = e.target && e.target.value ? [
  2032. {name: e.target.value.replace(/^.+\\/, '')}
  2033. ] : [];
  2034. } else {
  2035. tfiles = e.target.files;
  2036. }
  2037. }
  2038. if (isEmpty(tfiles) || tfiles.length === 0) {
  2039. if (!isAjaxUpload) {
  2040. self.clear();
  2041. }
  2042. self.showFolderError(folders);
  2043. self.raise('fileselectnone');
  2044. return;
  2045. }
  2046. self.resetErrors();
  2047. len = tfiles.length;
  2048. total = self.isUploadable ? self.getFileStack().length + len : len;
  2049. total = self.getFileCount(total);
  2050. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  2051. if (!self.autoReplace || len > self.maxFileCount) {
  2052. n = (self.autoReplace && len > self.maxFileCount) ? len : total;
  2053. msg = self.msgFilesTooMany.replace('{m}', self.maxFileCount).replace('{n}', n);
  2054. self.isError = throwError(msg, null, null, null);
  2055. self.$captionContainer.find('.kv-caption-icon').hide();
  2056. self.setCaption('', true);
  2057. self.$container.removeClass('file-input-new file-input-ajax-new');
  2058. return;
  2059. }
  2060. if (total > self.maxFileCount) {
  2061. self.resetPreviewThumbs(isAjaxUpload);
  2062. }
  2063. } else {
  2064. if (!isAjaxUpload || flagSingle) {
  2065. self.resetPreviewThumbs(false);
  2066. if (flagSingle) {
  2067. self.filestack = [];
  2068. }
  2069. } else {
  2070. if (isAjaxUpload && ctr === 0 && (!previewCache.count(self.id) || self.overwriteInitial)) {
  2071. self.resetPreviewThumbs(true);
  2072. }
  2073. }
  2074. }
  2075. if (self.isPreviewable) {
  2076. self.readFiles(tfiles);
  2077. } else {
  2078. self.updateFileDetails(1);
  2079. }
  2080. self.showFolderError(folders);
  2081. },
  2082. validateImage: function (i, previewId, fname) {
  2083. var self = this, $preview = self.$preview, params, w1, w2,
  2084. $thumb = $preview.find("#" + previewId), $img = $thumb.find('img');
  2085. fname = fname || 'Untitled';
  2086. if (!$img.length) {
  2087. return;
  2088. }
  2089. handler($img, 'load', function () {
  2090. w1 = $thumb.width();
  2091. w2 = $preview.width();
  2092. if (w1 > w2) {
  2093. $img.css('width', '100%');
  2094. $thumb.css('width', '97%');
  2095. }
  2096. params = {ind: i, id: previewId};
  2097. self.checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
  2098. self.checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
  2099. self.checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
  2100. self.checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
  2101. self.raise('fileimageloaded', [previewId]);
  2102. objUrl.revokeObjectURL($img.attr('src'));
  2103. });
  2104. },
  2105. checkDimensions: function (i, chk, $img, $thumb, fname, type, params) {
  2106. var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max',
  2107. limit = self[tag + 'Image' + type], $imgEl, isValid;
  2108. if (isEmpty(limit) || !$img.length) {
  2109. return;
  2110. }
  2111. $imgEl = $img[0];
  2112. dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height;
  2113. isValid = chk === 'Small' ? dim >= limit : dim <= limit;
  2114. if (isValid) {
  2115. return;
  2116. }
  2117. msg = self['msgImage' + type + chk].replace('{name}', fname).replace('{size}', limit);
  2118. self.showUploadError(msg, params);
  2119. self.setThumbStatus($thumb, 'Error');
  2120. self.filestack[i] = null;
  2121. },
  2122. initCaption: function () {
  2123. var self = this, cap = self.initialCaption || '';
  2124. if (self.overwriteInitial || isEmpty(cap)) {
  2125. self.$caption.html('');
  2126. return false;
  2127. }
  2128. self.setCaption(cap);
  2129. return true;
  2130. },
  2131. setCaption: function (content, isError) {
  2132. var self = this, title, out;
  2133. if (isError) {
  2134. title = $('<div>' + self.msgValidationError + '</div>').text();
  2135. out = '<span class="' + self.msgValidationErrorClass + '">' +
  2136. self.msgValidationErrorIcon + title + '</span>';
  2137. } else {
  2138. if (isEmpty(content) || self.$caption.length === 0) {
  2139. return;
  2140. }
  2141. title = $('<div>' + content + '</div>').text();
  2142. out = self.getLayoutTemplate('icon') + title;
  2143. }
  2144. self.$caption.html(out);
  2145. self.$caption.attr('title', title);
  2146. self.$captionContainer.find('.file-caption-ellipsis').attr('title', title);
  2147. },
  2148. initBrowse: function ($container) {
  2149. var self = this;
  2150. self.$btnFile = $container.find('.btn-file');
  2151. self.$btnFile.append(self.$element);
  2152. },
  2153. createContainer: function () {
  2154. var self = this,
  2155. $container = $(document.createElement("div"))
  2156. .attr({"class": 'file-input file-input-new'})
  2157. .html(self.renderMain());
  2158. self.$element.before($container);
  2159. self.initBrowse($container);
  2160. return $container;
  2161. },
  2162. refreshContainer: function () {
  2163. var self = this, $container = self.$container;
  2164. $container.before(self.$element);
  2165. $container.html(self.renderMain());
  2166. self.initBrowse($container);
  2167. },
  2168. renderMain: function () {
  2169. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : '',
  2170. preview = self.showPreview ? self.getLayoutTemplate('preview').replace(/\{class\}/g, self.previewClass)
  2171. .replace(/\{dropClass\}/g, dropCss) : '',
  2172. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  2173. caption = self.captionTemplate.replace(/\{class\}/g, css + ' kv-fileinput-caption');
  2174. return self.mainTemplate.replace(/\{class\}/g, self.mainClass)
  2175. .replace(/\{preview\}/g, preview)
  2176. .replace(/\{caption\}/g, caption)
  2177. .replace(/\{upload\}/g, self.renderButton('upload'))
  2178. .replace(/\{remove\}/g, self.renderButton('remove'))
  2179. .replace(/\{cancel\}/g, self.renderButton('cancel'))
  2180. .replace(/\{browse\}/g, self.renderButton('browse'));
  2181. },
  2182. renderButton: function (type) {
  2183. var self = this, tmplt = self.getLayoutTemplate('btnDefault'), css = self[type + 'Class'],
  2184. title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'],
  2185. status = self.isDisabled ? ' disabled' : '', btnType = 'button';
  2186. switch (type) {
  2187. case 'remove':
  2188. if (!self.showRemove) {
  2189. return '';
  2190. }
  2191. break;
  2192. case 'cancel':
  2193. if (!self.showCancel) {
  2194. return '';
  2195. }
  2196. css += ' hide';
  2197. break;
  2198. case 'upload':
  2199. if (!self.showUpload) {
  2200. return '';
  2201. }
  2202. if (self.isUploadable && !self.isDisabled) {
  2203. tmplt = self.getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl);
  2204. } else {
  2205. btnType = 'submit';
  2206. }
  2207. break;
  2208. case 'browse':
  2209. tmplt = self.getLayoutTemplate('btnBrowse');
  2210. break;
  2211. default:
  2212. return '';
  2213. }
  2214. css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button';
  2215. return tmplt.replace('{type}', btnType)
  2216. .replace('{css}', css)
  2217. .replace('{title}', title)
  2218. .replace('{status}', status)
  2219. .replace('{icon}', icon)
  2220. .replace('{label}', label);
  2221. }
  2222. };
  2223. //FileInput plugin definition
  2224. $.fn.fileinput = function (option) {
  2225. if (!hasFileAPISupport() && !isIE(9)) {
  2226. return;
  2227. }
  2228. var args = Array.apply(null, arguments);
  2229. args.shift();
  2230. return this.each(function () {
  2231. var $this = $(this), data = $this.data('fileinput'), defaults,
  2232. options = typeof option === 'object' && option,
  2233. lang = options.language || $this.data('language') || 'en';
  2234. if (!data) {
  2235. defaults = $.extend({}, $.fn.fileinput.defaults);
  2236. if (lang !== 'en' && !isEmpty($.fn.fileinputLocales[lang])) {
  2237. defaults = $.extend(defaults, $.fn.fileinputLocales[lang]);
  2238. }
  2239. data = new FileInput(this, $.extend(defaults, options, $this.data()));
  2240. $this.data('fileinput', data);
  2241. }
  2242. if (typeof option === 'string') {
  2243. data[option].apply(data, args);
  2244. }
  2245. });
  2246. };
  2247. $.fn.fileinput.defaults = {
  2248. language: 'en',
  2249. showCaption: true,
  2250. showPreview: true,
  2251. showRemove: true,
  2252. showUpload: true,
  2253. showCancel: true,
  2254. showUploadedThumbs: true,
  2255. autoReplace: false,
  2256. mainClass: '',
  2257. previewClass: '',
  2258. captionClass: '',
  2259. mainTemplate: null,
  2260. initialCaption: '',
  2261. initialPreview: [],
  2262. initialPreviewDelimiter: '*$$*',
  2263. initialPreviewConfig: [],
  2264. initialPreviewThumbTags: [],
  2265. previewThumbTags: {},
  2266. initialPreviewShowDelete: true,
  2267. deleteUrl: '',
  2268. deleteExtraData: {},
  2269. overwriteInitial: true,
  2270. layoutTemplates: defaultLayoutTemplates,
  2271. previewTemplates: defaultPreviewTemplates,
  2272. allowedPreviewTypes: defaultPreviewTypes,
  2273. allowedPreviewMimeTypes: null,
  2274. allowedFileTypes: null,
  2275. allowedFileExtensions: null,
  2276. customLayoutTags: {},
  2277. customPreviewTags: {},
  2278. previewSettings: defaultPreviewSettings,
  2279. fileTypeSettings: defaultFileTypeSettings,
  2280. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  2281. previewFileIconClass: 'file-icon-4x',
  2282. previewFileIconSettings: {},
  2283. previewFileExtSettings: {},
  2284. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> &nbsp;',
  2285. browseClass: 'btn btn-primary',
  2286. removeIcon: '<i class="glyphicon glyphicon-trash"></i> ',
  2287. removeClass: 'btn btn-default',
  2288. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i> ',
  2289. cancelClass: 'btn btn-default',
  2290. uploadIcon: '<i class="glyphicon glyphicon-upload"></i> ',
  2291. uploadClass: 'btn btn-default',
  2292. uploadUrl: null,
  2293. uploadAsync: true,
  2294. uploadExtraData: {},
  2295. minImageWidth: null,
  2296. minImageHeight: null,
  2297. maxImageWidth: null,
  2298. maxImageHeight: null,
  2299. maxFileSize: 0,
  2300. minFileCount: 0,
  2301. maxFileCount: 0,
  2302. validateInitialCount: false,
  2303. msgValidationErrorClass: 'text-danger',
  2304. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  2305. msgErrorClass: 'file-error-message',
  2306. progressClass: "progress-bar progress-bar-success progress-bar-striped active",
  2307. progressCompleteClass: "progress-bar progress-bar-success",
  2308. previewFileType: 'image',
  2309. zoomIndicator: '<i class="glyphicon glyphicon-zoom-in"></i>',
  2310. elCaptionContainer: null,
  2311. elCaptionText: null,
  2312. elPreviewContainer: null,
  2313. elPreviewImage: null,
  2314. elPreviewStatus: null,
  2315. elErrorContainer: null,
  2316. errorCloseButton: '<span class="close kv-error-close">&times;</span>',
  2317. slugCallback: null,
  2318. dropZoneEnabled: true,
  2319. dropZoneTitleClass: 'file-drop-zone-title',
  2320. fileActionSettings: {},
  2321. otherActionButtons: '',
  2322. textEncoding: 'UTF-8',
  2323. ajaxSettings: {},
  2324. ajaxDeleteSettings: {},
  2325. showAjaxErrorDetails: true
  2326. };
  2327. $.fn.fileinputLocales.en = {
  2328. fileSingle: 'file',
  2329. filePlural: 'files',
  2330. browseLabel: 'Browse &hellip;',
  2331. removeLabel: 'Remove',
  2332. removeTitle: 'Clear selected files',
  2333. cancelLabel: 'Cancel',
  2334. cancelTitle: 'Abort ongoing upload',
  2335. uploadLabel: 'Upload',
  2336. uploadTitle: 'Upload selected files',
  2337. msgZoomTitle: 'View details',
  2338. msgZoomModalHeading: 'Detailed Preview',
  2339. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
  2340. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
  2341. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
  2342. msgFileNotFound: 'File "{name}" not found!',
  2343. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  2344. msgFileNotReadable: 'File "{name}" is not readable.',
  2345. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  2346. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  2347. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  2348. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  2349. msgValidationError: 'File Upload Error',
  2350. msgLoading: 'Loading file {index} of {files} &hellip;',
  2351. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  2352. msgSelected: '{n} {files} selected',
  2353. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  2354. msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
  2355. msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
  2356. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
  2357. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
  2358. dropZoneTitle: 'Drag & drop files here &hellip;'
  2359. };
  2360. $.extend($.fn.fileinput.defaults, $.fn.fileinputLocales.en);
  2361. $.fn.fileinput.Constructor = FileInput;
  2362. /**
  2363. * Convert automatically file inputs with class 'file'
  2364. * into a bootstrap fileinput control.
  2365. */
  2366. $(document).ready(function () {
  2367. var $input = $('input.file[type=file]');
  2368. if ($input.length) {
  2369. $input.fileinput();
  2370. }
  2371. });
  2372. })(window.jQuery);