fileinput.js 156 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422
  1. /*!
  2. * bootstrap-fileinput v4.3.7
  3. * http://plugins.krajee.com/file-input
  4. *
  5. * Author: Kartik Visweswaran
  6. * Copyright: 2014 - 2017, Kartik Visweswaran, Krajee.com
  7. *
  8. * Licensed under the BSD 3-Clause
  9. * https://github.com/kartik-v/bootstrap-fileinput/blob/master/LICENSE.md
  10. */
  11. (function (factory) {
  12. "use strict";
  13. //noinspection JSUnresolvedVariable
  14. if (typeof define === 'function' && define.amd) { // jshint ignore:line
  15. // AMD. Register as an anonymous module.
  16. define(['jquery'], factory); // jshint ignore:line
  17. } else { // noinspection JSUnresolvedVariable
  18. if (typeof module === 'object' && module.exports) { // jshint ignore:line
  19. // Node/CommonJS
  20. // noinspection JSUnresolvedVariable
  21. module.exports = factory(require('jquery')); // jshint ignore:line
  22. } else {
  23. // Browser globals
  24. factory(window.jQuery);
  25. }
  26. }
  27. }(function ($) {
  28. "use strict";
  29. $.fn.fileinputLocales = {};
  30. $.fn.fileinputThemes = {};
  31. var NAMESPACE, MODAL_ID, FRAMES, SORT_CSS, STYLE_SETTING, OBJECT_PARAMS, DEFAULT_PREVIEW, objUrl, compare, handler,
  32. isIE, previewCache, getNum, hasFileAPISupport, hasDragDropSupport, hasFileUploadSupport, addCss, tMain1, tMain2,
  33. tPreview, tFileIcon, tClose, tCaption, tBtnDefault, tBtnLink, tBtnBrowse, tModalMain, tModal, tProgress, tSize,
  34. tFooter, tActions, tActionDelete, tActionUpload, tActionZoom, tActionDrag, tTagBef, tTagBef1, tTagBef2, tTagAft,
  35. tGeneric, tHtml, tImage, tText, tVideo, tAudio, tFlash, tObject, tPdf, tOther, defaultFileActionSettings,
  36. defaultLayoutTemplates, defaultPreviewTemplates, defaultPreviewZoomSettings, defaultPreviewTypes, getElement,
  37. defaultPreviewSettings, defaultFileTypeSettings, isEmpty, isArray, ifSet, uniqId, htmlEncode, replaceTags,
  38. cleanMemory, findFileName, checkFullScreen, toggleFullScreen, moveArray, FileInput;
  39. NAMESPACE = '.fileinput';
  40. MODAL_ID = 'kvFileinputModal';
  41. FRAMES = '.kv-preview-thumb';
  42. SORT_CSS = 'file-sortable';
  43. STYLE_SETTING = 'style="width:{width};height:{height};"';
  44. OBJECT_PARAMS = '<param name="controller" value="true" />\n' +
  45. '<param name="allowFullScreen" value="true" />\n' +
  46. '<param name="allowScriptAccess" value="always" />\n' +
  47. '<param name="autoPlay" value="false" />\n' +
  48. '<param name="autoStart" value="false" />\n' +
  49. '<param name="quality" value="high" />\n';
  50. DEFAULT_PREVIEW = '<div class="file-preview-other">\n' +
  51. '<span class="{previewFileIconClass}">{previewFileIcon}</span>\n' +
  52. '</div>';
  53. //noinspection JSUnresolvedVariable
  54. objUrl = window.URL || window.webkitURL;
  55. compare = function (input, str, exact) {
  56. return input !== undefined && (exact ? input === str : input.match(str));
  57. };
  58. isIE = function (ver) {
  59. // check for IE versions < 11
  60. if (navigator.appName !== 'Microsoft Internet Explorer') {
  61. return false;
  62. }
  63. if (ver === 10) {
  64. return new RegExp('msie\\s' + ver, 'i').test(navigator.userAgent);
  65. }
  66. var div = document.createElement("div"), status;
  67. div.innerHTML = "<!--[if IE " + ver + "]> <i></i> <![endif]-->";
  68. status = div.getElementsByTagName("i").length;
  69. document.body.appendChild(div);
  70. div.parentNode.removeChild(div);
  71. return status;
  72. };
  73. handler = function ($el, event, callback, skipNS) {
  74. var ev = skipNS ? event : event.split(' ').join(NAMESPACE + ' ') + NAMESPACE;
  75. if ($el.length) {
  76. $el.off(ev).on(ev, callback);
  77. }
  78. };
  79. previewCache = {
  80. data: {},
  81. init: function (obj) {
  82. var content = obj.initialPreview, id = obj.id;
  83. if (content.length > 0 && !isArray(content)) {
  84. content = content.split(obj.initialPreviewDelimiter);
  85. }
  86. previewCache.data[id] = {
  87. content: content,
  88. config: obj.initialPreviewConfig,
  89. tags: obj.initialPreviewThumbTags,
  90. delimiter: obj.initialPreviewDelimiter,
  91. previewFileType: obj.initialPreviewFileType,
  92. previewAsData: obj.initialPreviewAsData,
  93. template: obj.previewGenericTemplate,
  94. showZoom: obj.fileActionSettings.showZoom,
  95. showDrag: obj.fileActionSettings.showDrag,
  96. getSize: function (size) {
  97. return obj._getSize(size);
  98. },
  99. parseTemplate: function (cat, data, fname, ftype, pId, ftr, ind, tmpl) {
  100. var fc = ' file-preview-initial ' + SORT_CSS;
  101. return obj._generatePreviewTemplate(cat, data, fname, ftype, pId, false, null, fc, ftr, ind, tmpl);
  102. },
  103. msg: function (n) {
  104. return obj._getMsgSelected(n);
  105. },
  106. initId: obj.previewInitId,
  107. footer: obj._getLayoutTemplate('footer').replace(/\{progress}/g, obj._renderThumbProgress()),
  108. isDelete: obj.initialPreviewShowDelete,
  109. caption: obj.initialCaption,
  110. actions: function (showUpload, showDelete, showZoom, showDrag, disabled, url, key) {
  111. return obj._renderFileActions(showUpload, showDelete, showZoom, showDrag, disabled, url, key, true);
  112. }
  113. };
  114. },
  115. fetch: function (id) {
  116. return previewCache.data[id].content.filter(function (n) {
  117. return n !== null;
  118. });
  119. },
  120. count: function (id, all) {
  121. return !!previewCache.data[id] && !!previewCache.data[id].content ?
  122. (all ? previewCache.data[id].content.length : previewCache.fetch(id).length) : 0;
  123. },
  124. get: function (id, i, isDisabled) {
  125. var ind = 'init_' + i, data = previewCache.data[id], config = data.config[i], content = data.content[i],
  126. previewId = data.initId + '-' + ind, out, $tmp, cat, ftr, fname, ftype,
  127. asData = ifSet('previewAsData', config, data.previewAsData);
  128. isDisabled = isDisabled === undefined ? true : isDisabled;
  129. /** @namespace config.frameAttr */
  130. /** @namespace config.frameClass */
  131. /** @namespace config.filetype */
  132. if (!content) {
  133. return '';
  134. }
  135. cat = ifSet('type', config, data.previewFileType || 'generic');
  136. fname = ifSet('filename', config, ifSet('caption', config));
  137. ftype = ifSet('filetype', config, cat);
  138. ftr = previewCache.footer(id, i, isDisabled, (config && config.size || null));
  139. if (asData) {
  140. out = data.parseTemplate(cat, content, fname, ftype, previewId, ftr, ind);
  141. } else {
  142. out = data.parseTemplate('generic', content, fname, ftype, previewId, ftr, ind, cat)
  143. .replace(/\{content}/g, data.content[i]);
  144. }
  145. if (data.tags.length && data.tags[i]) {
  146. out = replaceTags(out, data.tags[i]);
  147. }
  148. if (!isEmpty(config) && !isEmpty(config.frameAttr)) {
  149. $tmp = $(document.createElement('div')).html(out);
  150. $tmp.find('.file-preview-initial').attr(config.frameAttr);
  151. out = $tmp.html();
  152. $tmp.remove();
  153. }
  154. return out;
  155. },
  156. add: function (id, content, config, tags, append) {
  157. var data = $.extend(true, {}, previewCache.data[id]), index;
  158. if (!isArray(content)) {
  159. content = content.split(data.delimiter);
  160. }
  161. if (append) {
  162. index = data.content.push(content) - 1;
  163. data.config[index] = config;
  164. data.tags[index] = tags;
  165. } else {
  166. index = content.length - 1;
  167. data.content = content;
  168. data.config = config;
  169. data.tags = tags;
  170. }
  171. previewCache.data[id] = data;
  172. return index;
  173. },
  174. set: function (id, content, config, tags, append) {
  175. var data = $.extend(true, {}, previewCache.data[id]), i, chk;
  176. if (!content || !content.length) {
  177. return;
  178. }
  179. if (!isArray(content)) {
  180. content = content.split(data.delimiter);
  181. }
  182. chk = content.filter(function (n) {
  183. return n !== null;
  184. });
  185. if (!chk.length) {
  186. return;
  187. }
  188. if (data.content === undefined) {
  189. data.content = [];
  190. }
  191. if (data.config === undefined) {
  192. data.config = [];
  193. }
  194. if (data.tags === undefined) {
  195. data.tags = [];
  196. }
  197. if (append) {
  198. for (i = 0; i < content.length; i++) {
  199. if (content[i]) {
  200. data.content.push(content[i]);
  201. }
  202. }
  203. for (i = 0; i < config.length; i++) {
  204. if (config[i]) {
  205. data.config.push(config[i]);
  206. }
  207. }
  208. for (i = 0; i < tags.length; i++) {
  209. if (tags[i]) {
  210. data.tags.push(tags[i]);
  211. }
  212. }
  213. } else {
  214. data.content = content;
  215. data.config = config;
  216. data.tags = tags;
  217. }
  218. previewCache.data[id] = data;
  219. },
  220. unset: function (obj, index) {
  221. var chk = previewCache.count(obj.id);
  222. if (!chk) {
  223. return;
  224. }
  225. if (chk === 1) {
  226. previewCache.data[obj.id].content = [];
  227. previewCache.data[obj.id].config = [];
  228. previewCache.data[obj.id].tags = [];
  229. obj.initialPreview = [];
  230. obj.initialPreviewConfig = [];
  231. obj.initialPreviewThumbTags = [];
  232. return;
  233. }
  234. previewCache.data[obj.id].content[index] = null;
  235. previewCache.data[obj.id].config[index] = null;
  236. previewCache.data[obj.id].tags[index] = null;
  237. },
  238. out: function (id) {
  239. var html = '', data = previewCache.data[id], caption, len = previewCache.count(id, true);
  240. if (len === 0) {
  241. return {content: '', caption: ''};
  242. }
  243. for (var i = 0; i < len; i++) {
  244. html += previewCache.get(id, i);
  245. }
  246. caption = data.msg(previewCache.count(id));
  247. return {content: html, caption: caption};
  248. },
  249. footer: function (id, i, isDisabled, size) {
  250. var data = previewCache.data[id];
  251. isDisabled = isDisabled === undefined ? true : isDisabled;
  252. if (!data || !data.config || data.config.length === 0 || isEmpty(data.config[i])) {
  253. return '';
  254. }
  255. var config = data.config[i], caption = ifSet('caption', config), width = ifSet('width', config, 'auto'),
  256. url = ifSet('url', config, false), key = ifSet('key', config, null),
  257. showDel = ifSet('showDelete', config, true), showZoom = ifSet('showZoom', config, data.showZoom),
  258. showDrag = ifSet('showDrag', config, data.showDrag), disabled = (url === false) && isDisabled,
  259. actions = data.isDelete ? data.actions(false, showDel, showZoom, showDrag, disabled, url, key) : '',
  260. footer = data.footer.replace(/\{actions}/g, actions);
  261. return footer.replace(/\{caption}/g, caption).replace(/\{size}/g, data.getSize(size))
  262. .replace(/\{width}/g, width).replace(/\{indicator}/g, '').replace(/\{indicatorTitle}/g, '');
  263. }
  264. };
  265. getNum = function (num, def) {
  266. def = def || 0;
  267. if (typeof num === "number") {
  268. return num;
  269. }
  270. if (typeof num === "string") {
  271. num = parseFloat(num);
  272. }
  273. return isNaN(num) ? def : num;
  274. };
  275. hasFileAPISupport = function () {
  276. return !!(window.File && window.FileReader);
  277. };
  278. hasDragDropSupport = function () {
  279. var div = document.createElement('div');
  280. /** @namespace div.draggable */
  281. /** @namespace div.ondragstart */
  282. /** @namespace div.ondrop */
  283. return !isIE(9) && (div.draggable !== undefined || (div.ondragstart !== undefined && div.ondrop !== undefined));
  284. };
  285. hasFileUploadSupport = function () {
  286. return hasFileAPISupport() && window.FormData;
  287. };
  288. addCss = function ($el, css) {
  289. $el.removeClass(css).addClass(css);
  290. };
  291. defaultFileActionSettings = {
  292. showRemove: true,
  293. showUpload: true,
  294. showZoom: true,
  295. showDrag: true,
  296. removeIcon: '<i class="glyphicon glyphicon-trash text-danger"></i>',
  297. removeClass: 'btn btn-xs btn-default',
  298. removeTitle: 'Remove file',
  299. uploadIcon: '<i class="glyphicon glyphicon-upload text-info"></i>',
  300. uploadClass: 'btn btn-xs btn-default',
  301. uploadTitle: 'Upload file',
  302. zoomIcon: '<i class="glyphicon glyphicon-zoom-in"></i>',
  303. zoomClass: 'btn btn-xs btn-default',
  304. zoomTitle: 'View Details',
  305. dragIcon: '<i class="glyphicon glyphicon-menu-hamburger"></i>',
  306. dragClass: 'text-info',
  307. dragTitle: 'Move / Rearrange',
  308. dragSettings: {},
  309. indicatorNew: '<i class="glyphicon glyphicon-hand-down text-warning"></i>',
  310. indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign text-success"></i>',
  311. indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>',
  312. indicatorLoading: '<i class="glyphicon glyphicon-hand-up text-muted"></i>',
  313. indicatorNewTitle: 'Not uploaded yet',
  314. indicatorSuccessTitle: 'Uploaded',
  315. indicatorErrorTitle: 'Upload Error',
  316. indicatorLoadingTitle: 'Uploading ...'
  317. };
  318. tMain1 = '{preview}\n' +
  319. '<div class="kv-upload-progress hide"></div>\n' +
  320. '<div class="input-group {class}">\n' +
  321. ' {caption}\n' +
  322. ' <div class="input-group-btn">\n' +
  323. ' {remove}\n' +
  324. ' {cancel}\n' +
  325. ' {upload}\n' +
  326. ' {browse}\n' +
  327. ' </div>\n' +
  328. '</div>';
  329. tMain2 = '{preview}\n<div class="kv-upload-progress hide"></div>\n{remove}\n{cancel}\n{upload}\n{browse}\n';
  330. tPreview = '<div class="file-preview {class}">\n' +
  331. ' {close}' +
  332. ' <div class="{dropClass}">\n' +
  333. ' <div class="file-preview-thumbnails">\n' +
  334. ' </div>\n' +
  335. ' <div class="clearfix"></div>' +
  336. ' <div class="file-preview-status text-center text-success"></div>\n' +
  337. ' <div class="kv-fileinput-error"></div>\n' +
  338. ' </div>\n' +
  339. '</div>';
  340. tClose = '<div class="close fileinput-remove">&times;</div>\n';
  341. tFileIcon = '<i class="glyphicon glyphicon-file kv-caption-icon"></i>';
  342. tCaption = '<div tabindex="500" class="form-control file-caption {class}">\n' +
  343. ' <div class="file-caption-name"></div>\n' +
  344. '</div>\n';
  345. //noinspection HtmlUnknownAttribute
  346. tBtnDefault = '<button type="{type}" tabindex="500" title="{title}" class="{css}" {status}>{icon} {label}</button>';
  347. //noinspection HtmlUnknownAttribute
  348. tBtnLink = '<a href="{href}" tabindex="500" title="{title}" class="{css}" {status}>{icon} {label}</a>';
  349. //noinspection HtmlUnknownAttribute
  350. tBtnBrowse = '<div tabindex="500" class="{css}" {status}>{icon} {label}</div>';
  351. tModalMain = '<div id="' + MODAL_ID + '" class="file-zoom-dialog modal fade" tabindex="-1" aria-labelledby="' +
  352. MODAL_ID + 'Label"></div>';
  353. tModal = '<div class="modal-dialog modal-lg" role="document">\n' +
  354. ' <div class="modal-content">\n' +
  355. ' <div class="modal-header">\n' +
  356. ' <div class="kv-zoom-actions pull-right">{toggleheader}{fullscreen}{borderless}{close}</div>\n' +
  357. ' <h3 class="modal-title">{heading} <small><span class="kv-zoom-title"></span></small></h3>\n' +
  358. ' </div>\n' +
  359. ' <div class="modal-body">\n' +
  360. ' <div class="floating-buttons"></div>\n' +
  361. ' <div class="kv-zoom-body file-zoom-content"></div>\n' + '{prev} {next}\n' +
  362. ' </div>\n' +
  363. ' </div>\n' +
  364. '</div>\n';
  365. tProgress = '<div class="progress">\n' +
  366. ' <div class="{class}" role="progressbar"' +
  367. ' aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' +
  368. ' {percent}%\n' +
  369. ' </div>\n' +
  370. '</div>';
  371. tSize = ' <br><samp>({sizeText})</samp>';
  372. tFooter = '<div class="file-thumbnail-footer">\n' +
  373. ' <div class="file-footer-caption" title="{caption}">{caption}{size}</div>\n' +
  374. ' {progress} {actions}\n' +
  375. '</div>';
  376. tActions = '<div class="file-actions">\n' +
  377. ' <div class="file-footer-buttons">\n' +
  378. ' {upload} {delete} {zoom} {other}' +
  379. ' </div>\n' +
  380. ' {drag}\n' +
  381. ' <div class="file-upload-indicator" title="{indicatorTitle}">{indicator}</div>\n' +
  382. ' <div class="clearfix"></div>\n' +
  383. '</div>';
  384. //noinspection HtmlUnknownAttribute
  385. tActionDelete = '<button type="button" class="kv-file-remove {removeClass}" ' + 'title="{removeTitle}" {dataUrl}{dataKey}>{removeIcon}</button>\n';
  386. tActionUpload = '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">' +
  387. '{uploadIcon}</button>';
  388. tActionZoom = '<button type="button" class="kv-file-zoom {zoomClass}" title="{zoomTitle}">{zoomIcon}</button>';
  389. tActionDrag = '<span class="file-drag-handle {dragClass}" title="{dragTitle}">{dragIcon}</span>';
  390. tTagBef = '<div class="file-preview-frame{frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  391. ' data-template="{template}"';
  392. tTagBef1 = tTagBef + '><div class="kv-file-content">\n';
  393. tTagBef2 = tTagBef + ' title="{caption}" ' + STYLE_SETTING + '><div class="kv-file-content">\n';
  394. tTagAft = '</div>{footer}\n</div>\n';
  395. tGeneric = '{content}\n';
  396. tHtml = '<div class="kv-preview-data file-preview-html" title="{caption}" ' + STYLE_SETTING + '>{data}</div>\n';
  397. tImage = '<img src="{data}" class="kv-preview-data file-preview-image" title="{caption}" alt="{caption}" ' +
  398. STYLE_SETTING + '>\n';
  399. tText = '<textarea class="kv-preview-data file-preview-text" title="{caption}" readonly ' + STYLE_SETTING +
  400. '>{data}</textarea>\n';
  401. tVideo = '<video class="kv-preview-data" width="{width}" height="{height}" controls>\n' +
  402. '<source src="{data}" type="{type}">\n' + DEFAULT_PREVIEW + '\n</video>\n';
  403. tAudio = '<audio class="kv-preview-data" controls>\n<source src="' + '{data}' + '" type="{type}">\n' +
  404. DEFAULT_PREVIEW + '\n</audio>\n';
  405. tFlash = '<object class="kv-preview-data file-object" type="application/x-shockwave-flash" ' +
  406. 'width="{width}" height="{height}" data="{data}">\n' + OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n</object>\n';
  407. tObject = '<object class="kv-preview-data file-object" data="{data}" type="{type}" width="{width}" height="{height}">\n' +
  408. '<param name="movie" value="{caption}" />\n' + OBJECT_PARAMS + ' ' + DEFAULT_PREVIEW + '\n</object>\n';
  409. tPdf = '<embed class="kv-preview-data" src="{data}" width="{width}" height="{height}" type="application/pdf">\n';
  410. tOther = '<div class="kv-preview-data file-preview-other-frame">\n' + DEFAULT_PREVIEW + '\n</div>\n';
  411. defaultLayoutTemplates = {
  412. main1: tMain1,
  413. main2: tMain2,
  414. preview: tPreview,
  415. close: tClose,
  416. fileIcon: tFileIcon,
  417. caption: tCaption,
  418. modalMain: tModalMain,
  419. modal: tModal,
  420. progress: tProgress,
  421. size: tSize,
  422. footer: tFooter,
  423. actions: tActions,
  424. actionDelete: tActionDelete,
  425. actionUpload: tActionUpload,
  426. actionZoom: tActionZoom,
  427. actionDrag: tActionDrag,
  428. btnDefault: tBtnDefault,
  429. btnLink: tBtnLink,
  430. btnBrowse: tBtnBrowse
  431. };
  432. defaultPreviewTemplates = {
  433. generic: tTagBef1 + tGeneric + tTagAft,
  434. html: tTagBef1 + tHtml + tTagAft,
  435. image: tTagBef1 + tImage + tTagAft,
  436. text: tTagBef1 + tText + tTagAft,
  437. video: tTagBef2 + tVideo + tTagAft,
  438. audio: tTagBef2 + tAudio + tTagAft,
  439. flash: tTagBef2 + tFlash + tTagAft,
  440. object: tTagBef2 + tObject + tTagAft,
  441. pdf: tTagBef2 + tPdf + tTagAft,
  442. other: tTagBef2 + tOther + tTagAft
  443. };
  444. defaultPreviewTypes = ['image', 'html', 'text', 'video', 'audio', 'flash', 'pdf', 'object'];
  445. defaultPreviewSettings = {
  446. image: {width: "auto", height: "160px"},
  447. html: {width: "213px", height: "160px"},
  448. text: {width: "213px", height: "160px"},
  449. video: {width: "213px", height: "160px"},
  450. audio: {width: "213px", height: "80px"},
  451. flash: {width: "213px", height: "160px"},
  452. object: {width: "160px", height: "160px"},
  453. pdf: {width: "160px", height: "160px"},
  454. other: {width: "160px", height: "160px"}
  455. };
  456. defaultPreviewZoomSettings = {
  457. image: {width: "auto", height: "auto", 'max-width': "100%", 'max-height': "100%"},
  458. html: {width: "100%", height: "100%", 'min-height': "480px"},
  459. text: {width: "100%", height: "100%", 'min-height': "480px"},
  460. video: {width: "auto", height: "100%", 'max-width': "100%"},
  461. audio: {width: "100%", height: "30px"},
  462. flash: {width: "auto", height: "480px"},
  463. object: {width: "auto", height: "100%", 'min-height': "480px"},
  464. pdf: {width: "100%", height: "100%", 'min-height': "480px"},
  465. other: {width: "auto", height: "100%", 'min-height': "480px"}
  466. };
  467. defaultFileTypeSettings = {
  468. image: function (vType, vName) {
  469. return compare(vType, 'image.*') || compare(vName, /\.(gif|png|jpe?g)$/i);
  470. },
  471. html: function (vType, vName) {
  472. return compare(vType, 'text/html') || compare(vName, /\.(htm|html)$/i);
  473. },
  474. text: function (vType, vName) {
  475. return compare(vType, 'text.*') || compare(vName, /\.(xml|javascript)$/i) ||
  476. compare(vName, /\.(txt|md|csv|nfo|ini|json|php|js|css)$/i);
  477. },
  478. video: function (vType, vName) {
  479. return compare(vType, 'video.*') && (compare(vType, /(ogg|mp4|mp?g|mov|webm|3gp)$/i) ||
  480. compare(vName, /\.(og?|mp4|webm|mp?g|mov|3gp)$/i));
  481. },
  482. audio: function (vType, vName) {
  483. return compare(vType, 'audio.*') && (compare(vName, /(ogg|mp3|mp?g|wav)$/i) ||
  484. compare(vName, /\.(og?|mp3|mp?g|wav)$/i));
  485. },
  486. flash: function (vType, vName) {
  487. return compare(vType, 'application/x-shockwave-flash', true) || compare(vName, /\.(swf)$/i);
  488. },
  489. pdf: function (vType, vName) {
  490. return compare(vType, 'application/pdf', true) || compare(vName, /\.(pdf)$/i);
  491. },
  492. object: function () {
  493. return true;
  494. },
  495. other: function () {
  496. return true;
  497. }
  498. };
  499. isEmpty = function (value, trim) {
  500. return value === undefined || value === null || value.length === 0 || (trim && $.trim(value) === '');
  501. };
  502. isArray = function (a) {
  503. return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]';
  504. };
  505. ifSet = function (needle, haystack, def) {
  506. def = def || '';
  507. return (haystack && typeof haystack === 'object' && needle in haystack) ? haystack[needle] : def;
  508. };
  509. getElement = function (options, param, value) {
  510. return (isEmpty(options) || isEmpty(options[param])) ? value : $(options[param]);
  511. };
  512. uniqId = function () {
  513. return Math.round(new Date().getTime() + (Math.random() * 100));
  514. };
  515. htmlEncode = function (str) {
  516. return str.replace(/&/g, '&amp;')
  517. .replace(/</g, '&lt;')
  518. .replace(/>/g, '&gt;')
  519. .replace(/"/g, '&quot;')
  520. .replace(/'/g, '&apos;');
  521. };
  522. replaceTags = function (str, tags) {
  523. var out = str;
  524. if (!tags) {
  525. return out;
  526. }
  527. $.each(tags, function (key, value) {
  528. if (typeof value === "function") {
  529. value = value();
  530. }
  531. out = out.split(key).join(value);
  532. });
  533. return out;
  534. };
  535. cleanMemory = function ($thumb) {
  536. var data = $thumb.is('img') ? $thumb.attr('src') : $thumb.find('source').attr('src');
  537. /** @namespace objUrl.revokeObjectURL */
  538. objUrl.revokeObjectURL(data);
  539. };
  540. findFileName = function (filePath) {
  541. var sepIndex = filePath.lastIndexOf('/');
  542. if (sepIndex === -1) {
  543. sepIndex = filePath.lastIndexOf('\\');
  544. }
  545. return filePath.split(filePath.substring(sepIndex, sepIndex + 1)).pop();
  546. };
  547. checkFullScreen = function () {
  548. //noinspection JSUnresolvedVariable
  549. return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement ||
  550. document.msFullscreenElement;
  551. };
  552. toggleFullScreen = function (maximize) {
  553. var doc = document, de = doc.documentElement;
  554. if (de && maximize && !checkFullScreen()) {
  555. /** @namespace document.requestFullscreen */
  556. /** @namespace document.msRequestFullscreen */
  557. /** @namespace document.mozRequestFullScreen */
  558. /** @namespace document.webkitRequestFullscreen */
  559. /** @namespace Element.ALLOW_KEYBOARD_INPUT */
  560. if (de.requestFullscreen) {
  561. de.requestFullscreen();
  562. } else if (de.msRequestFullscreen) {
  563. de.msRequestFullscreen();
  564. } else if (de.mozRequestFullScreen) {
  565. de.mozRequestFullScreen();
  566. } else if (de.webkitRequestFullscreen) {
  567. de.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
  568. }
  569. } else {
  570. /** @namespace document.exitFullscreen */
  571. /** @namespace document.msExitFullscreen */
  572. /** @namespace document.mozCancelFullScreen */
  573. /** @namespace document.webkitExitFullscreen */
  574. if (doc.exitFullscreen) {
  575. doc.exitFullscreen();
  576. } else if (doc.msExitFullscreen) {
  577. doc.msExitFullscreen();
  578. } else if (doc.mozCancelFullScreen) {
  579. doc.mozCancelFullScreen();
  580. } else if (doc.webkitExitFullscreen) {
  581. doc.webkitExitFullscreen();
  582. }
  583. }
  584. };
  585. moveArray = function (arr, oldIndex, newIndex) {
  586. if (newIndex >= arr.length) {
  587. var k = newIndex - arr.length;
  588. while ((k--) + 1) {
  589. arr.push(undefined);
  590. }
  591. }
  592. arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]);
  593. return arr;
  594. };
  595. FileInput = function (element, options) {
  596. var self = this;
  597. self.$element = $(element);
  598. if (!self._validate()) {
  599. return;
  600. }
  601. self.isPreviewable = hasFileAPISupport();
  602. self.isIE9 = isIE(9);
  603. self.isIE10 = isIE(10);
  604. if (self.isPreviewable || self.isIE9) {
  605. self._init(options);
  606. self._listen();
  607. } else {
  608. self.$element.removeClass('file-loading');
  609. }
  610. };
  611. FileInput.prototype = {
  612. constructor: FileInput,
  613. _init: function (options) {
  614. var self = this, $el = self.$element, t;
  615. $.each(options, function (key, value) {
  616. switch (key) {
  617. case 'minFileCount':
  618. case 'maxFileCount':
  619. case 'maxFileSize':
  620. self[key] = getNum(value);
  621. break;
  622. default:
  623. self[key] = value;
  624. break;
  625. }
  626. });
  627. self.fileInputCleared = false;
  628. self.fileBatchCompleted = true;
  629. if (!self.isPreviewable) {
  630. self.showPreview = false;
  631. }
  632. if (self.allowedPreviewTypes === undefined) {
  633. self.allowedPreviewTypes = defaultPreviewTypes;
  634. }
  635. self.uploadFileAttr = !isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data';
  636. self.reader = null;
  637. self.formdata = {};
  638. self.clearStack();
  639. self.uploadCount = 0;
  640. self.uploadStatus = {};
  641. self.uploadLog = [];
  642. self.uploadAsyncCount = 0;
  643. self.loadedImages = [];
  644. self.totalImagesCount = 0;
  645. self.ajaxRequests = [];
  646. self.isError = false;
  647. self.ajaxAborted = false;
  648. self.cancelling = false;
  649. t = self._getLayoutTemplate('progress');
  650. self.progressTemplate = t.replace('{class}', self.progressClass);
  651. self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass);
  652. self.progressErrorTemplate = t.replace('{class}', self.progressErrorClass);
  653. self.dropZoneEnabled = hasDragDropSupport() && self.dropZoneEnabled;
  654. self.isDisabled = self.$element.attr('disabled') || self.$element.attr('readonly');
  655. self.isUploadable = hasFileUploadSupport() && !isEmpty(self.uploadUrl);
  656. self.isClickable = self.browseOnZoneClick && self.showPreview &&
  657. (self.isUploadable && self.dropZoneEnabled || !isEmpty(self.defaultPreviewContent));
  658. self.slug = typeof options.slugCallback === "function" ? options.slugCallback : self._slugDefault;
  659. self.mainTemplate = self.showCaption ? self._getLayoutTemplate('main1') : self._getLayoutTemplate('main2');
  660. self.captionTemplate = self._getLayoutTemplate('caption');
  661. self.previewGenericTemplate = self._getPreviewTemplate('generic');
  662. if (self.resizeImage && (self.maxImageWidth || self.maxImageHeight)) {
  663. self.imageCanvas = document.createElement('canvas');
  664. self.imageCanvasContext = self.imageCanvas.getContext('2d');
  665. }
  666. if (isEmpty(self.$element.attr('id'))) {
  667. self.$element.attr('id', uniqId());
  668. }
  669. if (self.$container === undefined) {
  670. self.$container = self._createContainer();
  671. } else {
  672. self._refreshContainer();
  673. }
  674. self.$dropZone = self.$container.find('.file-drop-zone');
  675. self.$progress = self.$container.find('.kv-upload-progress');
  676. self.$btnUpload = self.$container.find('.fileinput-upload');
  677. self.$captionContainer = getElement(options, 'elCaptionContainer', self.$container.find('.file-caption'));
  678. self.$caption = getElement(options, 'elCaptionText', self.$container.find('.file-caption-name'));
  679. self.$previewContainer = getElement(options, 'elPreviewContainer', self.$container.find('.file-preview'));
  680. self.$preview = getElement(options, 'elPreviewImage', self.$container.find('.file-preview-thumbnails'));
  681. self.$previewStatus = getElement(options, 'elPreviewStatus', self.$container.find('.file-preview-status'));
  682. self.$errorContainer = getElement(options, 'elErrorContainer',
  683. self.$previewContainer.find('.kv-fileinput-error'));
  684. if (!isEmpty(self.msgErrorClass)) {
  685. addCss(self.$errorContainer, self.msgErrorClass);
  686. }
  687. self.$errorContainer.hide();
  688. self.fileActionSettings = $.extend(true, defaultFileActionSettings, options.fileActionSettings);
  689. self.previewInitId = "preview-" + uniqId();
  690. self.id = self.$element.attr('id');
  691. previewCache.init(self);
  692. self._initPreview(true);
  693. self._initPreviewActions();
  694. self.options = options;
  695. self._setFileDropZoneTitle();
  696. self.$element.removeClass('file-loading');
  697. if (self.$element.attr('disabled')) {
  698. self.disable();
  699. }
  700. self._initZoom();
  701. },
  702. _log: function (msg) {
  703. var self = this, id = self.$element.attr('id');
  704. if (id) {
  705. msg = '"' + id + '": ' + msg;
  706. }
  707. if (typeof window.console.log !== "undefined") {
  708. window.console.log(msg);
  709. } else {
  710. window.alert(msg);
  711. }
  712. },
  713. _validate: function () {
  714. var self = this, status = self.$element.attr('type') === 'file';
  715. if (!status) {
  716. self._log('The input "type" must be set to "file" for initializing the "bootstrap-fileinput" plugin.');
  717. }
  718. return status;
  719. },
  720. _errorsExist: function () {
  721. var self = this, $err;
  722. if (self.$errorContainer.find('li').length) {
  723. return true;
  724. }
  725. $err = $(document.createElement('div')).html(self.$errorContainer.html());
  726. $err.find('span.kv-error-close').remove();
  727. $err.find('ul').remove();
  728. return $.trim($err.text()).length ? true : false;
  729. },
  730. _errorHandler: function (evt, caption) {
  731. var self = this, err = evt.target.error;
  732. /** @namespace err.NOT_FOUND_ERR */
  733. /** @namespace err.SECURITY_ERR */
  734. /** @namespace err.NOT_READABLE_ERR */
  735. if (err.code === err.NOT_FOUND_ERR) {
  736. self._showError(self.msgFileNotFound.replace('{name}', caption));
  737. } else if (err.code === err.SECURITY_ERR) {
  738. self._showError(self.msgFileSecured.replace('{name}', caption));
  739. } else if (err.code === err.NOT_READABLE_ERR) {
  740. self._showError(self.msgFileNotReadable.replace('{name}', caption));
  741. } else if (err.code === err.ABORT_ERR) {
  742. self._showError(self.msgFilePreviewAborted.replace('{name}', caption));
  743. } else {
  744. self._showError(self.msgFilePreviewError.replace('{name}', caption));
  745. }
  746. },
  747. _addError: function (msg) {
  748. var self = this, $error = self.$errorContainer;
  749. if (msg && $error.length) {
  750. $error.html(self.errorCloseButton + msg);
  751. handler($error.find('.kv-error-close'), 'click', function () {
  752. $error.fadeOut('slow');
  753. });
  754. }
  755. },
  756. _resetErrors: function (fade) {
  757. var self = this, $error = self.$errorContainer;
  758. self.isError = false;
  759. self.$container.removeClass('has-error');
  760. $error.html('');
  761. if (fade) {
  762. $error.fadeOut('slow');
  763. } else {
  764. $error.hide();
  765. }
  766. },
  767. _showFolderError: function (folders) {
  768. var self = this, $error = self.$errorContainer, msg;
  769. if (!folders) {
  770. return;
  771. }
  772. msg = self.msgFoldersNotAllowed.replace(/\{n}/g, folders);
  773. self._addError(msg);
  774. addCss(self.$container, 'has-error');
  775. $error.fadeIn(800);
  776. self._raise('filefoldererror', [folders, msg]);
  777. },
  778. _showUploadError: function (msg, params, event) {
  779. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror', e = params && params.id ?
  780. '<li data-file-id="' + params.id + '">' + msg + '</li>' : '<li>' + msg + '</li>';
  781. if ($error.find('ul').length === 0) {
  782. self._addError('<ul>' + e + '</ul>');
  783. } else {
  784. $error.find('ul').append(e);
  785. }
  786. $error.fadeIn(800);
  787. self._raise(ev, [params, msg]);
  788. self.$container.removeClass('file-input-new');
  789. addCss(self.$container, 'has-error');
  790. return true;
  791. },
  792. _showError: function (msg, params, event) {
  793. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  794. params = params || {};
  795. params.reader = self.reader;
  796. self._addError(msg);
  797. $error.fadeIn(800);
  798. self._raise(ev, [params, msg]);
  799. if (!self.isUploadable) {
  800. self._clearFileInput();
  801. }
  802. self.$container.removeClass('file-input-new');
  803. addCss(self.$container, 'has-error');
  804. self.$btnUpload.attr('disabled', true);
  805. return true;
  806. },
  807. _noFilesError: function (params) {
  808. var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle,
  809. msg = self.msgFilesTooLess.replace('{n}', self.minFileCount).replace('{files}', label),
  810. $error = self.$errorContainer;
  811. self._addError(msg);
  812. self.isError = true;
  813. self._updateFileDetails(0);
  814. $error.fadeIn(800);
  815. self._raise('fileerror', [params, msg]);
  816. self._clearFileInput();
  817. addCss(self.$container, 'has-error');
  818. },
  819. _parseError: function (jqXHR, errorThrown, fileName) {
  820. /** @namespace jqXHR.responseJSON */
  821. var self = this, errMsg = $.trim(errorThrown + ''),
  822. dot = errMsg.slice(-1) === '.' ? '' : '.',
  823. text = jqXHR.responseJSON !== undefined && jqXHR.responseJSON.error !== undefined ?
  824. jqXHR.responseJSON.error : jqXHR.responseText;
  825. if (self.cancelling && self.msgUploadAborted) {
  826. errMsg = self.msgUploadAborted;
  827. }
  828. if (self.showAjaxErrorDetails && text) {
  829. text = $.trim(text.replace(/\n\s*\n/g, '\n'));
  830. text = text.length > 0 ? '<pre>' + text + '</pre>' : '';
  831. errMsg += dot + text;
  832. } else {
  833. errMsg += dot;
  834. }
  835. self.cancelling = false;
  836. return fileName ? '<b>' + fileName + ': </b>' + errMsg : errMsg;
  837. },
  838. _parseFileType: function (file) {
  839. var self = this, isValid, vType, cat, i;
  840. for (i = 0; i < defaultPreviewTypes.length; i += 1) {
  841. cat = defaultPreviewTypes[i];
  842. isValid = ifSet(cat, self.fileTypeSettings, defaultFileTypeSettings[cat]);
  843. vType = isValid(file.type, file.name) ? cat : '';
  844. if (!isEmpty(vType)) {
  845. return vType;
  846. }
  847. }
  848. return 'other';
  849. },
  850. _getPreviewIcon: function (fname) {
  851. var self = this, ext, out = null;
  852. if (fname && fname.indexOf('.') > -1) {
  853. ext = fname.split('.').pop();
  854. if (self.previewFileIconSettings && self.previewFileIconSettings[ext]) {
  855. out = self.previewFileIconSettings[ext];
  856. }
  857. if (self.previewFileExtSettings) {
  858. $.each(self.previewFileExtSettings, function (key, func) {
  859. if (self.previewFileIconSettings[key] && func(ext)) {
  860. out = self.previewFileIconSettings[key];
  861. //noinspection UnnecessaryReturnStatementJS
  862. return;
  863. }
  864. });
  865. }
  866. }
  867. return out;
  868. },
  869. _parseFilePreviewIcon: function (content, fname) {
  870. var self = this, icn = self._getPreviewIcon(fname) || self.previewFileIcon;
  871. if (content.indexOf('{previewFileIcon}') > -1) {
  872. content = content.replace(/\{previewFileIconClass}/g, self.previewFileIconClass).replace(
  873. /\{previewFileIcon}/g, icn);
  874. }
  875. return content;
  876. },
  877. _raise: function (event, params) {
  878. var self = this, e = $.Event(event);
  879. if (params !== undefined) {
  880. self.$element.trigger(e, params);
  881. } else {
  882. self.$element.trigger(e);
  883. }
  884. if (e.isDefaultPrevented()) {
  885. return false;
  886. }
  887. if (!e.result) {
  888. return e.result;
  889. }
  890. switch (event) {
  891. // ignore these events
  892. case 'filebatchuploadcomplete':
  893. case 'filebatchuploadsuccess':
  894. case 'fileuploaded':
  895. case 'fileclear':
  896. case 'filecleared':
  897. case 'filereset':
  898. case 'fileerror':
  899. case 'filefoldererror':
  900. case 'fileuploaderror':
  901. case 'filebatchuploaderror':
  902. case 'filedeleteerror':
  903. case 'filecustomerror':
  904. case 'filesuccessremove':
  905. break;
  906. // receive data response via `filecustomerror` event`
  907. default:
  908. self.ajaxAborted = e.result;
  909. break;
  910. }
  911. return true;
  912. },
  913. _listenFullScreen: function (isFullScreen) {
  914. var self = this, $modal = self.$modal, $btnFull, $btnBord;
  915. if (!$modal || !$modal.length) {
  916. return;
  917. }
  918. $btnFull = $modal && $modal.find('.btn-fullscreen');
  919. $btnBord = $modal && $modal.find('.btn-borderless');
  920. if (!$btnFull.length || !$btnBord.length) {
  921. return;
  922. }
  923. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  924. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  925. if (isFullScreen) {
  926. $btnFull.addClass('active').attr('aria-pressed', 'true');
  927. } else {
  928. $btnBord.addClass('active').attr('aria-pressed', 'true');
  929. }
  930. if ($modal.hasClass('file-zoom-fullscreen')) {
  931. self._maximizeZoomDialog();
  932. } else {
  933. if (isFullScreen) {
  934. self._maximizeZoomDialog();
  935. } else {
  936. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  937. }
  938. }
  939. },
  940. _listen: function () {
  941. var self = this, $el = self.$element, $form = $el.closest('form'), $cont = self.$container;
  942. handler($el, 'change', $.proxy(self._change, self));
  943. if (self.showBrowse) {
  944. handler(self.$btnFile, 'click', $.proxy(self._browse, self));
  945. }
  946. handler($form, 'reset', $.proxy(self.reset, self));
  947. handler($cont.find('.fileinput-remove:not([disabled])'), 'click', $.proxy(self.clear, self));
  948. handler($cont.find('.fileinput-cancel'), 'click', $.proxy(self.cancel, self));
  949. self._initDragDrop();
  950. if (!self.isUploadable) {
  951. handler($form, 'submit', $.proxy(self._submitForm, self));
  952. }
  953. handler(self.$container.find('.fileinput-upload'), 'click', $.proxy(self._uploadClick, self));
  954. handler($(window), 'resize', function () {
  955. self._listenFullScreen(screen.width === window.innerWidth && screen.height === window.innerHeight);
  956. });
  957. handler($(document), 'webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange',
  958. function () {
  959. self._listenFullScreen(checkFullScreen());
  960. });
  961. self._initClickable();
  962. },
  963. _initClickable: function () {
  964. var self = this, $zone;
  965. if (!self.isClickable) {
  966. return;
  967. }
  968. $zone = self.isUploadable ? self.$dropZone : self.$preview.find('.file-default-preview');
  969. addCss($zone, 'clickable');
  970. $zone.attr('tabindex', -1);
  971. handler($zone, 'click', function (e) {
  972. var $tar = $(e.target);
  973. if (!$tar.parents('.file-preview-thumbnails').length || $tar.parents('.file-default-preview').length) {
  974. self.$element.trigger('click');
  975. $zone.blur();
  976. }
  977. });
  978. },
  979. _initDragDrop: function () {
  980. var self = this, $zone = self.$dropZone;
  981. if (self.isUploadable && self.dropZoneEnabled && self.showPreview) {
  982. handler($zone, 'dragenter dragover', $.proxy(self._zoneDragEnter, self));
  983. handler($zone, 'dragleave', $.proxy(self._zoneDragLeave, self));
  984. handler($zone, 'drop', $.proxy(self._zoneDrop, self));
  985. handler($(document), 'dragenter dragover drop', self._zoneDragDropInit);
  986. }
  987. },
  988. _zoneDragDropInit: function (e) {
  989. e.stopPropagation();
  990. e.preventDefault();
  991. },
  992. _zoneDragEnter: function (e) {
  993. var self = this, hasFiles = $.inArray('Files', e.originalEvent.dataTransfer.types) > -1;
  994. self._zoneDragDropInit(e);
  995. if (self.isDisabled || !hasFiles) {
  996. e.originalEvent.dataTransfer.effectAllowed = 'none';
  997. e.originalEvent.dataTransfer.dropEffect = 'none';
  998. return;
  999. }
  1000. addCss(self.$dropZone, 'file-highlighted');
  1001. },
  1002. _zoneDragLeave: function (e) {
  1003. var self = this;
  1004. self._zoneDragDropInit(e);
  1005. if (self.isDisabled) {
  1006. return;
  1007. }
  1008. self.$dropZone.removeClass('file-highlighted');
  1009. },
  1010. _zoneDrop: function (e) {
  1011. var self = this;
  1012. e.preventDefault();
  1013. /** @namespace e.originalEvent.dataTransfer */
  1014. if (self.isDisabled || isEmpty(e.originalEvent.dataTransfer.files)) {
  1015. return;
  1016. }
  1017. self._change(e, 'dragdrop');
  1018. self.$dropZone.removeClass('file-highlighted');
  1019. },
  1020. _uploadClick: function (e) {
  1021. var self = this, $btn = self.$container.find('.fileinput-upload'), $form,
  1022. isEnabled = !$btn.hasClass('disabled') && isEmpty($btn.attr('disabled'));
  1023. if (e && e.isDefaultPrevented()) {
  1024. return;
  1025. }
  1026. if (!self.isUploadable) {
  1027. if (isEnabled && $btn.attr('type') !== 'submit') {
  1028. $form = $btn.closest('form');
  1029. // downgrade to normal form submit if possible
  1030. if ($form.length) {
  1031. $form.trigger('submit');
  1032. }
  1033. e.preventDefault();
  1034. }
  1035. return;
  1036. }
  1037. e.preventDefault();
  1038. if (isEnabled) {
  1039. self.upload();
  1040. }
  1041. },
  1042. _submitForm: function () {
  1043. var self = this, $el = self.$element, files = $el.get(0).files;
  1044. if (files && self.minFileCount > 0 && self._getFileCount(files.length) < self.minFileCount) {
  1045. self._noFilesError({});
  1046. return false;
  1047. }
  1048. return !self._abort({});
  1049. },
  1050. _clearPreview: function () {
  1051. var self = this, $thumbs = !self.showUploadedThumbs ? self.$preview.find(FRAMES) :
  1052. self.$preview.find(FRAMES + ':not(.file-preview-success)');
  1053. $thumbs.remove();
  1054. if (!self.$preview.find(FRAMES).length || !self.showPreview) {
  1055. self._resetUpload();
  1056. }
  1057. self._validateDefaultPreview();
  1058. },
  1059. _initSortable: function () {
  1060. var self = this, $el = self.$preview, settings, selector = '.' + SORT_CSS;
  1061. if (!window.KvSortable || $el.find(selector).length === 0) {
  1062. return;
  1063. }
  1064. //noinspection JSUnusedGlobalSymbols
  1065. settings = {
  1066. handle: '.drag-handle-init',
  1067. dataIdAttr: 'data-preview-id',
  1068. draggable: selector,
  1069. onSort: function (e) {
  1070. var oldIndex = e.oldIndex, newIndex = e.newIndex, key, $frame;
  1071. self.initialPreview = moveArray(self.initialPreview, oldIndex, newIndex);
  1072. self.initialPreviewConfig = moveArray(self.initialPreviewConfig, oldIndex, newIndex);
  1073. previewCache.init(self);
  1074. for (var i = 0; i < self.initialPreviewConfig.length; i++) {
  1075. if (self.initialPreviewConfig[i] !== null) {
  1076. key = self.initialPreviewConfig[i].key;
  1077. $frame = $(".kv-file-remove[data-key='" + key + "']").closest(FRAMES);
  1078. $frame.attr('data-fileindex', 'init_' + i).data('fileindex', 'init_' + i);
  1079. }
  1080. }
  1081. self._raise('filesorted', {
  1082. previewId: $(e.item).attr('id'),
  1083. 'oldIndex': oldIndex,
  1084. 'newIndex': newIndex,
  1085. stack: self.initialPreviewConfig
  1086. });
  1087. }
  1088. };
  1089. if ($el.data('kvsortable')) {
  1090. $el.kvsortable('destroy');
  1091. }
  1092. $.extend(true, settings, self.fileActionSettings.dragSettings);
  1093. $el.kvsortable(settings);
  1094. },
  1095. _initPreview: function (isInit) {
  1096. var self = this, cap = self.initialCaption || '', out;
  1097. if (!previewCache.count(self.id)) {
  1098. self._clearPreview();
  1099. if (isInit) {
  1100. self._setCaption(cap);
  1101. } else {
  1102. self._initCaption();
  1103. }
  1104. return;
  1105. }
  1106. out = previewCache.out(self.id);
  1107. cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
  1108. self.$preview.html(out.content);
  1109. self._setCaption(cap);
  1110. self._initSortable();
  1111. if (!isEmpty(out.content)) {
  1112. self.$container.removeClass('file-input-new');
  1113. }
  1114. },
  1115. _getZoomButton: function (type) {
  1116. var self = this, label = self.previewZoomButtonIcons[type], css = self.previewZoomButtonClasses[type],
  1117. title = ' title="' + (self.previewZoomButtonTitles[type] || '') + '" ',
  1118. params = title + (type === 'close' ? ' data-dismiss="modal" aria-hidden="true"' : '');
  1119. if (type === 'fullscreen' || type === 'borderless' || type === 'toggleheader') {
  1120. params += ' data-toggle="button" aria-pressed="false" autocomplete="off"';
  1121. }
  1122. return '<button type="button" class="' + css + ' btn-' + type + '"' + params + '>' + label + '</button>';
  1123. },
  1124. _getModalContent: function () {
  1125. var self = this;
  1126. return self._getLayoutTemplate('modal')
  1127. .replace(/\{heading}/g, self.msgZoomModalHeading)
  1128. .replace(/\{prev}/g, self._getZoomButton('prev'))
  1129. .replace(/\{next}/g, self._getZoomButton('next'))
  1130. .replace(/\{toggleheader}/g, self._getZoomButton('toggleheader'))
  1131. .replace(/\{fullscreen}/g, self._getZoomButton('fullscreen'))
  1132. .replace(/\{borderless}/g, self._getZoomButton('borderless'))
  1133. .replace(/\{close}/g, self._getZoomButton('close'));
  1134. },
  1135. _listenModalEvent: function (event) {
  1136. var self = this, $modal = self.$modal, getParams = function (e) {
  1137. return {
  1138. sourceEvent: e,
  1139. previewId: $modal.data('previewId'),
  1140. modal: $modal
  1141. };
  1142. };
  1143. $modal.on(event + '.bs.modal', function (e) {
  1144. var $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless');
  1145. self._raise('filezoom' + event, getParams(e));
  1146. if (event === 'shown') {
  1147. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1148. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  1149. if ($modal.hasClass('file-zoom-fullscreen')) {
  1150. self._maximizeZoomDialog();
  1151. if (checkFullScreen()) {
  1152. $btnFull.addClass('active').attr('aria-pressed', 'true');
  1153. } else {
  1154. $btnBord.addClass('active').attr('aria-pressed', 'true');
  1155. }
  1156. }
  1157. }
  1158. });
  1159. },
  1160. _initZoom: function () {
  1161. var self = this, $dialog, modalMain = self._getLayoutTemplate('modalMain'), modalId = '#' + MODAL_ID;
  1162. self.$modal = $(modalId);
  1163. if (!self.$modal || !self.$modal.length) {
  1164. $dialog = $(document.createElement('div')).html(modalMain).insertAfter(self.$container);
  1165. self.$modal = $('#' + MODAL_ID).insertBefore($dialog);
  1166. $dialog.remove();
  1167. }
  1168. self.$modal.html(self._getModalContent());
  1169. self._listenModalEvent('show');
  1170. self._listenModalEvent('shown');
  1171. self._listenModalEvent('hide');
  1172. self._listenModalEvent('hidden');
  1173. self._listenModalEvent('loaded');
  1174. },
  1175. _initZoomButtons: function () {
  1176. var self = this, previewId = self.$modal.data('previewId') || '', $first, $last,
  1177. thumbs = self.$preview.find(FRAMES).toArray(), len = thumbs.length,
  1178. $prev = self.$modal.find('.btn-prev'), $next = self.$modal.find('.btn-next');
  1179. if (!len) {
  1180. return;
  1181. }
  1182. $first = $(thumbs[0]);
  1183. $last = $(thumbs[len - 1]);
  1184. $prev.removeAttr('disabled');
  1185. $next.removeAttr('disabled');
  1186. if ($first.length && $first.attr('id') === previewId) {
  1187. $prev.attr('disabled', true);
  1188. }
  1189. if ($last.length && $last.attr('id') === previewId) {
  1190. $next.attr('disabled', true);
  1191. }
  1192. },
  1193. _maximizeZoomDialog: function () {
  1194. var self = this, $modal = self.$modal, $head = $modal.find('.modal-header:visible'),
  1195. $foot = $modal.find('.modal-footer:visible'), $body = $modal.find('.modal-body'),
  1196. h = $(window).height(), diff = 0;
  1197. $modal.addClass('file-zoom-fullscreen');
  1198. if ($head && $head.length) {
  1199. h -= $head.outerHeight(true);
  1200. }
  1201. if ($foot && $foot.length) {
  1202. h -= $foot.outerHeight(true);
  1203. }
  1204. if ($body && $body.length) {
  1205. diff = $body.outerHeight(true) - $body.height();
  1206. h -= diff;
  1207. }
  1208. $modal.find('.kv-zoom-body').height(h);
  1209. },
  1210. _resizeZoomDialog: function (fullScreen) {
  1211. var self = this, $modal = self.$modal, $btnFull = $modal.find('.btn-fullscreen'),
  1212. $btnBord = $modal.find('.btn-borderless');
  1213. if ($modal.hasClass('file-zoom-fullscreen')) {
  1214. toggleFullScreen(false);
  1215. if (!fullScreen) {
  1216. if (!$btnFull.hasClass('active')) {
  1217. $modal.removeClass('file-zoom-fullscreen');
  1218. self.$modal.find('.kv-zoom-body').css('height', self.zoomModalHeight);
  1219. } else {
  1220. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  1221. }
  1222. } else {
  1223. if (!$btnFull.hasClass('active')) {
  1224. $modal.removeClass('file-zoom-fullscreen');
  1225. self._resizeZoomDialog(true);
  1226. if ($btnBord.hasClass('active')) {
  1227. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1228. }
  1229. }
  1230. }
  1231. } else {
  1232. if (!fullScreen) {
  1233. self._maximizeZoomDialog();
  1234. return;
  1235. }
  1236. toggleFullScreen(true);
  1237. }
  1238. $modal.focus();
  1239. },
  1240. _setZoomContent: function ($preview, animate) {
  1241. var self = this, $content, tmplt, body, title, $body, $dataEl, config, previewId = $preview.attr('id'),
  1242. $modal = self.$modal, $prev = $modal.find('.btn-prev'), $next = $modal.find('.btn-next'), $tmp,
  1243. $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless'),
  1244. $btnTogh = $modal.find('.btn-toggleheader'),
  1245. $zoomPreview = self.$preview.find('#zoom-' + previewId);
  1246. tmplt = $zoomPreview.attr('data-template') || 'generic';
  1247. $content = $zoomPreview.find('.kv-file-content');
  1248. body = $content.length ? $content.html() : '';
  1249. title = $zoomPreview.find('.file-footer-caption').text() || '';
  1250. $modal.find('.kv-zoom-title').html(title);
  1251. $body = $modal.find('.kv-zoom-body');
  1252. if (animate) {
  1253. $tmp = $body.clone().insertAfter($body);
  1254. $body.html(body).hide();
  1255. $tmp.fadeOut('fast', function () {
  1256. $body.fadeIn('fast');
  1257. $tmp.remove();
  1258. });
  1259. } else {
  1260. $body.html(body);
  1261. }
  1262. config = self.previewZoomSettings[tmplt];
  1263. if (config) {
  1264. $dataEl = $body.find('.kv-preview-data');
  1265. addCss($dataEl, 'file-zoom-detail');
  1266. $.each(config, function (key, value) {
  1267. $dataEl.css(key, value);
  1268. if (($dataEl.attr('width') && key === 'width') || ($dataEl.attr('height') && key === 'height')) {
  1269. $dataEl.removeAttr(key);
  1270. }
  1271. });
  1272. }
  1273. $modal.data('previewId', previewId);
  1274. handler($prev, 'click', function () {
  1275. self._zoomSlideShow('prev', previewId);
  1276. });
  1277. handler($next, 'click', function () {
  1278. self._zoomSlideShow('next', previewId);
  1279. });
  1280. handler($btnFull, 'click', function () {
  1281. self._resizeZoomDialog(true);
  1282. });
  1283. handler($btnBord, 'click', function () {
  1284. self._resizeZoomDialog(false);
  1285. });
  1286. handler($btnTogh, 'click', function () {
  1287. var $header = $modal.find('.modal-header'), $floatBar = $modal.find('.modal-body .floating-buttons'),
  1288. ht, $actions = $header.find('.kv-zoom-actions'), resize = function (height) {
  1289. var $body = self.$modal.find('.kv-zoom-body'), h = self.zoomModalHeight;
  1290. if ($modal.hasClass('file-zoom-fullscreen')) {
  1291. h = $body.outerHeight(true);
  1292. if (!height) {
  1293. h = h - $header.outerHeight(true);
  1294. }
  1295. }
  1296. $body.css('height', height ? h + height : h);
  1297. };
  1298. if ($header.is(':visible')) {
  1299. ht = $header.outerHeight(true);
  1300. $header.slideUp('slow', function () {
  1301. $actions.find('.btn').appendTo($floatBar);
  1302. resize(ht);
  1303. });
  1304. } else {
  1305. $floatBar.find('.btn').appendTo($actions);
  1306. $header.slideDown('slow', function () {
  1307. resize();
  1308. });
  1309. }
  1310. $modal.focus();
  1311. });
  1312. handler($modal, 'keydown', function (e) {
  1313. var key = e.which || e.keyCode;
  1314. if (key === 37 && !$prev.attr('disabled')) {
  1315. self._zoomSlideShow('prev', previewId);
  1316. }
  1317. if (key === 39 && !$next.attr('disabled')) {
  1318. self._zoomSlideShow('next', previewId);
  1319. }
  1320. });
  1321. },
  1322. _zoomPreview: function ($btn) {
  1323. var self = this, $preview;
  1324. if (!$btn.length) {
  1325. throw 'Cannot zoom to detailed preview!';
  1326. }
  1327. self.$modal.html(self._getModalContent());
  1328. $preview = $btn.closest(FRAMES);
  1329. self._setZoomContent($preview);
  1330. self.$modal.modal('show');
  1331. self._initZoomButtons();
  1332. },
  1333. _zoomSlideShow: function (dir, previewId) {
  1334. var self = this, $btn = self.$modal.find('.kv-zoom-actions .btn-' + dir), $targFrame, i,
  1335. thumbs = self.$preview.find(FRAMES).toArray(), len = thumbs.length, out;
  1336. if ($btn.attr('disabled')) {
  1337. return;
  1338. }
  1339. for (i = 0; i < len; i++) {
  1340. if ($(thumbs[i]).attr('id') === previewId) {
  1341. out = dir === 'prev' ? i - 1 : i + 1;
  1342. break;
  1343. }
  1344. }
  1345. if (out < 0 || out >= len || !thumbs[out]) {
  1346. return;
  1347. }
  1348. $targFrame = $(thumbs[out]);
  1349. if ($targFrame.length) {
  1350. self._setZoomContent($targFrame, true);
  1351. }
  1352. self._initZoomButtons();
  1353. self._raise('filezoom' + dir, {'previewId': previewId, modal: self.$modal});
  1354. },
  1355. _initZoomButton: function () {
  1356. var self = this;
  1357. self.$preview.find('.kv-file-zoom').each(function () {
  1358. var $el = $(this);
  1359. handler($el, 'click', function () {
  1360. self._zoomPreview($el);
  1361. });
  1362. });
  1363. },
  1364. _initPreviewActions: function () {
  1365. var self = this, $preview = self.$preview, deleteExtraData = self.deleteExtraData || {},
  1366. btnRemove = FRAMES + ' .kv-file-remove',
  1367. resetProgress = function () {
  1368. var hasFiles = self.isUploadable ? previewCache.count(self.id) : self.$element.get(0).files.length;
  1369. if ($preview.find(btnRemove).length === 0 && !hasFiles) {
  1370. self.reset();
  1371. self.initialCaption = '';
  1372. }
  1373. };
  1374. self._initZoomButton();
  1375. $preview.find(btnRemove).each(function () {
  1376. var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key');
  1377. if (isEmpty(vUrl) || vKey === undefined) {
  1378. return;
  1379. }
  1380. var $frame = $el.closest(FRAMES), cache = previewCache.data[self.id],
  1381. settings, params, index = $frame.data('fileindex'), config, extraData;
  1382. index = parseInt(index.replace('init_', ''));
  1383. config = isEmpty(cache.config) && isEmpty(cache.config[index]) ? null : cache.config[index];
  1384. extraData = isEmpty(config) || isEmpty(config.extra) ? deleteExtraData : config.extra;
  1385. if (typeof extraData === "function") {
  1386. extraData = extraData();
  1387. }
  1388. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  1389. settings = $.extend(true, {}, {
  1390. url: vUrl,
  1391. type: 'POST',
  1392. dataType: 'json',
  1393. data: $.extend(true, {}, {key: vKey}, extraData),
  1394. beforeSend: function (jqXHR) {
  1395. self.ajaxAborted = false;
  1396. self._raise('filepredelete', [vKey, jqXHR, extraData]);
  1397. if (self.ajaxAborted) {
  1398. jqXHR.abort();
  1399. } else {
  1400. addCss($frame, 'file-uploading');
  1401. addCss($el, 'disabled');
  1402. }
  1403. },
  1404. success: function (data, textStatus, jqXHR) {
  1405. var n, cap;
  1406. if (isEmpty(data) || isEmpty(data.error)) {
  1407. previewCache.init(self);
  1408. index = parseInt(($frame.data('fileindex')).replace('init_', ''));
  1409. previewCache.unset(self, index);
  1410. n = previewCache.count(self.id);
  1411. cap = n > 0 ? self._getMsgSelected(n) : '';
  1412. self._raise('filedeleted', [vKey, jqXHR, extraData]);
  1413. self._setCaption(cap);
  1414. } else {
  1415. params.jqXHR = jqXHR;
  1416. params.response = data;
  1417. self._showError(data.error, params, 'filedeleteerror');
  1418. $frame.removeClass('file-uploading');
  1419. $el.removeClass('disabled');
  1420. resetProgress();
  1421. return;
  1422. }
  1423. $frame.removeClass('file-uploading').addClass('file-deleted');
  1424. $frame.fadeOut('slow', function () {
  1425. var $zoom = $preview.find('#zoom-' + $frame.attr('id'));
  1426. if ($zoom.length) {
  1427. $zoom.closest('.kv-zoom-cache').remove();
  1428. }
  1429. self._clearObjects($frame);
  1430. $frame.remove();
  1431. resetProgress();
  1432. if (!n && self.getFileStack().length === 0) {
  1433. self._setCaption('');
  1434. self.reset();
  1435. }
  1436. });
  1437. },
  1438. error: function (jqXHR, textStatus, errorThrown) {
  1439. var errMsg = self._parseError(jqXHR, errorThrown);
  1440. params.jqXHR = jqXHR;
  1441. params.response = {};
  1442. self._showError(errMsg, params, 'filedeleteerror');
  1443. $frame.removeClass('file-uploading');
  1444. resetProgress();
  1445. }
  1446. }, self.ajaxDeleteSettings);
  1447. handler($el, 'click', function () {
  1448. if (!self._validateMinCount()) {
  1449. return false;
  1450. }
  1451. $.ajax(settings);
  1452. });
  1453. });
  1454. },
  1455. _clearObjects: function ($el) {
  1456. $el.find('video audio').each(function () {
  1457. this.pause();
  1458. $(this).remove();
  1459. });
  1460. $el.find('img object div').each(function () {
  1461. $(this).remove();
  1462. });
  1463. },
  1464. _clearFileInput: function () {
  1465. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  1466. self.fileInputCleared = true;
  1467. if (isEmpty($el.val())) {
  1468. return;
  1469. }
  1470. // Fix for IE ver < 11, that does not clear file inputs. Requires a sequence of steps to prevent IE
  1471. // crashing but still allow clearing of the file input.
  1472. if (self.isIE9 || self.isIE10) {
  1473. $srcFrm = $el.closest('form');
  1474. $tmpFrm = $(document.createElement('form'));
  1475. $tmpEl = $(document.createElement('div'));
  1476. $el.before($tmpEl);
  1477. if ($srcFrm.length) {
  1478. $srcFrm.after($tmpFrm);
  1479. } else {
  1480. $tmpEl.after($tmpFrm);
  1481. }
  1482. $tmpFrm.append($el).trigger('reset');
  1483. $tmpEl.before($el).remove();
  1484. $tmpFrm.remove();
  1485. } else { // normal input clear behavior for other sane browsers
  1486. $el.val('');
  1487. }
  1488. },
  1489. _resetUpload: function () {
  1490. var self = this;
  1491. self.uploadCache = {content: [], config: [], tags: [], append: true};
  1492. self.uploadCount = 0;
  1493. self.uploadStatus = {};
  1494. self.uploadLog = [];
  1495. self.uploadAsyncCount = 0;
  1496. self.loadedImages = [];
  1497. self.totalImagesCount = 0;
  1498. self.$btnUpload.removeAttr('disabled');
  1499. self._setProgress(0);
  1500. addCss(self.$progress, 'hide');
  1501. self._resetErrors(false);
  1502. self.ajaxAborted = false;
  1503. self.ajaxRequests = [];
  1504. self._resetCanvas();
  1505. self.cacheInitialPreview = {};
  1506. },
  1507. _resetCanvas: function () {
  1508. var self = this;
  1509. if (self.canvas && self.imageCanvasContext) {
  1510. self.imageCanvasContext.clearRect(0, 0, self.canvas.width, self.canvas.height);
  1511. }
  1512. },
  1513. _hasInitialPreview: function () {
  1514. var self = this;
  1515. return !self.overwriteInitial && previewCache.count(self.id);
  1516. },
  1517. _resetPreview: function () {
  1518. var self = this, out, cap;
  1519. if (previewCache.count(self.id)) {
  1520. out = previewCache.out(self.id);
  1521. self.$preview.html(out.content);
  1522. cap = self.initialCaption ? self.initialCaption : out.caption;
  1523. self._setCaption(cap);
  1524. } else {
  1525. self._clearPreview();
  1526. self._initCaption();
  1527. }
  1528. if (self.showPreview) {
  1529. self._initZoom();
  1530. self._initSortable();
  1531. }
  1532. },
  1533. _clearDefaultPreview: function () {
  1534. var self = this;
  1535. self.$preview.find('.file-default-preview').remove();
  1536. },
  1537. _validateDefaultPreview: function () {
  1538. var self = this;
  1539. if (!self.showPreview || isEmpty(self.defaultPreviewContent)) {
  1540. return;
  1541. }
  1542. self.$preview.html('<div class="file-default-preview">' + self.defaultPreviewContent + '</div>');
  1543. self.$container.removeClass('file-input-new');
  1544. self._initClickable();
  1545. },
  1546. _resetPreviewThumbs: function (isAjax) {
  1547. var self = this, out;
  1548. if (isAjax) {
  1549. self._clearPreview();
  1550. self.clearStack();
  1551. return;
  1552. }
  1553. if (self._hasInitialPreview()) {
  1554. out = previewCache.out(self.id);
  1555. self.$preview.html(out.content);
  1556. self._setCaption(out.caption);
  1557. self._initPreviewActions();
  1558. } else {
  1559. self._clearPreview();
  1560. }
  1561. },
  1562. _getLayoutTemplate: function (t) {
  1563. var self = this,
  1564. template = ifSet(t, self.layoutTemplates, defaultLayoutTemplates[t]);
  1565. if (isEmpty(self.customLayoutTags)) {
  1566. return template;
  1567. }
  1568. return replaceTags(template, self.customLayoutTags);
  1569. },
  1570. _getPreviewTemplate: function (t) {
  1571. var self = this,
  1572. template = ifSet(t, self.previewTemplates, defaultPreviewTemplates[t]);
  1573. if (isEmpty(self.customPreviewTags)) {
  1574. return template;
  1575. }
  1576. return replaceTags(template, self.customPreviewTags);
  1577. },
  1578. _getOutData: function (jqXHR, responseData, filesData) {
  1579. var self = this;
  1580. jqXHR = jqXHR || {};
  1581. responseData = responseData || {};
  1582. filesData = filesData || self.filestack.slice(0) || {};
  1583. return {
  1584. form: self.formdata,
  1585. files: filesData,
  1586. filenames: self.filenames,
  1587. filescount: self.getFilesCount(),
  1588. extra: self._getExtraData(),
  1589. response: responseData,
  1590. reader: self.reader,
  1591. jqXHR: jqXHR
  1592. };
  1593. },
  1594. _getMsgSelected: function (n) {
  1595. var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural;
  1596. return n > 0 ? self.msgSelected.replace('{n}', n).replace('{files}', strFiles) : self.msgNoFilesSelected;
  1597. },
  1598. _getThumbs: function (css) {
  1599. css = css || '';
  1600. return this.$preview.find(FRAMES + ':not(.file-preview-initial)' + css);
  1601. },
  1602. _getExtraData: function (previewId, index) {
  1603. var self = this, data = self.uploadExtraData;
  1604. if (typeof self.uploadExtraData === "function") {
  1605. data = self.uploadExtraData(previewId, index);
  1606. }
  1607. return data;
  1608. },
  1609. _initXhr: function (xhrobj, previewId, fileCount) {
  1610. var self = this;
  1611. if (xhrobj.upload) {
  1612. xhrobj.upload.addEventListener('progress', function (event) {
  1613. var pct = 0, total = event.total, position = event.loaded || event.position;
  1614. /** @namespace event.lengthComputable */
  1615. if (event.lengthComputable) {
  1616. pct = Math.floor(position / total * 100);
  1617. }
  1618. if (previewId) {
  1619. self._setAsyncUploadStatus(previewId, pct, fileCount);
  1620. } else {
  1621. self._setProgress(pct);
  1622. }
  1623. }, false);
  1624. }
  1625. return xhrobj;
  1626. },
  1627. _ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, previewId, index) {
  1628. var self = this, settings;
  1629. self._raise('filepreajax', [previewId, index]);
  1630. self._uploadExtra(previewId, index);
  1631. settings = $.extend(true, {}, {
  1632. xhr: function () {
  1633. var xhrobj = $.ajaxSettings.xhr();
  1634. return self._initXhr(xhrobj, previewId, self.getFileStack().length);
  1635. },
  1636. url: self.uploadUrl,
  1637. type: 'POST',
  1638. dataType: 'json',
  1639. data: self.formdata,
  1640. cache: false,
  1641. processData: false,
  1642. contentType: false,
  1643. beforeSend: fnBefore,
  1644. success: fnSuccess,
  1645. complete: fnComplete,
  1646. error: fnError
  1647. }, self.ajaxSettings);
  1648. self.ajaxRequests.push($.ajax(settings));
  1649. },
  1650. _initUploadSuccess: function (out, $thumb, allFiles) {
  1651. var self = this, append, data, index, $div, $newCache, content, config, tags, i,
  1652. mergeArray = function (prop, content) {
  1653. if (!(self[prop] instanceof Array)) {
  1654. self[prop] = [];
  1655. }
  1656. if (content && content.length) {
  1657. self[prop] = self[prop].concat(content);
  1658. }
  1659. };
  1660. if (!self.showPreview || typeof out !== 'object' || $.isEmptyObject(out)) {
  1661. return;
  1662. }
  1663. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  1664. self.hasInitData = true;
  1665. content = out.initialPreview || [];
  1666. config = out.initialPreviewConfig || [];
  1667. tags = out.initialPreviewThumbTags || [];
  1668. append = out.append === undefined || out.append ? true : false;
  1669. if (content.length > 0 && !isArray(content)) {
  1670. content = content.split(self.initialPreviewDelimiter);
  1671. }
  1672. self.overwriteInitial = false;
  1673. mergeArray('initialPreview', content);
  1674. mergeArray('initialPreviewConfig', config);
  1675. mergeArray('initialPreviewThumbTags', tags);
  1676. if ($thumb !== undefined) {
  1677. if (!allFiles) {
  1678. index = previewCache.add(self.id, content, config[0], tags[0], append);
  1679. data = previewCache.get(self.id, index, false);
  1680. $div = $(document.createElement('div')).html(data).hide().insertAfter($thumb);
  1681. $newCache = $div.find('.kv-zoom-cache');
  1682. if ($newCache && $newCache.length) {
  1683. $newCache.insertAfter($thumb);
  1684. }
  1685. $thumb.fadeOut('slow', function () {
  1686. var $newThumb = $div.find('.file-preview-frame'),
  1687. $cache = self.$preview.find('#zoom-' + $thumb.attr('id')).closest('.kv-zoom-cache');
  1688. if ($newThumb && $newThumb.length) {
  1689. $newThumb.insertBefore($thumb).fadeIn('slow').css('display:inline-block');
  1690. }
  1691. self._initPreviewActions();
  1692. self._clearFileInput();
  1693. if ($cache && $cache.length) {
  1694. $cache.remove();
  1695. }
  1696. $thumb.remove();
  1697. $div.remove();
  1698. self._initSortable();
  1699. });
  1700. } else {
  1701. i = $thumb.attr('data-fileindex');
  1702. self.uploadCache.content[i] = content[0];
  1703. self.uploadCache.config[i] = config[0] || [];
  1704. self.uploadCache.tags[i] = tags[0] || [];
  1705. self.uploadCache.append = append;
  1706. }
  1707. } else {
  1708. previewCache.set(self.id, content, config, tags, append);
  1709. self._initPreview();
  1710. self._initPreviewActions();
  1711. }
  1712. }
  1713. },
  1714. _initSuccessThumbs: function () {
  1715. var self = this;
  1716. if (!self.showPreview) {
  1717. return;
  1718. }
  1719. self._getThumbs(FRAMES + ' .file-preview-success').each(function () {
  1720. var $thumb = $(this), $preview = self.$preview, $remove = $thumb.find('.kv-file-remove');
  1721. $remove.removeAttr('disabled');
  1722. handler($remove, 'click', function () {
  1723. var id = $thumb.attr('id'), out = self._raise('filesuccessremove', [id, $thumb.data('fileindex')]);
  1724. cleanMemory($thumb);
  1725. if (out === false) {
  1726. return;
  1727. }
  1728. $thumb.fadeOut('slow', function () {
  1729. var $zoom = $preview.find('#zoom-' + id);
  1730. if ($zoom.length) {
  1731. $zoom.closest('.kv-zoom-cache').remove();
  1732. }
  1733. $thumb.remove();
  1734. if (!$preview.find(FRAMES).length) {
  1735. self.reset();
  1736. }
  1737. });
  1738. });
  1739. });
  1740. },
  1741. _checkAsyncComplete: function () {
  1742. var self = this, previewId, i;
  1743. for (i = 0; i < self.filestack.length; i++) {
  1744. if (self.filestack[i]) {
  1745. previewId = self.previewInitId + "-" + i;
  1746. if ($.inArray(previewId, self.uploadLog) === -1) {
  1747. return false;
  1748. }
  1749. }
  1750. }
  1751. return (self.uploadAsyncCount === self.uploadLog.length);
  1752. },
  1753. _uploadExtra: function (previewId, index) {
  1754. var self = this, data = self._getExtraData(previewId, index);
  1755. if (data.length === 0) {
  1756. return;
  1757. }
  1758. $.each(data, function (key, value) {
  1759. self.formdata.append(key, value);
  1760. });
  1761. },
  1762. _uploadSingle: function (i, files, allFiles) {
  1763. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  1764. previewId = self.previewInitId + "-" + i, $thumb, chkComplete, $btnUpload, $btnDelete,
  1765. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1766. fnBefore, fnSuccess, fnComplete, fnError, updateUploadLog, params = {id: previewId, index: i};
  1767. self.formdata = formdata;
  1768. if (self.showPreview) {
  1769. $thumb = $('#' + previewId + ':not(.file-preview-initial)');
  1770. $btnUpload = $thumb.find('.kv-file-upload');
  1771. $btnDelete = $thumb.find('.kv-file-remove');
  1772. $('#' + previewId).find('.file-thumb-progress').removeClass('hide');
  1773. }
  1774. if (total === 0 || !hasPostData || ($btnUpload && $btnUpload.hasClass('disabled')) || self._abort(params)) {
  1775. return;
  1776. }
  1777. updateUploadLog = function (i, previewId) {
  1778. self.updateStack(i, undefined);
  1779. self.uploadLog.push(previewId);
  1780. if (self._checkAsyncComplete()) {
  1781. self.fileBatchCompleted = true;
  1782. }
  1783. };
  1784. chkComplete = function () {
  1785. var u = self.uploadCache, $initThumbs, i, j, len, data = self.cacheInitialPreview;
  1786. if (!self.fileBatchCompleted) {
  1787. return;
  1788. }
  1789. setTimeout(function () {
  1790. if (self.showPreview) {
  1791. previewCache.set(self.id, u.content, u.config, u.tags, u.append);
  1792. len = data && data.content ? data.content.length : 0;
  1793. if (len) {
  1794. for (i = 0; i < u.content.length; i++) {
  1795. j = i + len;
  1796. data.content[j] = u.content[i];
  1797. if (data.config.length) {
  1798. data.config[j] = u.config[i];
  1799. }
  1800. if (data.tags.length) {
  1801. data.tags[j] = u.tags[i];
  1802. }
  1803. }
  1804. self.initialPreview = data.content;
  1805. self.initialPreviewConfig = data.config;
  1806. self.initialPreviewThumbTags = data.tags;
  1807. } else {
  1808. self.initialPreview = u.content;
  1809. self.initialPreviewConfig = u.config;
  1810. self.initialPreviewThumbTags = u.tags;
  1811. }
  1812. self.cacheInitialPreview = {};
  1813. if (self.hasInitData) {
  1814. self._initPreview();
  1815. self._initPreviewActions();
  1816. }
  1817. }
  1818. self.unlock();
  1819. self._clearFileInput();
  1820. $initThumbs = self.$preview.find('.file-preview-initial');
  1821. if (self.uploadAsync && $initThumbs.length) {
  1822. addCss($initThumbs, SORT_CSS);
  1823. self._initSortable();
  1824. }
  1825. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  1826. self.uploadCount = 0;
  1827. self.uploadStatus = {};
  1828. self.uploadLog = [];
  1829. self._setProgress(101);
  1830. }, 100);
  1831. };
  1832. fnBefore = function (jqXHR) {
  1833. outData = self._getOutData(jqXHR);
  1834. self.fileBatchCompleted = false;
  1835. if (self.showPreview) {
  1836. if (!$thumb.hasClass('file-preview-success')) {
  1837. self._setThumbStatus($thumb, 'Loading');
  1838. addCss($thumb, 'file-uploading');
  1839. }
  1840. $btnUpload.attr('disabled', true);
  1841. $btnDelete.attr('disabled', true);
  1842. }
  1843. if (!allFiles) {
  1844. self.lock();
  1845. }
  1846. self._raise('filepreupload', [outData, previewId, i]);
  1847. $.extend(true, params, outData);
  1848. if (self._abort(params)) {
  1849. jqXHR.abort();
  1850. self._setProgressCancelled();
  1851. }
  1852. };
  1853. fnSuccess = function (data, textStatus, jqXHR) {
  1854. var pid = self.showPreview && $thumb.attr('id') ? $thumb.attr('id') : previewId;
  1855. outData = self._getOutData(jqXHR, data);
  1856. $.extend(true, params, outData);
  1857. setTimeout(function () {
  1858. if (isEmpty(data) || isEmpty(data.error)) {
  1859. if (self.showPreview) {
  1860. self._setThumbStatus($thumb, 'Success');
  1861. $btnUpload.hide();
  1862. self._initUploadSuccess(data, $thumb, allFiles);
  1863. }
  1864. self._raise('fileuploaded', [outData, pid, i]);
  1865. if (!allFiles) {
  1866. self.updateStack(i, undefined);
  1867. } else {
  1868. updateUploadLog(i, pid);
  1869. }
  1870. } else {
  1871. self._showUploadError(data.error, params);
  1872. self._setPreviewError($thumb, i);
  1873. if (allFiles) {
  1874. updateUploadLog(i, pid);
  1875. }
  1876. }
  1877. }, 100);
  1878. };
  1879. fnComplete = function () {
  1880. setTimeout(function () {
  1881. if (self.showPreview) {
  1882. $btnUpload.removeAttr('disabled');
  1883. $btnDelete.removeAttr('disabled');
  1884. $thumb.removeClass('file-uploading');
  1885. self._setProgress(101, $('#' + previewId).find('.file-thumb-progress'));
  1886. }
  1887. if (!allFiles) {
  1888. self.unlock(false);
  1889. self._clearFileInput();
  1890. } else {
  1891. chkComplete();
  1892. }
  1893. self._initSuccessThumbs();
  1894. }, 100);
  1895. };
  1896. fnError = function (jqXHR, textStatus, errorThrown) {
  1897. var errMsg = self._parseError(jqXHR, errorThrown, (allFiles ? files[i].name : null));
  1898. setTimeout(function () {
  1899. if (allFiles) {
  1900. updateUploadLog(i, previewId);
  1901. }
  1902. self.uploadStatus[previewId] = 100;
  1903. self._setPreviewError($thumb, i);
  1904. $.extend(true, params, self._getOutData(jqXHR));
  1905. self._showUploadError(errMsg, params);
  1906. }, 100);
  1907. };
  1908. formdata.append(self.uploadFileAttr, files[i], self.filenames[i]);
  1909. formdata.append('file_id', i);
  1910. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, previewId, i);
  1911. },
  1912. _uploadBatch: function () {
  1913. var self = this, files = self.filestack, total = files.length, params = {}, fnBefore, fnSuccess, fnError,
  1914. fnComplete, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  1915. setAllUploaded;
  1916. self.formdata = new FormData();
  1917. if (total === 0 || !hasPostData || self._abort(params)) {
  1918. return;
  1919. }
  1920. setAllUploaded = function () {
  1921. $.each(files, function (key) {
  1922. self.updateStack(key, undefined);
  1923. });
  1924. self._clearFileInput();
  1925. };
  1926. fnBefore = function (jqXHR) {
  1927. self.lock();
  1928. var outData = self._getOutData(jqXHR);
  1929. if (self.showPreview) {
  1930. self._getThumbs().each(function () {
  1931. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  1932. $btnDelete = $thumb.find('.kv-file-remove');
  1933. if (!$thumb.hasClass('file-preview-success')) {
  1934. self._setThumbStatus($thumb, 'Loading');
  1935. addCss($thumb, 'file-uploading');
  1936. }
  1937. $btnUpload.attr('disabled', true);
  1938. $btnDelete.attr('disabled', true);
  1939. });
  1940. }
  1941. self._raise('filebatchpreupload', [outData]);
  1942. if (self._abort(outData)) {
  1943. jqXHR.abort();
  1944. self._setProgressCancelled();
  1945. }
  1946. };
  1947. fnSuccess = function (data, textStatus, jqXHR) {
  1948. /** @namespace data.errorkeys */
  1949. var outData = self._getOutData(jqXHR, data), $thumbs = self._getThumbs(':not(.file-preview-error)'), key = 0,
  1950. keys = isEmpty(data) || isEmpty(data.errorkeys) ? [] : data.errorkeys;
  1951. if (isEmpty(data) || isEmpty(data.error)) {
  1952. self._raise('filebatchuploadsuccess', [outData]);
  1953. setAllUploaded();
  1954. if (self.showPreview) {
  1955. $thumbs.each(function () {
  1956. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload');
  1957. $thumb.find('.kv-file-upload').hide();
  1958. self._setThumbStatus($thumb, 'Success');
  1959. $thumb.removeClass('file-uploading');
  1960. $btnUpload.removeAttr('disabled');
  1961. });
  1962. self._initUploadSuccess(data);
  1963. } else {
  1964. self.reset();
  1965. }
  1966. } else {
  1967. if (self.showPreview) {
  1968. $thumbs.each(function () {
  1969. var $thumb = $(this), $btnDelete = $thumb.find('.kv-file-remove'),
  1970. $btnUpload = $thumb.find('.kv-file-upload');
  1971. $thumb.removeClass('file-uploading');
  1972. $btnUpload.removeAttr('disabled');
  1973. $btnDelete.removeAttr('disabled');
  1974. if (keys.length === 0) {
  1975. self._setPreviewError($thumb);
  1976. return;
  1977. }
  1978. if ($.inArray(key, keys) !== -1) {
  1979. self._setPreviewError($thumb);
  1980. } else {
  1981. $thumb.find('.kv-file-upload').hide();
  1982. self._setThumbStatus($thumb, 'Success');
  1983. self.updateStack(key, undefined);
  1984. }
  1985. key++;
  1986. });
  1987. self._initUploadSuccess(data);
  1988. }
  1989. self._showUploadError(data.error, outData, 'filebatchuploaderror');
  1990. }
  1991. };
  1992. fnComplete = function () {
  1993. self._setProgress(101);
  1994. self.unlock();
  1995. self._initSuccessThumbs();
  1996. self._clearFileInput();
  1997. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  1998. };
  1999. fnError = function (jqXHR, textStatus, errorThrown) {
  2000. var outData = self._getOutData(jqXHR), errMsg = self._parseError(jqXHR, errorThrown);
  2001. self._showUploadError(errMsg, outData, 'filebatchuploaderror');
  2002. self.uploadFileCount = total - 1;
  2003. if (!self.showPreview) {
  2004. return;
  2005. }
  2006. self._getThumbs().each(function () {
  2007. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  2008. $thumb.removeClass('file-uploading');
  2009. if (self.filestack[key] !== undefined) {
  2010. self._setPreviewError($thumb);
  2011. }
  2012. });
  2013. self._getThumbs().removeClass('file-uploading');
  2014. self._getThumbs(' .kv-file-upload').removeAttr('disabled');
  2015. self._getThumbs(' .kv-file-delete').removeAttr('disabled');
  2016. };
  2017. $.each(files, function (key, data) {
  2018. if (!isEmpty(files[key])) {
  2019. self.formdata.append(self.uploadFileAttr, data, self.filenames[key]);
  2020. }
  2021. });
  2022. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  2023. },
  2024. _uploadExtraOnly: function () {
  2025. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  2026. self.formdata = new FormData();
  2027. if (self._abort(params)) {
  2028. return;
  2029. }
  2030. fnBefore = function (jqXHR) {
  2031. self.lock();
  2032. var outData = self._getOutData(jqXHR);
  2033. self._raise('filebatchpreupload', [outData]);
  2034. self._setProgress(50);
  2035. params.data = outData;
  2036. params.xhr = jqXHR;
  2037. if (self._abort(params)) {
  2038. jqXHR.abort();
  2039. self._setProgressCancelled();
  2040. }
  2041. };
  2042. fnSuccess = function (data, textStatus, jqXHR) {
  2043. var outData = self._getOutData(jqXHR, data);
  2044. if (isEmpty(data) || isEmpty(data.error)) {
  2045. self._raise('filebatchuploadsuccess', [outData]);
  2046. self._clearFileInput();
  2047. self._initUploadSuccess(data);
  2048. } else {
  2049. self._showUploadError(data.error, outData, 'filebatchuploaderror');
  2050. }
  2051. };
  2052. fnComplete = function () {
  2053. self._setProgress(101);
  2054. self.unlock();
  2055. self._clearFileInput();
  2056. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  2057. };
  2058. fnError = function (jqXHR, textStatus, errorThrown) {
  2059. var outData = self._getOutData(jqXHR), errMsg = self._parseError(jqXHR, errorThrown);
  2060. params.data = outData;
  2061. self._showUploadError(errMsg, outData, 'filebatchuploaderror');
  2062. };
  2063. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  2064. },
  2065. _initFileActions: function () {
  2066. var self = this, $preview = self.$preview;
  2067. if (!self.showPreview) {
  2068. return;
  2069. }
  2070. self._initZoomButton();
  2071. $preview.find(FRAMES + ' .kv-file-remove').each(function () {
  2072. var $el = $(this), $frame = $el.closest(FRAMES), hasError, id = $frame.attr('id'),
  2073. ind = $frame.attr('data-fileindex'), n, cap, status;
  2074. handler($el, 'click', function () {
  2075. status = self._raise('filepreremove', [id, ind]);
  2076. if (status === false || !self._validateMinCount()) {
  2077. return false;
  2078. }
  2079. hasError = $frame.hasClass('file-preview-error');
  2080. cleanMemory($frame);
  2081. $frame.fadeOut('slow', function () {
  2082. var $zoom = $preview.find('#zoom-' + id);
  2083. if ($zoom.length) {
  2084. $zoom.closest('.kv-zoom-cache').remove();
  2085. }
  2086. self.updateStack(ind, undefined);
  2087. self._clearObjects($frame);
  2088. $frame.remove();
  2089. if (id && hasError) {
  2090. self.$errorContainer.find('li[data-file-id="' + id + '"]').fadeOut('fast', function () {
  2091. $(this).remove();
  2092. if (!self._errorsExist()) {
  2093. self._resetErrors();
  2094. }
  2095. });
  2096. }
  2097. self._clearFileInput();
  2098. var filestack = self.getFileStack(true), chk = previewCache.count(self.id),
  2099. len = filestack.length,
  2100. hasThumb = self.showPreview && $preview.find(FRAMES).length;
  2101. if (len === 0 && chk === 0 && !hasThumb) {
  2102. self.reset();
  2103. } else {
  2104. n = chk + len;
  2105. cap = n > 1 ? self._getMsgSelected(n) : (filestack[0] ? self._getFileNames()[0] : '');
  2106. self._setCaption(cap);
  2107. }
  2108. self._raise('fileremoved', [id, ind]);
  2109. });
  2110. });
  2111. });
  2112. self.$preview.find(FRAMES + ' .kv-file-upload').each(function () {
  2113. var $el = $(this);
  2114. handler($el, 'click', function () {
  2115. var $frame = $el.closest(FRAMES), ind = $frame.attr('data-fileindex');
  2116. if (!$frame.hasClass('file-preview-error')) {
  2117. self._uploadSingle(ind, self.filestack, false);
  2118. }
  2119. });
  2120. });
  2121. },
  2122. _hideFileIcon: function () {
  2123. if (this.overwriteInitial) {
  2124. this.$captionContainer.find('.kv-caption-icon').hide();
  2125. }
  2126. },
  2127. _showFileIcon: function () {
  2128. this.$captionContainer.find('.kv-caption-icon').show();
  2129. },
  2130. _getSize: function (bytes) {
  2131. var self = this, size = parseFloat(bytes);
  2132. if (!bytes || !size || isNaN(bytes) || isNaN(size)) {
  2133. return self._getLayoutTemplate('size').replace('{sizeText}', '0.00 KB');
  2134. }
  2135. var i, func = self.fileSizeGetter, sizes, out;
  2136. if (typeof func === 'function') {
  2137. out = func(bytes);
  2138. } else {
  2139. i = Math.floor(Math.log(size) / Math.log(1024));
  2140. sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  2141. out = (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + sizes[i];
  2142. }
  2143. return self._getLayoutTemplate('size').replace('{sizeText}', out);
  2144. },
  2145. _generatePreviewTemplate: function (cat, data, fname, ftype, previewId, isError, size, frameClass, foot, ind, templ) {
  2146. var self = this, caption = self.slug(fname),
  2147. config = ifSet(cat, self.previewSettings, defaultPreviewSettings[cat]), prevContent, zoomContent = '',
  2148. footer = foot || self._renderFileFooter(caption, size, config.width, isError),
  2149. hasIconSetting = self._getPreviewIcon(fname),
  2150. forcePrevIcon = hasIconSetting && self.preferIconicPreview,
  2151. forceZoomIcon = hasIconSetting && self.preferIconicZoomPreview,
  2152. getContent = function (c, d, zoom, frameCss) {
  2153. var id = zoom ? 'zoom-' + previewId : previewId, tmplt = self._getPreviewTemplate(c),
  2154. css = (frameClass || '') + ' ' + frameCss;
  2155. if (zoom) {
  2156. css = css.replace(' ' + SORT_CSS, '');
  2157. }
  2158. tmplt = self._parseFilePreviewIcon(tmplt, fname);
  2159. if (c === 'text') {
  2160. d = htmlEncode(d);
  2161. }
  2162. return tmplt.replace(/\{previewId}/g, id).replace(/\{caption}/g, caption)
  2163. .replace(/\{frameClass}/g, css).replace(/\{type}/g, ftype).replace(/\{fileindex}/g, ind)
  2164. .replace(/\{width}/g, config.width).replace(/\{height}/g, config.height)
  2165. .replace(/\{footer}/g, footer).replace(/\{data}/g, d).replace(/\{template}/g, templ || cat);
  2166. };
  2167. ind = ind || previewId.slice(previewId.lastIndexOf('-') + 1);
  2168. if (self.fileActionSettings.showZoom) {
  2169. zoomContent = getContent((forceZoomIcon ? 'other' : cat), data, true, 'kv-zoom-thumb');
  2170. }
  2171. zoomContent = '\n<div class="kv-zoom-cache" style="display:none">\n' + zoomContent + '\n</div>\n';
  2172. prevContent = getContent((forcePrevIcon ? 'other' : cat), data, false, 'kv-preview-thumb');
  2173. return prevContent + zoomContent;
  2174. },
  2175. _previewDefault: function (file, previewId, isDisabled) {
  2176. var self = this, $preview = self.$preview;
  2177. if (!self.showPreview) {
  2178. return;
  2179. }
  2180. var fname = file ? file.name : '', ftype = file ? file.type : '', content,
  2181. isError = isDisabled === true && !self.isUploadable, data = objUrl.createObjectURL(file);
  2182. self._clearDefaultPreview();
  2183. content = self._generatePreviewTemplate('other', data, fname, ftype, previewId, isError, file.size);
  2184. $preview.append("\n" + content);
  2185. if (isDisabled === true && self.isUploadable) {
  2186. self._setThumbStatus($('#' + previewId), 'Error');
  2187. }
  2188. },
  2189. _previewFile: function (i, file, theFile, previewId, data) {
  2190. if (!this.showPreview) {
  2191. return;
  2192. }
  2193. var self = this, cat = self._parseFileType(file), fname = file ? file.name : '', caption = self.slug(fname),
  2194. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes, $preview = self.$preview,
  2195. chkTypes = types && types.indexOf(cat) >= 0,
  2196. iData = (cat === 'text' || cat === 'html' || cat === 'image') ? theFile.target.result : data, content,
  2197. chkMimes = mimes && mimes.indexOf(file.type) !== -1;
  2198. /** @namespace window.DOMPurify */
  2199. if (cat === 'html' && self.purifyHtml && window.DOMPurify) {
  2200. iData = window.DOMPurify.sanitize(iData);
  2201. }
  2202. if (chkTypes || chkMimes) {
  2203. content = self._generatePreviewTemplate(cat, iData, fname, file.type, previewId, false, file.size);
  2204. self._clearDefaultPreview();
  2205. $preview.append("\n" + content);
  2206. self._validateImage(previewId, caption, file.type);
  2207. } else {
  2208. self._previewDefault(file, previewId);
  2209. }
  2210. self._initSortable();
  2211. },
  2212. _slugDefault: function (text) {
  2213. return isEmpty(text) ? '' : String(text).replace(/[\-\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_');
  2214. },
  2215. _readFiles: function (files) {
  2216. this.reader = new FileReader();
  2217. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  2218. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  2219. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  2220. settings = self.fileTypeSettings, ctr = self.filestack.length, readFile,
  2221. maxPreviewSize = self.maxFilePreviewSize && parseFloat(self.maxFilePreviewSize),
  2222. canPreview = $preview.length && (!maxPreviewSize || isNaN(maxPreviewSize)),
  2223. throwError = function (msg, file, previewId, index) {
  2224. var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}),
  2225. p2 = {id: previewId, index: index, file: file, files: files};
  2226. self._previewDefault(file, previewId, true);
  2227. if (self.isUploadable) {
  2228. self.addToStack(undefined);
  2229. setTimeout(function () {
  2230. readFile(index + 1);
  2231. }, 100);
  2232. }
  2233. self._initFileActions();
  2234. if (self.removeFromPreviewOnError) {
  2235. $('#' + previewId).remove();
  2236. }
  2237. return self.isUploadable ? self._showUploadError(msg, p1) : self._showError(msg, p2);
  2238. };
  2239. self.loadedImages = [];
  2240. self.totalImagesCount = 0;
  2241. $.each(files, function (key, file) {
  2242. var func = self.fileTypeSettings.image || defaultFileTypeSettings.image;
  2243. if (func && func(file.type)) {
  2244. self.totalImagesCount++;
  2245. }
  2246. });
  2247. readFile = function (i) {
  2248. if (isEmpty($el.attr('multiple'))) {
  2249. numFiles = 1;
  2250. }
  2251. if (i >= numFiles) {
  2252. if (self.isUploadable && self.filestack.length > 0) {
  2253. self._raise('filebatchselected', [self.getFileStack()]);
  2254. } else {
  2255. self._raise('filebatchselected', [files]);
  2256. }
  2257. $container.removeClass('file-thumb-loading');
  2258. $status.html('');
  2259. return;
  2260. }
  2261. var node = ctr + i, previewId = previewInitId + "-" + node, isText, isImage, file = files[i], fSizeKB,
  2262. caption = file.name ? self.slug(file.name) : '', fileSize = (file.size || 0) / 1000, checkFile,
  2263. fileExtExpr = '', previewData = objUrl.createObjectURL(file), fileCount = 0, j, msg, typ, chk,
  2264. fileTypes = self.allowedFileTypes, typ1, typ2, strTypes = '', typLen = fileTypes ? fileTypes.length : 0,
  2265. fileExt = self.allowedFileExtensions, strExt = isEmpty(fileExt) ? '' : fileExt.join(', ');
  2266. if (typLen > 0) {
  2267. for (j = 0; j < typLen; j++) {
  2268. typ1 = fileTypes[j];
  2269. typ2 = self.msgFileTypes[typ1] || typ1;
  2270. strTypes += j === 0 ? typ2 : ', ' + typ2;
  2271. }
  2272. }
  2273. if (caption === false) {
  2274. readFile(i + 1);
  2275. return;
  2276. }
  2277. if (caption.length === 0) {
  2278. msg = self.msgInvalidFileName.replace('{name}', htmlEncode(file.name));
  2279. self.isError = throwError(msg, file, previewId, i);
  2280. return;
  2281. }
  2282. if (!isEmpty(fileExt)) {
  2283. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  2284. }
  2285. fSizeKB = fileSize.toFixed(2);
  2286. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  2287. msg = self.msgSizeTooLarge.replace('{name}', caption).replace('{size}', fSizeKB)
  2288. .replace('{maxSize}', self.maxFileSize);
  2289. self.isError = throwError(msg, file, previewId, i);
  2290. return;
  2291. }
  2292. if (self.minFileSize !== null && fileSize <= getNum(self.minFileSize)) {
  2293. msg = self.msgSizeTooSmall.replace('{name}', caption).replace('{size}', fSizeKB)
  2294. .replace('{minSize}', self.minFileSize);
  2295. self.isError = throwError(msg, file, previewId, i);
  2296. return;
  2297. }
  2298. if (!isEmpty(fileTypes) && isArray(fileTypes)) {
  2299. for (j = 0; j < fileTypes.length; j += 1) {
  2300. typ = fileTypes[j];
  2301. checkFile = settings[typ];
  2302. chk = (checkFile !== undefined && checkFile(file.type, caption));
  2303. fileCount += isEmpty(chk) ? 0 : chk.length;
  2304. }
  2305. if (fileCount === 0) {
  2306. msg = self.msgInvalidFileType.replace('{name}', caption).replace('{types}', strTypes);
  2307. self.isError = throwError(msg, file, previewId, i);
  2308. return;
  2309. }
  2310. }
  2311. if (fileCount === 0 && !isEmpty(fileExt) && isArray(fileExt) && !isEmpty(fileExtExpr)) {
  2312. chk = compare(caption, fileExtExpr);
  2313. fileCount += isEmpty(chk) ? 0 : chk.length;
  2314. if (fileCount === 0) {
  2315. msg = self.msgInvalidFileExtension.replace('{name}', caption).replace('{extensions}', strExt);
  2316. self.isError = throwError(msg, file, previewId, i);
  2317. return;
  2318. }
  2319. }
  2320. if (!self.showPreview) {
  2321. self.addToStack(file);
  2322. setTimeout(function () {
  2323. readFile(i + 1);
  2324. }, 100);
  2325. self._raise('fileloaded', [file, previewId, i, reader]);
  2326. return;
  2327. }
  2328. if (!canPreview && fileSize > maxPreviewSize) {
  2329. self.addToStack(file);
  2330. $container.addClass('file-thumb-loading');
  2331. self._previewDefault(file, previewId);
  2332. self._initFileActions();
  2333. self._updateFileDetails(numFiles);
  2334. readFile(i + 1);
  2335. return;
  2336. }
  2337. if ($preview.length && FileReader !== undefined) {
  2338. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  2339. $container.addClass('file-thumb-loading');
  2340. reader.onerror = function (evt) {
  2341. self._errorHandler(evt, caption);
  2342. };
  2343. reader.onload = function (theFile) {
  2344. self._previewFile(i, file, theFile, previewId, previewData);
  2345. self._initFileActions();
  2346. };
  2347. reader.onloadend = function () {
  2348. msg = msgProgress.replace('{index}', i + 1).replace('{files}', numFiles)
  2349. .replace('{percent}', 50).replace('{name}', caption);
  2350. setTimeout(function () {
  2351. $status.html(msg);
  2352. self._updateFileDetails(numFiles);
  2353. readFile(i + 1);
  2354. }, 100);
  2355. self._raise('fileloaded', [file, previewId, i, reader]);
  2356. };
  2357. reader.onprogress = function (data) {
  2358. if (data.lengthComputable) {
  2359. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  2360. msg = msgProgress.replace('{index}', i + 1).replace('{files}', numFiles)
  2361. .replace('{percent}', progress).replace('{name}', caption);
  2362. setTimeout(function () {
  2363. $status.html(msg);
  2364. }, 100);
  2365. }
  2366. };
  2367. isText = ifSet('text', settings, defaultFileTypeSettings.text);
  2368. isImage = ifSet('image', settings, defaultFileTypeSettings.image);
  2369. if (isText(file.type, caption)) {
  2370. reader.readAsText(file, self.textEncoding);
  2371. } else {
  2372. if (isImage(file.type, caption)) {
  2373. reader.readAsDataURL(file);
  2374. } else {
  2375. reader.readAsArrayBuffer(file);
  2376. }
  2377. }
  2378. } else {
  2379. self._previewDefault(file, previewId);
  2380. setTimeout(function () {
  2381. readFile(i + 1);
  2382. self._updateFileDetails(numFiles);
  2383. }, 100);
  2384. self._raise('fileloaded', [file, previewId, i, reader]);
  2385. }
  2386. self.addToStack(file);
  2387. };
  2388. readFile(0);
  2389. self._updateFileDetails(numFiles, false);
  2390. },
  2391. _updateFileDetails: function (numFiles) {
  2392. var self = this, $el = self.$element, fileStack = self.getFileStack(),
  2393. name = (isIE(9) && findFileName($el.val())) ||
  2394. ($el[0].files[0] && $el[0].files[0].name) || (fileStack.length && fileStack[0].name) || '',
  2395. label = self.slug(name), n = self.isUploadable ? fileStack.length : numFiles,
  2396. nFiles = previewCache.count(self.id) + n, log = n > 1 ? self._getMsgSelected(nFiles) : label;
  2397. if (self.isError) {
  2398. self.$previewContainer.removeClass('file-thumb-loading');
  2399. self.$previewStatus.html('');
  2400. self.$captionContainer.find('.kv-caption-icon').hide();
  2401. } else {
  2402. self._showFileIcon();
  2403. }
  2404. self._setCaption(log, self.isError);
  2405. self.$container.removeClass('file-input-new file-input-ajax-new');
  2406. if (arguments.length === 1) {
  2407. self._raise('fileselect', [numFiles, label]);
  2408. }
  2409. if (previewCache.count(self.id)) {
  2410. self._initPreviewActions();
  2411. }
  2412. },
  2413. _setThumbStatus: function ($thumb, status) {
  2414. var self = this;
  2415. if (!self.showPreview) {
  2416. return;
  2417. }
  2418. var icon = 'indicator' + status, msg = icon + 'Title',
  2419. css = 'file-preview-' + status.toLowerCase(),
  2420. $indicator = $thumb.find('.file-upload-indicator'),
  2421. config = self.fileActionSettings;
  2422. $thumb.removeClass('file-preview-success file-preview-error file-preview-loading');
  2423. if (status === 'Error') {
  2424. $thumb.find('.kv-file-upload').attr('disabled', true);
  2425. }
  2426. if (status === 'Success') {
  2427. $thumb.find('.file-drag-handle').remove();
  2428. $indicator.css('margin-left', 0);
  2429. }
  2430. $indicator.html(config[icon]);
  2431. $indicator.attr('title', config[msg]);
  2432. $thumb.addClass(css);
  2433. },
  2434. _setProgressCancelled: function () {
  2435. var self = this;
  2436. self._setProgress(101, self.$progress, self.msgCancelled);
  2437. },
  2438. _setProgress: function (p, $el, error) {
  2439. var self = this, pct = Math.min(p, 100), template = pct < 100 ? self.progressTemplate :
  2440. (error ? self.progressErrorTemplate : (p <= 100 ? self.progressTemplate : self.progressCompleteTemplate)),
  2441. pctLimit = self.progressUploadThreshold;
  2442. $el = $el || self.$progress;
  2443. if (!isEmpty(template)) {
  2444. if (pctLimit && pct > pctLimit && p <= 100) {
  2445. var out = template.replace('{percent}', pctLimit).replace('{percent}', pctLimit).replace('{percent}%', self.msgUploadThreshold);
  2446. $el.html(out);
  2447. } else {
  2448. $el.html(template.replace(/\{percent}/g, pct));
  2449. }
  2450. if (error) {
  2451. $el.find('[role="progressbar"]').html(error);
  2452. }
  2453. }
  2454. },
  2455. _setFileDropZoneTitle: function () {
  2456. var self = this, $zone = self.$container.find('.file-drop-zone'), title = self.dropZoneTitle, strFiles;
  2457. if (self.isClickable) {
  2458. strFiles = isEmpty(self.$element.attr('multiple')) ? self.fileSingle : self.filePlural;
  2459. title += self.dropZoneClickTitle.replace('{files}', strFiles);
  2460. }
  2461. $zone.find('.' + self.dropZoneTitleClass).remove();
  2462. if (!self.isUploadable || !self.showPreview || $zone.length === 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled) {
  2463. return;
  2464. }
  2465. if ($zone.find(FRAMES).length === 0 && isEmpty(self.defaultPreviewContent)) {
  2466. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + title + '</div>');
  2467. }
  2468. self.$container.removeClass('file-input-new');
  2469. addCss(self.$container, 'file-input-ajax-new');
  2470. },
  2471. _setAsyncUploadStatus: function (previewId, pct, total) {
  2472. var self = this, sum = 0;
  2473. self._setProgress(pct, $('#' + previewId).find('.file-thumb-progress'));
  2474. self.uploadStatus[previewId] = pct;
  2475. $.each(self.uploadStatus, function (key, value) {
  2476. sum += value;
  2477. });
  2478. self._setProgress(Math.floor(sum / total));
  2479. },
  2480. _validateMinCount: function () {
  2481. var self = this, len = self.isUploadable ? self.getFileStack().length : self.$element.get(0).files.length;
  2482. if (self.validateInitialCount && self.minFileCount > 0 && self._getFileCount(len - 1) < self.minFileCount) {
  2483. self._noFilesError({});
  2484. return false;
  2485. }
  2486. return true;
  2487. },
  2488. _getFileCount: function (fileCount) {
  2489. var self = this, addCount = 0;
  2490. if (self.validateInitialCount && !self.overwriteInitial) {
  2491. addCount = previewCache.count(self.id);
  2492. fileCount += addCount;
  2493. }
  2494. return fileCount;
  2495. },
  2496. _getFileName: function (file) {
  2497. return file && file.name ? this.slug(file.name) : undefined;
  2498. },
  2499. _getFileNames: function (skipNull) {
  2500. var self = this;
  2501. return self.filenames.filter(function (n) {
  2502. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  2503. });
  2504. },
  2505. _setPreviewError: function ($thumb, i, val) {
  2506. var self = this;
  2507. if (i !== undefined) {
  2508. self.updateStack(i, val);
  2509. }
  2510. if (self.removeFromPreviewOnError) {
  2511. $thumb.remove();
  2512. } else {
  2513. self._setThumbStatus($thumb, 'Error');
  2514. }
  2515. },
  2516. _checkDimensions: function (i, chk, $img, $thumb, fname, type, params) {
  2517. var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max', limit = self[tag + 'Image' + type],
  2518. $imgEl, isValid;
  2519. if (isEmpty(limit) || !$img.length) {
  2520. return;
  2521. }
  2522. $imgEl = $img[0];
  2523. dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height;
  2524. isValid = chk === 'Small' ? dim >= limit : dim <= limit;
  2525. if (isValid) {
  2526. return;
  2527. }
  2528. msg = self['msgImage' + type + chk].replace('{name}', fname).replace('{size}', limit);
  2529. self._showUploadError(msg, params);
  2530. self._setPreviewError($thumb, i, null);
  2531. },
  2532. _validateImage: function (previewId, fname, ftype) {
  2533. var self = this, $preview = self.$preview, params, w1, w2, $thumb = $preview.find("#" + previewId),
  2534. i = $thumb.attr('data-fileindex'), $img = $thumb.find('img');
  2535. fname = fname || 'Untitled';
  2536. if (!$img.length) {
  2537. return;
  2538. }
  2539. handler($img, 'load', function () {
  2540. w1 = $thumb.width();
  2541. w2 = $preview.width();
  2542. if (w1 > w2) {
  2543. $img.css('width', '100%');
  2544. $thumb.css('width', '97%');
  2545. }
  2546. params = {ind: i, id: previewId};
  2547. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
  2548. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
  2549. if (!self.resizeImage) {
  2550. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
  2551. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
  2552. }
  2553. self._raise('fileimageloaded', [previewId]);
  2554. self.loadedImages.push({ind: i, img: $img, thumb: $thumb, pid: previewId, typ: ftype});
  2555. self._validateAllImages();
  2556. });
  2557. },
  2558. _validateAllImages: function () {
  2559. var self = this, i, config, $img, pid, ind, errFunc, ctr = {val: 0};
  2560. if (self.loadedImages.length !== self.totalImagesCount) {
  2561. return;
  2562. }
  2563. self._raise('fileimagesloaded');
  2564. if (!self.resizeImage) {
  2565. return;
  2566. }
  2567. errFunc = self.isUploadable ? self._showUploadError : self._showError;
  2568. for (i = 0; i < self.loadedImages.length; i++) {
  2569. config = self.loadedImages[i];
  2570. $img = config.img;
  2571. pid = config.pid;
  2572. ind = config.ind;
  2573. if (!self._getResizedImage($img[0], config.typ, pid, ind, ctr, self.loadedImages.length)) {
  2574. errFunc(self.msgImageResizeError, {id: pid, 'index': ind}, 'fileimageresizeerror');
  2575. self._setPreviewError(config.thumb, ind);
  2576. }
  2577. }
  2578. },
  2579. _getResizedImage: function (image, type, pid, ind, counter, numImgs) {
  2580. var self = this, width = image.naturalWidth, height = image.naturalHeight, ratio = 1,
  2581. maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height,
  2582. isValidImage = !!(width && height), chkWidth, chkHeight, canvas = self.imageCanvas,
  2583. context = self.imageCanvasContext;
  2584. if (!self.filestack[ind] || !isValidImage || (width <= maxWidth && height <= maxHeight)) {
  2585. if (isValidImage && self.filestack[ind]) {
  2586. self._raise('fileimageresized', [pid, ind]);
  2587. }
  2588. counter.val++;
  2589. if (counter.val === numImgs) {
  2590. self._raise('fileimagesresized');
  2591. }
  2592. return isValidImage;
  2593. }
  2594. type = type || self.resizeDefaultImageType;
  2595. chkWidth = width > maxWidth;
  2596. chkHeight = height > maxHeight;
  2597. if (self.resizePreference === 'width') {
  2598. ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1);
  2599. } else {
  2600. ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1);
  2601. }
  2602. self._resetCanvas();
  2603. width *= ratio;
  2604. height *= ratio;
  2605. canvas.width = width;
  2606. canvas.height = height;
  2607. try {
  2608. context.drawImage(image, 0, 0, width, height);
  2609. canvas.toBlob(function (blob) {
  2610. self.filestack[ind] = blob;
  2611. self._raise('fileimageresized', [pid, ind]);
  2612. counter.val++;
  2613. if (counter.val === numImgs) {
  2614. self._raise('fileimagesresized', [undefined, undefined]);
  2615. }
  2616. }, type, self.resizeQuality);
  2617. return true;
  2618. }
  2619. catch (err) {
  2620. counter.val++;
  2621. if (counter.val === numImgs) {
  2622. self._raise('fileimagesresized', [undefined, undefined]);
  2623. }
  2624. return false;
  2625. }
  2626. },
  2627. _initBrowse: function ($container) {
  2628. var self = this;
  2629. if (self.showBrowse) {
  2630. self.$btnFile = $container.find('.btn-file');
  2631. self.$btnFile.append(self.$element);
  2632. } else {
  2633. self.$element.hide();
  2634. }
  2635. },
  2636. _initCaption: function () {
  2637. var self = this, cap = self.initialCaption || '';
  2638. if (self.overwriteInitial || isEmpty(cap)) {
  2639. self.$caption.html('');
  2640. return false;
  2641. }
  2642. self._setCaption(cap);
  2643. return true;
  2644. },
  2645. _setCaption: function (content, isError) {
  2646. var self = this, title, out, n, cap, stack = self.getFileStack();
  2647. if (!self.$caption.length) {
  2648. return;
  2649. }
  2650. if (isError) {
  2651. title = $('<div>' + self.msgValidationError + '</div>').text();
  2652. n = stack.length;
  2653. if (n) {
  2654. cap = n === 1 && stack[0] ? self._getFileNames()[0] : self._getMsgSelected(n);
  2655. } else {
  2656. cap = self._getMsgSelected(self.msgNo);
  2657. }
  2658. out = '<span class="' + self.msgValidationErrorClass + '">' + self.msgValidationErrorIcon +
  2659. (isEmpty(content) ? cap : content) + '</span>';
  2660. } else {
  2661. if (isEmpty(content)) {
  2662. return;
  2663. }
  2664. title = $('<div>' + content + '</div>').text();
  2665. out = self._getLayoutTemplate('fileIcon') + title;
  2666. }
  2667. self.$caption.html(out);
  2668. self.$caption.attr('title', title);
  2669. self.$captionContainer.find('.file-caption-ellipsis').attr('title', title);
  2670. },
  2671. _createContainer: function () {
  2672. var self = this, $container = $(document.createElement("div"))
  2673. .attr({"class": 'file-input file-input-new'})
  2674. .html(self._renderMain());
  2675. self.$element.before($container);
  2676. self._initBrowse($container);
  2677. if (self.theme) {
  2678. $container.addClass('theme-' + self.theme);
  2679. }
  2680. return $container;
  2681. },
  2682. _refreshContainer: function () {
  2683. var self = this, $container = self.$container;
  2684. $container.before(self.$element);
  2685. $container.html(self._renderMain());
  2686. self._initBrowse($container);
  2687. },
  2688. _renderMain: function () {
  2689. var self = this, dropCss = (self.isUploadable && self.dropZoneEnabled) ? ' file-drop-zone' : 'file-drop-disabled',
  2690. close = !self.showClose ? '' : self._getLayoutTemplate('close'),
  2691. preview = !self.showPreview ? '' : self._getLayoutTemplate('preview')
  2692. .replace(/\{class}/g, self.previewClass)
  2693. .replace(/\{dropClass}/g, dropCss),
  2694. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  2695. caption = self.captionTemplate.replace(/\{class}/g, css + ' kv-fileinput-caption');
  2696. return self.mainTemplate.replace(/\{class}/g, self.mainClass +
  2697. (!self.showBrowse && self.showCaption ? ' no-browse' : ''))
  2698. .replace(/\{preview}/g, preview)
  2699. .replace(/\{close}/g, close)
  2700. .replace(/\{caption}/g, caption)
  2701. .replace(/\{upload}/g, self._renderButton('upload'))
  2702. .replace(/\{remove}/g, self._renderButton('remove'))
  2703. .replace(/\{cancel}/g, self._renderButton('cancel'))
  2704. .replace(/\{browse}/g, self._renderButton('browse'));
  2705. },
  2706. _renderButton: function (type) {
  2707. var self = this, tmplt = self._getLayoutTemplate('btnDefault'), css = self[type + 'Class'],
  2708. title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'],
  2709. status = self.isDisabled ? ' disabled' : '', btnType = 'button';
  2710. switch (type) {
  2711. case 'remove':
  2712. if (!self.showRemove) {
  2713. return '';
  2714. }
  2715. break;
  2716. case 'cancel':
  2717. if (!self.showCancel) {
  2718. return '';
  2719. }
  2720. css += ' hide';
  2721. break;
  2722. case 'upload':
  2723. if (!self.showUpload) {
  2724. return '';
  2725. }
  2726. if (self.isUploadable && !self.isDisabled) {
  2727. tmplt = self._getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl);
  2728. } else {
  2729. btnType = 'submit';
  2730. }
  2731. break;
  2732. case 'browse':
  2733. if (!self.showBrowse) {
  2734. return '';
  2735. }
  2736. tmplt = self._getLayoutTemplate('btnBrowse');
  2737. break;
  2738. default:
  2739. return '';
  2740. }
  2741. css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button';
  2742. if (!isEmpty(label)) {
  2743. label = ' <span class="' + self.buttonLabelClass + '">' + label + '</span>';
  2744. }
  2745. return tmplt.replace('{type}', btnType).replace('{css}', css).replace('{title}', title)
  2746. .replace('{status}', status).replace('{icon}', icon).replace('{label}', label);
  2747. },
  2748. _renderThumbProgress: function () {
  2749. return '<div class="file-thumb-progress hide">' + this.progressTemplate.replace(/\{percent}/g,
  2750. '0') + '</div>';
  2751. },
  2752. _renderFileFooter: function (caption, size, width, isError) {
  2753. var self = this, config = self.fileActionSettings, rem = config.showRemove, drg = config.showDrag,
  2754. upl = config.showUpload, zoom = config.showZoom, out, template = self._getLayoutTemplate('footer'),
  2755. indicator = isError ? config.indicatorError : config.indicatorNew,
  2756. title = isError ? config.indicatorErrorTitle : config.indicatorNewTitle;
  2757. size = self._getSize(size);
  2758. if (self.isUploadable) {
  2759. out = template.replace(/\{actions}/g, self._renderFileActions(upl, rem, zoom, drg, false, false, false))
  2760. .replace(/\{caption}/g, caption).replace(/\{size}/g, size).replace(/\{width}/g, width)
  2761. .replace(/\{progress}/g, self._renderThumbProgress()).replace(/\{indicator}/g, indicator)
  2762. .replace(/\{indicatorTitle}/g, title);
  2763. } else {
  2764. out = template.replace(/\{actions}/g,
  2765. self._renderFileActions(false, false, zoom, drg, false, false, false))
  2766. .replace(/\{caption}/g, caption).replace(/\{size}/g, size).replace(/\{width}/g, width)
  2767. .replace(/\{progress}/g, '').replace(/\{indicator}/g, indicator)
  2768. .replace(/\{indicatorTitle}/g, title);
  2769. }
  2770. out = replaceTags(out, self.previewThumbTags);
  2771. return out;
  2772. },
  2773. _renderFileActions: function (showUpload, showDelete, showZoom, showDrag, disabled, url, key, isInit) {
  2774. if (!showUpload && !showDelete && !showZoom && !showDrag) {
  2775. return '';
  2776. }
  2777. var self = this,
  2778. vUrl = url === false ? '' : ' data-url="' + url + '"',
  2779. vKey = key === false ? '' : ' data-key="' + key + '"',
  2780. btnDelete = '', btnUpload = '', btnZoom = '', btnDrag = '', css,
  2781. template = self._getLayoutTemplate('actions'), config = self.fileActionSettings,
  2782. otherButtons = self.otherActionButtons.replace(/\{dataKey}/g, vKey),
  2783. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  2784. if (showDelete) {
  2785. btnDelete = self._getLayoutTemplate('actionDelete')
  2786. .replace(/\{removeClass}/g, removeClass)
  2787. .replace(/\{removeIcon}/g, config.removeIcon)
  2788. .replace(/\{removeTitle}/g, config.removeTitle)
  2789. .replace(/\{dataUrl}/g, vUrl)
  2790. .replace(/\{dataKey}/g, vKey);
  2791. }
  2792. if (showUpload) {
  2793. btnUpload = self._getLayoutTemplate('actionUpload')
  2794. .replace(/\{uploadClass}/g, config.uploadClass)
  2795. .replace(/\{uploadIcon}/g, config.uploadIcon)
  2796. .replace(/\{uploadTitle}/g, config.uploadTitle);
  2797. }
  2798. if (showZoom) {
  2799. btnZoom = self._getLayoutTemplate('actionZoom')
  2800. .replace(/\{zoomClass}/g, config.zoomClass)
  2801. .replace(/\{zoomIcon}/g, config.zoomIcon)
  2802. .replace(/\{zoomTitle}/g, config.zoomTitle);
  2803. }
  2804. if (showDrag && isInit) {
  2805. css = 'drag-handle-init ' + config.dragClass;
  2806. btnDrag = self._getLayoutTemplate('actionDrag').replace(/\{dragClass}/g, css)
  2807. .replace(/\{dragTitle}/g, config.dragTitle)
  2808. .replace(/\{dragIcon}/g, config.dragIcon);
  2809. }
  2810. return template.replace(/\{delete}/g, btnDelete)
  2811. .replace(/\{upload}/g, btnUpload)
  2812. .replace(/\{zoom}/g, btnZoom)
  2813. .replace(/\{drag}/g, btnDrag)
  2814. .replace(/\{other}/g, otherButtons);
  2815. },
  2816. _browse: function (e) {
  2817. var self = this;
  2818. self._raise('filebrowse');
  2819. if (e && e.isDefaultPrevented()) {
  2820. return;
  2821. }
  2822. if (self.isError && !self.isUploadable) {
  2823. self.clear();
  2824. }
  2825. self.$captionContainer.focus();
  2826. },
  2827. _change: function (e) {
  2828. var self = this, $el = self.$element;
  2829. if (!self.isUploadable && isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix
  2830. self.fileInputCleared = false;
  2831. return;
  2832. }
  2833. self.fileInputCleared = false;
  2834. var tfiles, msg, total, isDragDrop = arguments.length > 1, isAjaxUpload = self.isUploadable, i = 0, f, n, len,
  2835. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files, ctr = self.filestack.length,
  2836. isSingleUpload = isEmpty($el.attr('multiple')), flagSingle = (isSingleUpload && ctr > 0), folders = 0,
  2837. throwError = function (mesg, file, previewId, index) {
  2838. var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}),
  2839. p2 = {id: previewId, index: index, file: file, files: files};
  2840. return self.isUploadable ? self._showUploadError(mesg, p1) : self._showError(mesg, p2);
  2841. };
  2842. self.reader = null;
  2843. self._resetUpload();
  2844. self._hideFileIcon();
  2845. if (self.isUploadable) {
  2846. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  2847. }
  2848. if (isDragDrop) {
  2849. tfiles = [];
  2850. while (files[i]) {
  2851. f = files[i];
  2852. if (!f.type && f.size % 4096 === 0) {
  2853. folders++;
  2854. } else {
  2855. tfiles.push(f);
  2856. }
  2857. i++;
  2858. }
  2859. } else {
  2860. if (e.target.files === undefined) {
  2861. tfiles = e.target && e.target.value ? [
  2862. {name: e.target.value.replace(/^.+\\/, '')}
  2863. ] : [];
  2864. } else {
  2865. tfiles = e.target.files;
  2866. }
  2867. }
  2868. if (isEmpty(tfiles) || tfiles.length === 0) {
  2869. if (!isAjaxUpload) {
  2870. self.clear();
  2871. }
  2872. self._showFolderError(folders);
  2873. self._raise('fileselectnone');
  2874. return;
  2875. }
  2876. self._resetErrors();
  2877. len = tfiles.length;
  2878. total = self._getFileCount(self.isUploadable ? (self.getFileStack().length + len) : len);
  2879. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  2880. if (!self.autoReplace || len > self.maxFileCount) {
  2881. n = (self.autoReplace && len > self.maxFileCount) ? len : total;
  2882. msg = self.msgFilesTooMany.replace('{m}', self.maxFileCount).replace('{n}', n);
  2883. self.isError = throwError(msg, null, null, null);
  2884. self.$captionContainer.find('.kv-caption-icon').hide();
  2885. self._setCaption('', true);
  2886. self.$container.removeClass('file-input-new file-input-ajax-new');
  2887. return;
  2888. }
  2889. if (total > self.maxFileCount) {
  2890. self._resetPreviewThumbs(isAjaxUpload);
  2891. }
  2892. } else {
  2893. if (!isAjaxUpload || flagSingle) {
  2894. self._resetPreviewThumbs(false);
  2895. if (flagSingle) {
  2896. self.clearStack();
  2897. }
  2898. } else {
  2899. if (isAjaxUpload && ctr === 0 && (!previewCache.count(self.id) || self.overwriteInitial)) {
  2900. self._resetPreviewThumbs(true);
  2901. }
  2902. }
  2903. }
  2904. if (self.isPreviewable) {
  2905. self._readFiles(tfiles);
  2906. } else {
  2907. self._updateFileDetails(1);
  2908. }
  2909. self._showFolderError(folders);
  2910. },
  2911. _abort: function (params) {
  2912. var self = this, data;
  2913. if (self.ajaxAborted && typeof self.ajaxAborted === "object" && self.ajaxAborted.message !== undefined) {
  2914. data = $.extend(true, {}, self._getOutData(), params);
  2915. data.abortData = self.ajaxAborted.data || {};
  2916. data.abortMessage = self.ajaxAborted.message;
  2917. self.cancel();
  2918. self._setProgress(101, self.$progress, self.msgCancelled);
  2919. self._showUploadError(self.ajaxAborted.message, data, 'filecustomerror');
  2920. return true;
  2921. }
  2922. return false;
  2923. },
  2924. _resetFileStack: function () {
  2925. var self = this, i = 0, newstack = [], newnames = [];
  2926. self._getThumbs().each(function () {
  2927. var $thumb = $(this), ind = $thumb.attr('data-fileindex'),
  2928. file = self.filestack[ind];
  2929. if (ind === -1) {
  2930. return;
  2931. }
  2932. if (file !== undefined) {
  2933. newstack[i] = file;
  2934. newnames[i] = self._getFileName(file);
  2935. $thumb.attr({
  2936. 'id': self.previewInitId + '-' + i,
  2937. 'data-fileindex': i
  2938. });
  2939. i++;
  2940. } else {
  2941. $thumb.attr({
  2942. 'id': 'uploaded-' + uniqId(),
  2943. 'data-fileindex': '-1'
  2944. });
  2945. }
  2946. });
  2947. self.filestack = newstack;
  2948. self.filenames = newnames;
  2949. },
  2950. clearStack: function () {
  2951. var self = this;
  2952. self.filestack = [];
  2953. self.filenames = [];
  2954. return self.$element;
  2955. },
  2956. updateStack: function (i, file) {
  2957. var self = this;
  2958. self.filestack[i] = file;
  2959. self.filenames[i] = self._getFileName(file);
  2960. return self.$element;
  2961. },
  2962. addToStack: function (file) {
  2963. var self = this;
  2964. self.filestack.push(file);
  2965. self.filenames.push(self._getFileName(file));
  2966. return self.$element;
  2967. },
  2968. getFileStack: function (skipNull) {
  2969. var self = this;
  2970. return self.filestack.filter(function (n) {
  2971. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  2972. });
  2973. },
  2974. getFilesCount: function () {
  2975. var self = this, len = self.isUploadable ? self.getFileStack().length : self.$element.get(0).files.length;
  2976. return self._getFileCount(len);
  2977. },
  2978. lock: function () {
  2979. var self = this;
  2980. self._resetErrors();
  2981. self.disable();
  2982. if (self.showRemove) {
  2983. addCss(self.$container.find('.fileinput-remove'), 'hide');
  2984. }
  2985. if (self.showCancel) {
  2986. self.$container.find('.fileinput-cancel').removeClass('hide');
  2987. }
  2988. self._raise('filelock', [self.filestack, self._getExtraData()]);
  2989. return self.$element;
  2990. },
  2991. unlock: function (reset) {
  2992. var self = this;
  2993. if (reset === undefined) {
  2994. reset = true;
  2995. }
  2996. self.enable();
  2997. if (self.showCancel) {
  2998. addCss(self.$container.find('.fileinput-cancel'), 'hide');
  2999. }
  3000. if (self.showRemove) {
  3001. self.$container.find('.fileinput-remove').removeClass('hide');
  3002. }
  3003. if (reset) {
  3004. self._resetFileStack();
  3005. }
  3006. self._raise('fileunlock', [self.filestack, self._getExtraData()]);
  3007. return self.$element;
  3008. },
  3009. cancel: function () {
  3010. var self = this, xhr = self.ajaxRequests, len = xhr.length, i;
  3011. if (len > 0) {
  3012. for (i = 0; i < len; i += 1) {
  3013. self.cancelling = true;
  3014. xhr[i].abort();
  3015. }
  3016. }
  3017. self._setProgressCancelled();
  3018. self._getThumbs().each(function () {
  3019. var $thumb = $(this), ind = $thumb.attr('data-fileindex');
  3020. $thumb.removeClass('file-uploading');
  3021. if (self.filestack[ind] !== undefined) {
  3022. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  3023. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  3024. }
  3025. self.unlock();
  3026. });
  3027. return self.$element;
  3028. },
  3029. clear: function () {
  3030. var self = this, cap;
  3031. self.$btnUpload.removeAttr('disabled');
  3032. self._getThumbs().find('video,audio,img').each(function () {
  3033. cleanMemory($(this));
  3034. });
  3035. self._resetUpload();
  3036. self.clearStack();
  3037. self._clearFileInput();
  3038. self._resetErrors(true);
  3039. self._raise('fileclear');
  3040. if (self._hasInitialPreview()) {
  3041. self._showFileIcon();
  3042. self._resetPreview();
  3043. self._initPreviewActions();
  3044. self.$container.removeClass('file-input-new');
  3045. } else {
  3046. self._getThumbs().each(function () {
  3047. self._clearObjects($(this));
  3048. });
  3049. if (self.isUploadable) {
  3050. previewCache.data[self.id] = {};
  3051. }
  3052. self.$preview.html('');
  3053. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  3054. self.$caption.html(cap);
  3055. self.$caption.attr('title', '');
  3056. addCss(self.$container, 'file-input-new');
  3057. self._validateDefaultPreview();
  3058. }
  3059. if (self.$container.find(FRAMES).length === 0) {
  3060. if (!self._initCaption()) {
  3061. self.$captionContainer.find('.kv-caption-icon').hide();
  3062. }
  3063. }
  3064. self._hideFileIcon();
  3065. self._raise('filecleared');
  3066. self.$captionContainer.focus();
  3067. self._setFileDropZoneTitle();
  3068. return self.$element;
  3069. },
  3070. reset: function () {
  3071. var self = this;
  3072. self._resetPreview();
  3073. self.$container.find('.fileinput-filename').text('');
  3074. self._raise('filereset');
  3075. addCss(self.$container, 'file-input-new');
  3076. if (self.$preview.find(FRAMES).length || self.isUploadable && self.dropZoneEnabled) {
  3077. self.$container.removeClass('file-input-new');
  3078. }
  3079. self._setFileDropZoneTitle();
  3080. self.clearStack();
  3081. self.formdata = {};
  3082. return self.$element;
  3083. },
  3084. disable: function () {
  3085. var self = this;
  3086. self.isDisabled = true;
  3087. self._raise('filedisabled');
  3088. self.$element.attr('disabled', 'disabled');
  3089. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  3090. self.$container.find(".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").attr(
  3091. "disabled",
  3092. true);
  3093. self._initDragDrop();
  3094. return self.$element;
  3095. },
  3096. enable: function () {
  3097. var self = this;
  3098. self.isDisabled = false;
  3099. self._raise('fileenabled');
  3100. self.$element.removeAttr('disabled');
  3101. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  3102. self.$container.find(
  3103. ".btn-file, .fileinput-remove, .fileinput-upload, .file-preview-frame button").removeAttr("disabled");
  3104. self._initDragDrop();
  3105. return self.$element;
  3106. },
  3107. upload: function () {
  3108. var self = this, totLen = self.getFileStack().length, params = {}, i, outData, len,
  3109. hasExtraData = !$.isEmptyObject(self._getExtraData());
  3110. if (!self.isUploadable || self.isDisabled) {
  3111. return;
  3112. }
  3113. if (self.minFileCount > 0 && self._getFileCount(totLen) < self.minFileCount) {
  3114. self._noFilesError(params);
  3115. return;
  3116. }
  3117. if (totLen === 0 && !hasExtraData) {
  3118. self._resetUpload();
  3119. self._showUploadError(self.msgUploadEmpty);
  3120. return;
  3121. }
  3122. self._resetUpload();
  3123. self.$progress.removeClass('hide');
  3124. self.uploadCount = 0;
  3125. self.uploadStatus = {};
  3126. self.uploadLog = [];
  3127. self.lock();
  3128. self._setProgress(2);
  3129. if (totLen === 0 && hasExtraData) {
  3130. self._uploadExtraOnly();
  3131. return;
  3132. }
  3133. len = self.filestack.length;
  3134. self.hasInitData = false;
  3135. if (self.uploadAsync) {
  3136. outData = self._getOutData();
  3137. self._raise('filebatchpreupload', [outData]);
  3138. self.fileBatchCompleted = false;
  3139. self.uploadCache = {content: [], config: [], tags: [], append: true};
  3140. self.uploadAsyncCount = self.getFileStack().length;
  3141. for (i = 0; i < len; i++) {
  3142. self.uploadCache.content[i] = null;
  3143. self.uploadCache.config[i] = null;
  3144. self.uploadCache.tags[i] = null;
  3145. }
  3146. self.$preview.find('.file-preview-initial').removeClass(SORT_CSS);
  3147. self._initSortable();
  3148. self.cacheInitialPreview = {
  3149. content: self.initialPreview,
  3150. config: self.initialPreviewConfig,
  3151. tags: self.initialPreviewThumbTags
  3152. };
  3153. for (i = 0; i < len; i++) {
  3154. if (self.filestack[i] !== undefined) {
  3155. self._uploadSingle(i, self.filestack, true);
  3156. }
  3157. }
  3158. return;
  3159. }
  3160. self._uploadBatch();
  3161. return self.$element;
  3162. },
  3163. destroy: function () {
  3164. var self = this, $cont = self.$container;
  3165. $cont.find('.file-drop-zone').off();
  3166. self.$element.insertBefore($cont).off(NAMESPACE).removeData();
  3167. $cont.off().remove();
  3168. return self.$element;
  3169. },
  3170. refresh: function (options) {
  3171. var self = this, $el = self.$element;
  3172. options = options ? $.extend(true, {}, self.options, options) : self.options;
  3173. self.destroy();
  3174. $el.fileinput(options);
  3175. if ($el.val()) {
  3176. $el.trigger('change.fileinput');
  3177. }
  3178. return $el;
  3179. }
  3180. };
  3181. $.fn.fileinput = function (option) {
  3182. if (!hasFileAPISupport() && !isIE(9)) {
  3183. return;
  3184. }
  3185. var args = Array.apply(null, arguments), retvals = [];
  3186. args.shift();
  3187. this.each(function () {
  3188. var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option,
  3189. theme = options.theme || self.data('theme'), l = {}, t = {},
  3190. lang = options.language || self.data('language') || $.fn.fileinput.defaults.language || 'en', opts;
  3191. if (!data) {
  3192. if (theme) {
  3193. t = $.fn.fileinputThemes[theme] || {};
  3194. }
  3195. if (lang !== 'en' && !isEmpty($.fn.fileinputLocales[lang])) {
  3196. l = $.fn.fileinputLocales[lang] || {};
  3197. }
  3198. opts = $.extend(true, {}, $.fn.fileinput.defaults, t, $.fn.fileinputLocales.en, l, options,
  3199. self.data());
  3200. data = new FileInput(this, opts);
  3201. self.data('fileinput', data);
  3202. }
  3203. if (typeof option === 'string') {
  3204. retvals.push(data[option].apply(data, args));
  3205. }
  3206. });
  3207. switch (retvals.length) {
  3208. case 0:
  3209. return this;
  3210. case 1:
  3211. return retvals[0];
  3212. default:
  3213. return retvals;
  3214. }
  3215. };
  3216. $.fn.fileinput.defaults = {
  3217. language: 'en',
  3218. showCaption: true,
  3219. showBrowse: true,
  3220. showPreview: true,
  3221. showRemove: true,
  3222. showUpload: true,
  3223. showCancel: true,
  3224. showClose: true,
  3225. showUploadedThumbs: true,
  3226. browseOnZoneClick: false,
  3227. autoReplace: false,
  3228. previewClass: '',
  3229. captionClass: '',
  3230. mainClass: 'file-caption-main',
  3231. mainTemplate: null,
  3232. purifyHtml: true,
  3233. fileSizeGetter: null,
  3234. initialCaption: '',
  3235. initialPreview: [],
  3236. initialPreviewDelimiter: '*$$*',
  3237. initialPreviewAsData: false,
  3238. initialPreviewFileType: 'image',
  3239. initialPreviewConfig: [],
  3240. initialPreviewThumbTags: [],
  3241. previewThumbTags: {},
  3242. initialPreviewShowDelete: true,
  3243. removeFromPreviewOnError: false,
  3244. deleteUrl: '',
  3245. deleteExtraData: {},
  3246. overwriteInitial: true,
  3247. layoutTemplates: defaultLayoutTemplates,
  3248. previewTemplates: defaultPreviewTemplates,
  3249. previewZoomSettings: defaultPreviewZoomSettings,
  3250. previewZoomButtonIcons: {
  3251. prev: '<i class="glyphicon glyphicon-triangle-left"></i>',
  3252. next: '<i class="glyphicon glyphicon-triangle-right"></i>',
  3253. toggleheader: '<i class="glyphicon glyphicon-resize-vertical"></i>',
  3254. fullscreen: '<i class="glyphicon glyphicon-fullscreen"></i>',
  3255. borderless: '<i class="glyphicon glyphicon-resize-full"></i>',
  3256. close: '<i class="glyphicon glyphicon-remove"></i>'
  3257. },
  3258. previewZoomButtonClasses: {
  3259. prev: 'btn btn-navigate',
  3260. next: 'btn btn-navigate',
  3261. toggleheader: 'btn btn-default btn-header-toggle',
  3262. fullscreen: 'btn btn-default',
  3263. borderless: 'btn btn-default',
  3264. close: 'btn btn-default'
  3265. },
  3266. preferIconicPreview: false,
  3267. preferIconicZoomPreview: false,
  3268. allowedPreviewTypes: undefined,
  3269. allowedPreviewMimeTypes: null,
  3270. allowedFileTypes: null,
  3271. allowedFileExtensions: null,
  3272. defaultPreviewContent: null,
  3273. customLayoutTags: {},
  3274. customPreviewTags: {},
  3275. previewSettings: defaultPreviewSettings,
  3276. fileTypeSettings: defaultFileTypeSettings,
  3277. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  3278. previewFileIconClass: 'file-other-icon',
  3279. previewFileIconSettings: {},
  3280. previewFileExtSettings: {},
  3281. buttonLabelClass: 'hidden-xs',
  3282. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i>&nbsp;',
  3283. browseClass: 'btn btn-primary',
  3284. removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
  3285. removeClass: 'btn btn-default',
  3286. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i>',
  3287. cancelClass: 'btn btn-default',
  3288. uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
  3289. uploadClass: 'btn btn-default',
  3290. uploadUrl: null,
  3291. uploadAsync: true,
  3292. uploadExtraData: {},
  3293. zoomModalHeight: 480,
  3294. minImageWidth: null,
  3295. minImageHeight: null,
  3296. maxImageWidth: null,
  3297. maxImageHeight: null,
  3298. resizeImage: false,
  3299. resizePreference: 'width',
  3300. resizeQuality: 0.92,
  3301. resizeDefaultImageType: 'image/jpeg',
  3302. minFileSize: 0,
  3303. maxFileSize: 0,
  3304. maxFilePreviewSize: 25600, // 25 MB
  3305. minFileCount: 0,
  3306. maxFileCount: 0,
  3307. validateInitialCount: false,
  3308. msgValidationErrorClass: 'text-danger',
  3309. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  3310. msgErrorClass: 'file-error-message',
  3311. progressThumbClass: "progress-bar progress-bar-success progress-bar-striped active",
  3312. progressClass: "progress-bar progress-bar-success progress-bar-striped active",
  3313. progressCompleteClass: "progress-bar progress-bar-success",
  3314. progressErrorClass: "progress-bar progress-bar-danger",
  3315. progressUploadThreshold: 99,
  3316. previewFileType: 'image',
  3317. elCaptionContainer: null,
  3318. elCaptionText: null,
  3319. elPreviewContainer: null,
  3320. elPreviewImage: null,
  3321. elPreviewStatus: null,
  3322. elErrorContainer: null,
  3323. errorCloseButton: '<span class="close kv-error-close">&times;</span>',
  3324. slugCallback: null,
  3325. dropZoneEnabled: true,
  3326. dropZoneTitleClass: 'file-drop-zone-title',
  3327. fileActionSettings: {},
  3328. otherActionButtons: '',
  3329. textEncoding: 'UTF-8',
  3330. ajaxSettings: {},
  3331. ajaxDeleteSettings: {},
  3332. showAjaxErrorDetails: true
  3333. };
  3334. $.fn.fileinputLocales.en = {
  3335. fileSingle: 'file',
  3336. filePlural: 'files',
  3337. browseLabel: 'Browse &hellip;',
  3338. removeLabel: 'Remove',
  3339. removeTitle: 'Clear selected files',
  3340. cancelLabel: 'Cancel',
  3341. cancelTitle: 'Abort ongoing upload',
  3342. uploadLabel: 'Upload',
  3343. uploadTitle: 'Upload selected files',
  3344. msgNo: 'No',
  3345. msgNoFilesSelected: 'No files selected',
  3346. msgCancelled: 'Cancelled',
  3347. msgZoomModalHeading: 'Detailed Preview',
  3348. msgSizeTooSmall: 'File "{name}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.',
  3349. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
  3350. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
  3351. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
  3352. msgFileNotFound: 'File "{name}" not found!',
  3353. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  3354. msgFileNotReadable: 'File "{name}" is not readable.',
  3355. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  3356. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  3357. msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".',
  3358. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  3359. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  3360. msgFileTypes: {
  3361. 'image': 'image',
  3362. 'html': 'HTML',
  3363. 'text': 'text',
  3364. 'video': 'video',
  3365. 'audio': 'audio',
  3366. 'flash': 'flash',
  3367. 'pdf': 'PDF',
  3368. 'object': 'object'
  3369. },
  3370. msgUploadAborted: 'The file upload was aborted',
  3371. msgUploadThreshold: 'Processing...',
  3372. msgUploadEmpty: 'No valid data available for upload.',
  3373. msgValidationError: 'Validation Error',
  3374. msgLoading: 'Loading file {index} of {files} &hellip;',
  3375. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  3376. msgSelected: '{n} {files} selected',
  3377. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  3378. msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
  3379. msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
  3380. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
  3381. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
  3382. msgImageResizeError: 'Could not get the image dimensions to resize.',
  3383. msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>',
  3384. dropZoneTitle: 'Drag & drop files here &hellip;',
  3385. dropZoneClickTitle: '<br>(or click to select {files})',
  3386. previewZoomButtonTitles: {
  3387. prev: 'View previous file',
  3388. next: 'View next file',
  3389. toggleheader: 'Toggle header',
  3390. fullscreen: 'Toggle full screen',
  3391. borderless: 'Toggle borderless mode',
  3392. close: 'Close detailed preview'
  3393. }
  3394. };
  3395. $.fn.fileinput.Constructor = FileInput;
  3396. /**
  3397. * Convert automatically file inputs with class 'file' into a bootstrap fileinput control.
  3398. */
  3399. $(document).ready(function () {
  3400. var $input = $('input.file[type=file]');
  3401. if ($input.length) {
  3402. $input.fileinput();
  3403. }
  3404. });
  3405. }));