fileinput.js 112 KB

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