fileinput.js 196 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301
  1. /*!
  2. * bootstrap-fileinput v4.4.6
  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. String.prototype.setTokens = function (replacePairs) {
  32. var str = this.toString(), key, re;
  33. for (key in replacePairs) {
  34. if (replacePairs.hasOwnProperty(key)) {
  35. re = new RegExp("\{" + key + "\}", "g");
  36. str = str.replace(re, replacePairs[key]);
  37. }
  38. }
  39. return str;
  40. };
  41. var $h, FileInput;
  42. // fileinput helper object for all global variables and internal helper methods
  43. //noinspection JSUnresolvedVariable
  44. $h = {
  45. FRAMES: '.kv-preview-thumb',
  46. SORT_CSS: 'file-sortable',
  47. OBJECT_PARAMS: '<param name="controller" value="true" />\n' +
  48. '<param name="allowFullScreen" value="true" />\n' +
  49. '<param name="allowScriptAccess" value="always" />\n' +
  50. '<param name="autoPlay" value="false" />\n' +
  51. '<param name="autoStart" value="false" />\n' +
  52. '<param name="quality" value="high" />\n',
  53. DEFAULT_PREVIEW: '<div class="file-preview-other">\n' +
  54. '<span class="{previewFileIconClass}">{previewFileIcon}</span>\n' +
  55. '</div>',
  56. MODAL_ID: 'kvFileinputModal',
  57. MODAL_EVENTS: ['show', 'shown', 'hide', 'hidden', 'loaded'],
  58. objUrl: window.URL || window.webkitURL,
  59. compare: function (input, str, exact) {
  60. return input !== undefined && (exact ? input === str : input.match(str));
  61. },
  62. isIE: function (ver) {
  63. // check for IE versions < 11
  64. if (navigator.appName !== 'Microsoft Internet Explorer') {
  65. return false;
  66. }
  67. if (ver === 10) {
  68. return new RegExp('msie\\s' + ver, 'i').test(navigator.userAgent);
  69. }
  70. var div = document.createElement("div"), status;
  71. div.innerHTML = "<!--[if IE " + ver + "]> <i></i> <![endif]-->";
  72. status = div.getElementsByTagName("i").length;
  73. document.body.appendChild(div);
  74. div.parentNode.removeChild(div);
  75. return status;
  76. },
  77. initModal: function ($modal) {
  78. var $body = $('body');
  79. if ($body.length) {
  80. $modal.appendTo($body);
  81. }
  82. },
  83. isEmpty: function (value, trim) {
  84. return value === undefined || value === null || value.length === 0 || (trim && $.trim(value) === '');
  85. },
  86. isArray: function (a) {
  87. return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]';
  88. },
  89. ifSet: function (needle, haystack, def) {
  90. def = def || '';
  91. return (haystack && typeof haystack === 'object' && needle in haystack) ? haystack[needle] : def;
  92. },
  93. cleanArray: function (arr) {
  94. if (!(arr instanceof Array)) {
  95. arr = [];
  96. }
  97. return arr.filter(function (e) {
  98. return (e !== undefined && e !== null);
  99. });
  100. },
  101. spliceArray: function (arr, index) {
  102. var i, j = 0, out = [];
  103. if (!(arr instanceof Array)) {
  104. return [];
  105. }
  106. for (i = 0; i < arr.length; i++) {
  107. if (i !== index) {
  108. out[j] = arr[i];
  109. j++;
  110. }
  111. }
  112. return out;
  113. },
  114. getNum: function (num, def) {
  115. def = def || 0;
  116. if (typeof num === "number") {
  117. return num;
  118. }
  119. if (typeof num === "string") {
  120. num = parseFloat(num);
  121. }
  122. return isNaN(num) ? def : num;
  123. },
  124. hasFileAPISupport: function () {
  125. return !!(window.File && window.FileReader);
  126. },
  127. hasDragDropSupport: function () {
  128. var div = document.createElement('div');
  129. /** @namespace div.draggable */
  130. /** @namespace div.ondragstart */
  131. /** @namespace div.ondrop */
  132. return !$h.isIE(9) &&
  133. (div.draggable !== undefined || (div.ondragstart !== undefined && div.ondrop !== undefined));
  134. },
  135. hasFileUploadSupport: function () {
  136. return $h.hasFileAPISupport() && window.FormData;
  137. },
  138. hasBlobSupport: function () {
  139. try {
  140. return !!window.Blob && Boolean(new Blob());
  141. } catch (e) {
  142. return false;
  143. }
  144. },
  145. hasArrayBufferViewSupport: function () {
  146. try {
  147. return new Blob([new Uint8Array(100)]).size === 100;
  148. } catch (e) {
  149. return false;
  150. }
  151. },
  152. dataURI2Blob: function (dataURI) {
  153. //noinspection JSUnresolvedVariable
  154. var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder ||
  155. window.MSBlobBuilder, canBlob = $h.hasBlobSupport(), byteStr, arrayBuffer, intArray, i, mimeStr, bb,
  156. canProceed = (canBlob || BlobBuilder) && window.atob && window.ArrayBuffer && window.Uint8Array;
  157. if (!canProceed) {
  158. return null;
  159. }
  160. if (dataURI.split(',')[0].indexOf('base64') >= 0) {
  161. byteStr = atob(dataURI.split(',')[1]);
  162. } else {
  163. byteStr = decodeURIComponent(dataURI.split(',')[1]);
  164. }
  165. arrayBuffer = new ArrayBuffer(byteStr.length);
  166. intArray = new Uint8Array(arrayBuffer);
  167. for (i = 0; i < byteStr.length; i += 1) {
  168. intArray[i] = byteStr.charCodeAt(i);
  169. }
  170. mimeStr = dataURI.split(',')[0].split(':')[1].split(';')[0];
  171. if (canBlob) {
  172. return new Blob([$h.hasArrayBufferViewSupport() ? intArray : arrayBuffer], {type: mimeStr});
  173. }
  174. bb = new BlobBuilder();
  175. bb.append(arrayBuffer);
  176. return bb.getBlob(mimeStr);
  177. },
  178. arrayBuffer2String: function (buffer) {
  179. //noinspection JSUnresolvedVariable
  180. if (window.TextDecoder) {
  181. return new TextDecoder("utf-8").decode(buffer);
  182. }
  183. var array = Array.prototype.slice.apply(new Uint8Array(buffer)), out = '', i = 0, len, c, char2, char3;
  184. len = array.length;
  185. while (i < len) {
  186. c = array[i++];
  187. switch (c >> 4) { // jshint ignore:line
  188. case 0:
  189. case 1:
  190. case 2:
  191. case 3:
  192. case 4:
  193. case 5:
  194. case 6:
  195. case 7:
  196. // 0xxxxxxx
  197. out += String.fromCharCode(c);
  198. break;
  199. case 12:
  200. case 13:
  201. // 110x xxxx 10xx xxxx
  202. char2 = array[i++];
  203. out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); // jshint ignore:line
  204. break;
  205. case 14:
  206. // 1110 xxxx 10xx xxxx 10xx xxxx
  207. char2 = array[i++];
  208. char3 = array[i++];
  209. out += String.fromCharCode(((c & 0x0F) << 12) | // jshint ignore:line
  210. ((char2 & 0x3F) << 6) | // jshint ignore:line
  211. ((char3 & 0x3F) << 0)); // jshint ignore:line
  212. break;
  213. }
  214. }
  215. return out;
  216. },
  217. isHtml: function (str) {
  218. var a = document.createElement('div');
  219. a.innerHTML = str;
  220. for (var c = a.childNodes, i = c.length; i--;) {
  221. if (c[i].nodeType === 1) {
  222. return true;
  223. }
  224. }
  225. return false;
  226. },
  227. isSvg: function (str) {
  228. return str.match(/^\s*<\?xml/i) && (str.match(/<!DOCTYPE svg/i) || str.match(/<svg/i));
  229. },
  230. getMimeType: function (signature, contents, type) {
  231. switch (signature) {
  232. case "ffd8ffe0":
  233. case "ffd8ffe1":
  234. case "ffd8ffe2":
  235. return 'image/jpeg';
  236. case '89504E47':
  237. return 'image/png';
  238. case '47494638':
  239. return 'image/gif';
  240. case '49492a00':
  241. return 'image/tiff';
  242. case '52494646':
  243. return 'image/webp';
  244. case '66747970':
  245. return 'video/3gp';
  246. case '4f676753':
  247. return 'video/ogg';
  248. case '1a45dfa3':
  249. return 'video/mkv';
  250. case '000001ba':
  251. case '000001b3':
  252. return 'video/mpeg';
  253. case '3026b275':
  254. return 'video/wmv';
  255. case '25504446':
  256. return 'application/pdf';
  257. case '25215053':
  258. return 'application/ps';
  259. case '504b0304':
  260. case '504b0506':
  261. case '504b0508':
  262. return 'application/zip';
  263. case '377abcaf':
  264. return 'application/7z';
  265. case '75737461':
  266. return 'application/tar';
  267. case '7801730d':
  268. return 'application/dmg';
  269. default:
  270. switch (signature.substring(0, 6)) {
  271. case '435753':
  272. return 'application/x-shockwave-flash';
  273. case '494433':
  274. return 'audio/mp3';
  275. case '425a68':
  276. return 'application/bzip';
  277. default:
  278. switch (signature.substring(0, 4)) {
  279. case '424d':
  280. return 'image/bmp';
  281. case 'fffb':
  282. return 'audio/mp3';
  283. case '4d5a':
  284. return 'application/exe';
  285. case '1f9d':
  286. case '1fa0':
  287. return 'application/zip';
  288. case '1f8b':
  289. return 'application/gzip';
  290. default:
  291. return contents && !contents.match(/[^\u0000-\u007f]/) ? 'application/text-plain' : type;
  292. }
  293. }
  294. }
  295. },
  296. addCss: function ($el, css) {
  297. $el.removeClass(css).addClass(css);
  298. },
  299. getElement: function (options, param, value) {
  300. return ($h.isEmpty(options) || $h.isEmpty(options[param])) ? value : $(options[param]);
  301. },
  302. uniqId: function () {
  303. return Math.round(new Date().getTime()) + '_' + Math.round(Math.random() * 100);
  304. },
  305. htmlEncode: function (str) {
  306. return str.replace(/&/g, '&amp;')
  307. .replace(/</g, '&lt;')
  308. .replace(/>/g, '&gt;')
  309. .replace(/"/g, '&quot;')
  310. .replace(/'/g, '&apos;');
  311. },
  312. replaceTags: function (str, tags) {
  313. var out = str;
  314. if (!tags) {
  315. return out;
  316. }
  317. $.each(tags, function (key, value) {
  318. if (typeof value === "function") {
  319. value = value();
  320. }
  321. out = out.split(key).join(value);
  322. });
  323. return out;
  324. },
  325. cleanMemory: function ($thumb) {
  326. var data = $thumb.is('img') ? $thumb.attr('src') : $thumb.find('source').attr('src');
  327. /** @namespace $h.objUrl.revokeObjectURL */
  328. $h.objUrl.revokeObjectURL(data);
  329. },
  330. findFileName: function (filePath) {
  331. var sepIndex = filePath.lastIndexOf('/');
  332. if (sepIndex === -1) {
  333. sepIndex = filePath.lastIndexOf('\\');
  334. }
  335. return filePath.split(filePath.substring(sepIndex, sepIndex + 1)).pop();
  336. },
  337. checkFullScreen: function () {
  338. //noinspection JSUnresolvedVariable
  339. return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement ||
  340. document.msFullscreenElement;
  341. },
  342. toggleFullScreen: function (maximize) {
  343. var doc = document, de = doc.documentElement;
  344. if (de && maximize && !$h.checkFullScreen()) {
  345. /** @namespace document.requestFullscreen */
  346. /** @namespace document.msRequestFullscreen */
  347. /** @namespace document.mozRequestFullScreen */
  348. /** @namespace document.webkitRequestFullscreen */
  349. /** @namespace Element.ALLOW_KEYBOARD_INPUT */
  350. if (de.requestFullscreen) {
  351. de.requestFullscreen();
  352. } else if (de.msRequestFullscreen) {
  353. de.msRequestFullscreen();
  354. } else if (de.mozRequestFullScreen) {
  355. de.mozRequestFullScreen();
  356. } else if (de.webkitRequestFullscreen) {
  357. de.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
  358. }
  359. } else {
  360. /** @namespace document.exitFullscreen */
  361. /** @namespace document.msExitFullscreen */
  362. /** @namespace document.mozCancelFullScreen */
  363. /** @namespace document.webkitExitFullscreen */
  364. if (doc.exitFullscreen) {
  365. doc.exitFullscreen();
  366. } else if (doc.msExitFullscreen) {
  367. doc.msExitFullscreen();
  368. } else if (doc.mozCancelFullScreen) {
  369. doc.mozCancelFullScreen();
  370. } else if (doc.webkitExitFullscreen) {
  371. doc.webkitExitFullscreen();
  372. }
  373. }
  374. },
  375. moveArray: function (arr, oldIndex, newIndex) {
  376. if (newIndex >= arr.length) {
  377. var k = newIndex - arr.length;
  378. while ((k--) + 1) {
  379. arr.push(undefined);
  380. }
  381. }
  382. arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]);
  383. return arr;
  384. },
  385. cleanZoomCache: function ($el) {
  386. var $cache = $el.closest('.kv-zoom-cache-theme');
  387. if (!$cache.length) {
  388. $cache = $el.closest('.kv-zoom-cache');
  389. }
  390. $cache.remove();
  391. },
  392. setOrientation: function (buffer, callback) {
  393. var scanner = new DataView(buffer), idx = 0, value = 1, // Non-rotated is the default
  394. maxBytes, uInt16, exifLength;
  395. if (scanner.getUint16(idx) !== 0xFFD8 || buffer.length < 2) { // not a proper JPEG
  396. if (callback) {
  397. callback();
  398. }
  399. return;
  400. }
  401. idx += 2;
  402. maxBytes = scanner.byteLength;
  403. while (idx < maxBytes - 2) {
  404. uInt16 = scanner.getUint16(idx);
  405. idx += 2;
  406. switch (uInt16) {
  407. case 0xFFE1: // Start of EXIF
  408. exifLength = scanner.getUint16(idx);
  409. maxBytes = exifLength - idx;
  410. idx += 2;
  411. break;
  412. case 0x0112: // Orientation tag
  413. value = scanner.getUint16(idx + 6, false);
  414. maxBytes = 0; // Stop scanning
  415. break;
  416. }
  417. }
  418. if (callback) {
  419. callback(value);
  420. }
  421. },
  422. validateOrientation: function (file, callback) {
  423. if (!window.FileReader || !window.DataView) {
  424. return; // skip orientation if pre-requisite libraries not supported by browser
  425. }
  426. var reader = new FileReader(), buffer;
  427. reader.onloadend = function () {
  428. buffer = reader.result;
  429. $h.setOrientation(buffer, callback);
  430. };
  431. reader.readAsArrayBuffer(file);
  432. },
  433. adjustOrientedImage: function ($img, isZoom) {
  434. var offsetContTop, offsetTop, newTop;
  435. if (!$img.hasClass('is-portrait-gt4')) {
  436. return;
  437. }
  438. if (isZoom) {
  439. $img.css({width: $img.parent().height()});
  440. return;
  441. } else {
  442. $img.css({height: 'auto', width: $img.height()});
  443. }
  444. offsetContTop = $img.parent().offset().top;
  445. offsetTop = $img.offset().top;
  446. newTop = offsetContTop - offsetTop;
  447. $img.css('margin-top', newTop);
  448. }
  449. };
  450. FileInput = function (element, options) {
  451. var self = this;
  452. self.$element = $(element);
  453. self.$parent = self.$element.parent();
  454. if (!self._validate()) {
  455. return;
  456. }
  457. self.isPreviewable = $h.hasFileAPISupport();
  458. self.isIE9 = $h.isIE(9);
  459. self.isIE10 = $h.isIE(10);
  460. if (self.isPreviewable || self.isIE9) {
  461. self._init(options);
  462. self._listen();
  463. }
  464. self.$element.removeClass('file-loading');
  465. };
  466. //noinspection JSUnusedGlobalSymbols
  467. FileInput.prototype = {
  468. constructor: FileInput,
  469. _cleanup: function () {
  470. var self = this;
  471. self.reader = null;
  472. self.formdata = {};
  473. self.uploadCount = 0;
  474. self.uploadStatus = {};
  475. self.uploadLog = [];
  476. self.uploadAsyncCount = 0;
  477. self.loadedImages = [];
  478. self.totalImagesCount = 0;
  479. self.ajaxRequests = [];
  480. self.clearStack();
  481. self.fileInputCleared = false;
  482. self.fileBatchCompleted = true;
  483. if (!self.isPreviewable) {
  484. self.showPreview = false;
  485. }
  486. self.isError = false;
  487. self.ajaxAborted = false;
  488. self.cancelling = false;
  489. },
  490. _init: function (options, refreshMode) {
  491. var self = this, f, $el = self.$element, $cont, t, tmp;
  492. self.options = options;
  493. $.each(options, function (key, value) {
  494. switch (key) {
  495. case 'minFileCount':
  496. case 'maxFileCount':
  497. case 'minFileSize':
  498. case 'maxFileSize':
  499. case 'maxFilePreviewSize':
  500. case 'resizeImageQuality':
  501. case 'resizeIfSizeMoreThan':
  502. case 'progressUploadThreshold':
  503. case 'initialPreviewCount':
  504. case 'zoomModalHeight':
  505. case 'minImageHeight':
  506. case 'maxImageHeight':
  507. case 'minImageWidth':
  508. case 'maxImageWidth':
  509. self[key] = $h.getNum(value);
  510. break;
  511. default:
  512. self[key] = value;
  513. break;
  514. }
  515. });
  516. if (self.rtl) { // swap buttons for rtl
  517. tmp = self.previewZoomButtonIcons.prev;
  518. self.previewZoomButtonIcons.prev = self.previewZoomButtonIcons.next;
  519. self.previewZoomButtonIcons.next = tmp;
  520. }
  521. if (!refreshMode) {
  522. self._cleanup();
  523. }
  524. self.$form = $el.closest('form');
  525. self._initTemplateDefaults();
  526. self.uploadFileAttr = !$h.isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data';
  527. t = self._getLayoutTemplate('progress');
  528. self.progressTemplate = t.replace('{class}', self.progressClass);
  529. self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass);
  530. self.progressErrorTemplate = t.replace('{class}', self.progressErrorClass);
  531. self.dropZoneEnabled = $h.hasDragDropSupport() && self.dropZoneEnabled;
  532. self.isDisabled = $el.attr('disabled') || $el.attr('readonly');
  533. if (self.isDisabled) {
  534. $el.attr('disabled', true);
  535. }
  536. self.isAjaxUpload = $h.hasFileUploadSupport() && !$h.isEmpty(self.uploadUrl);
  537. self.isClickable = self.browseOnZoneClick && self.showPreview &&
  538. (self.isAjaxUpload && self.dropZoneEnabled || !$h.isEmpty(self.defaultPreviewContent));
  539. self.slug = typeof options.slugCallback === "function" ? options.slugCallback : self._slugDefault;
  540. self.mainTemplate = self.showCaption ? self._getLayoutTemplate('main1') : self._getLayoutTemplate('main2');
  541. self.captionTemplate = self._getLayoutTemplate('caption');
  542. self.previewGenericTemplate = self._getPreviewTemplate('generic');
  543. if (!self.imageCanvas && self.resizeImage && (self.maxImageWidth || self.maxImageHeight)) {
  544. self.imageCanvas = document.createElement('canvas');
  545. self.imageCanvasContext = self.imageCanvas.getContext('2d');
  546. }
  547. if ($h.isEmpty($el.attr('id'))) {
  548. $el.attr('id', $h.uniqId());
  549. }
  550. self.namespace = '.fileinput_' + $el.attr('id').replace(/-/g, '_');
  551. if (self.$container === undefined) {
  552. self.$container = self._createContainer();
  553. } else {
  554. self._refreshContainer();
  555. }
  556. $cont = self.$container;
  557. self.$dropZone = $cont.find('.file-drop-zone');
  558. self.$progress = $cont.find('.kv-upload-progress');
  559. self.$btnUpload = $cont.find('.fileinput-upload');
  560. self.$captionContainer = $h.getElement(options, 'elCaptionContainer', $cont.find('.file-caption'));
  561. self.$caption = $h.getElement(options, 'elCaptionText', $cont.find('.file-caption-name'));
  562. if (!$h.isEmpty(self.msgPlaceholder)) {
  563. f = $el.attr('multiple') ? self.filePlural : self.fileSingle;
  564. self.$caption.attr('placeholder', self.msgPlaceholder.replace('{files}', f));
  565. }
  566. self.$captionIcon = self.$captionContainer.find('.file-caption-icon');
  567. if (self.mainClass.indexOf('input-group-lg') > -1) {
  568. $h.addCss(self.$captionIcon, 'icon-lg');
  569. } else {
  570. self.$captionIcon.removeClass('icon-lg');
  571. }
  572. self.$previewContainer = $h.getElement(options, 'elPreviewContainer', $cont.find('.file-preview'));
  573. self.$preview = $h.getElement(options, 'elPreviewImage', $cont.find('.file-preview-thumbnails'));
  574. self.$previewStatus = $h.getElement(options, 'elPreviewStatus', $cont.find('.file-preview-status'));
  575. self.$errorContainer = $h.getElement(options, 'elErrorContainer',
  576. self.$previewContainer.find('.kv-fileinput-error'));
  577. self._validateDisabled();
  578. if (!$h.isEmpty(self.msgErrorClass)) {
  579. $h.addCss(self.$errorContainer, self.msgErrorClass);
  580. }
  581. if (!refreshMode) {
  582. self.$errorContainer.hide();
  583. self.previewInitId = "preview-" + $h.uniqId();
  584. self._initPreviewCache();
  585. self._initPreview(true);
  586. self._initPreviewActions();
  587. self._setFileDropZoneTitle();
  588. if (self.$parent.hasClass('file-loading')) {
  589. self.$container.insertBefore(self.$parent);
  590. self.$parent.remove();
  591. }
  592. }
  593. if ($el.attr('disabled')) {
  594. self.disable();
  595. }
  596. self._initZoom();
  597. if (self.hideThumbnailContent) {
  598. $h.addCss(self.$preview, 'hide-content');
  599. }
  600. },
  601. _initTemplateDefaults: function () {
  602. var self = this, tMain1, tMain2, tPreview, tFileIcon, tClose, tCaption, tBtnDefault, tBtnLink, tBtnBrowse,
  603. tModalMain, tModal, tProgress, tSize, tFooter, tActions, tActionDelete, tActionUpload, tActionDownload,
  604. tActionZoom, tActionDrag, tIndicator, tTagBef, tTagBef1, tTagBef2, tTagAft, tGeneric, tHtml, tImage,
  605. tText, tOffice, tVideo, tAudio, tFlash, tObject, tPdf, tOther, tZoomCache, vDefaultDim;
  606. tMain1 = '{preview}\n' +
  607. '<div class="kv-upload-progress kv-hidden"></div><div class="clearfix"></div>\n' +
  608. '<div class="input-group {class}">\n' +
  609. ' {caption}\n' +
  610. '<div class="input-group-btn">\n' +
  611. ' {remove}\n' +
  612. ' {cancel}\n' +
  613. ' {upload}\n' +
  614. ' {browse}\n' +
  615. ' </div>\n' +
  616. '</div>';
  617. tMain2 = '{preview}\n<div class="kv-upload-progress kv-hidden"></div>\n<div class="clearfix"></div>\n{remove}\n{cancel}\n{upload}\n{browse}\n';
  618. tPreview = '<div class="file-preview {class}">\n' +
  619. ' {close}' +
  620. ' <div class="{dropClass}">\n' +
  621. ' <div class="file-preview-thumbnails">\n' +
  622. ' </div>\n' +
  623. ' <div class="clearfix"></div>' +
  624. ' <div class="file-preview-status text-center text-success"></div>\n' +
  625. ' <div class="kv-fileinput-error"></div>\n' +
  626. ' </div>\n' +
  627. '</div>';
  628. tClose = '<button type="button" class="close fileinput-remove">&times;</button>\n';
  629. tFileIcon = '<i class="glyphicon glyphicon-file"></i>';
  630. tCaption = '<div class="file-caption form-control {class}" tabindex="500">\n' +
  631. ' <span class="file-caption-icon"></span>\n' +
  632. ' <input class="file-caption-name" onkeydown="return false;" onpaste="return false;">\n' +
  633. '</div>';
  634. //noinspection HtmlUnknownAttribute
  635. tBtnDefault = '<button type="{type}" tabindex="500" title="{title}" class="{css}" ' +
  636. '{status}>{icon} {label}</button>';
  637. //noinspection HtmlUnknownAttribute
  638. tBtnLink = '<a href="{href}" tabindex="500" title="{title}" class="{css}" {status}>{icon} {label}</a>';
  639. //noinspection HtmlUnknownAttribute
  640. tBtnBrowse = '<div tabindex="500" class="{css}" {status}>{icon} {label}</div>';
  641. tModalMain = '<div id="' + $h.MODAL_ID + '" class="file-zoom-dialog modal fade" ' +
  642. 'tabindex="-1" aria-labelledby="' + $h.MODAL_ID + 'Label"></div>';
  643. tModal = '<div class="modal-dialog modal-lg{rtl}" role="document">\n' +
  644. ' <div class="modal-content">\n' +
  645. ' <div class="modal-header">\n' +
  646. ' <h5 class="modal-title">{heading}</h5>\n' +
  647. ' <span class="kv-zoom-title"></span>\n' +
  648. ' <div class="kv-zoom-actions">{toggleheader}{fullscreen}{borderless}{close}</div>\n' +
  649. ' </div>\n' +
  650. ' <div class="modal-body">\n' +
  651. ' <div class="floating-buttons"></div>\n' +
  652. ' <div class="kv-zoom-body file-zoom-content {zoomFrameClass}"></div>\n' + '{prev} {next}\n' +
  653. ' </div>\n' +
  654. ' </div>\n' +
  655. '</div>\n';
  656. tProgress = '<div class="progress">\n' +
  657. ' <div class="{class}" role="progressbar"' +
  658. ' aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' +
  659. ' {status}\n' +
  660. ' </div>\n' +
  661. '</div>';
  662. tSize = ' <samp>({sizeText})</samp>';
  663. tFooter = '<div class="file-thumbnail-footer">\n' +
  664. ' <div class="file-footer-caption" title="{caption}">\n' +
  665. ' <div class="file-caption-info">{caption}</div>\n' +
  666. ' <div class="file-size-info">{size}</div>\n' +
  667. ' </div>\n' +
  668. ' {progress}\n{indicator}\n{actions}\n' +
  669. '</div>';
  670. tActions = '<div class="file-actions">\n' +
  671. ' <div class="file-footer-buttons">\n' +
  672. ' {download} {upload} {delete} {zoom} {other}' +
  673. ' </div>\n' +
  674. '</div>\n' +
  675. '{drag}\n' +
  676. '<div class="clearfix"></div>';
  677. //noinspection HtmlUnknownAttribute
  678. tActionDelete = '<button type="button" class="kv-file-remove {removeClass}" ' +
  679. 'title="{removeTitle}" {dataUrl}{dataKey}>{removeIcon}</button>\n';
  680. tActionUpload = '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">' +
  681. '{uploadIcon}</button>';
  682. tActionDownload = '<button type="button" class="kv-file-download {downloadClass}" title="{downloadTitle}" ' +
  683. 'data-url="{downloadUrl}" data-caption="{caption}">{downloadIcon}</button>';
  684. tActionZoom = '<button type="button" class="kv-file-zoom {zoomClass}" ' +
  685. 'title="{zoomTitle}">{zoomIcon}</button>';
  686. tActionDrag = '<span class="file-drag-handle {dragClass}" title="{dragTitle}">{dragIcon}</span>';
  687. tIndicator = '<div class="file-upload-indicator" title="{indicatorTitle}">{indicator}</div>';
  688. tTagBef = '<div class="file-preview-frame {frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  689. ' data-template="{template}"';
  690. tTagBef1 = tTagBef + '><div class="kv-file-content">\n';
  691. tTagBef2 = tTagBef + ' title="{caption}"><div class="kv-file-content">\n';
  692. tTagAft = '</div>{footer}\n</div>\n';
  693. tGeneric = '{content}\n';
  694. tHtml = '<div class="kv-preview-data file-preview-html" title="{caption}" {style}>{data}</div>\n';
  695. tImage = '<img src="{data}" class="file-preview-image kv-preview-data" title="{caption}" ' +
  696. 'alt="{caption}" {style}>\n';
  697. tText = '<textarea class="kv-preview-data file-preview-text" title="{caption}" readonly {style}>' +
  698. '{data}</textarea>\n';
  699. tOffice = '<iframe class="kv-preview-data file-preview-office" ' +
  700. 'src="https://docs.google.com/gview?url={data}&embedded=true" {style}></iframe>';
  701. tVideo = '<video class="kv-preview-data file-preview-video" controls {style}>\n' +
  702. '<source src="{data}" type="{type}">\n' + $h.DEFAULT_PREVIEW + '\n</video>\n';
  703. tAudio = '<audio class="kv-preview-data file-preview-audio" controls {style}>\n<source src="{data}" ' +
  704. 'type="{type}">\n' + $h.DEFAULT_PREVIEW + '\n</audio>\n';
  705. tFlash = '<embed class="kv-preview-data file-preview-flash" src="{data}" type="application/x-shockwave-flash" {style}>\n';
  706. tPdf = '<embed class="kv-preview-data file-preview-pdf" src="{data}" type="application/pdf" {style}>\n';
  707. tObject = '<object class="kv-preview-data file-preview-object file-object {typeCss}" ' +
  708. 'data="{data}" type="{type}" {style}>\n' + '<param name="movie" value="{caption}" />\n' +
  709. $h.OBJECT_PARAMS + ' ' + $h.DEFAULT_PREVIEW + '\n</object>\n';
  710. tOther = '<div class="kv-preview-data file-preview-other-frame" {style}>\n' + $h.DEFAULT_PREVIEW + '\n</div>\n';
  711. tZoomCache = '<div class="kv-zoom-cache" style="display:none">{zoomContent}</div>';
  712. vDefaultDim = {width: "100%", height: "100%", 'min-height': "480px"};
  713. self.defaults = {
  714. layoutTemplates: {
  715. main1: tMain1,
  716. main2: tMain2,
  717. preview: tPreview,
  718. close: tClose,
  719. fileIcon: tFileIcon,
  720. caption: tCaption,
  721. modalMain: tModalMain,
  722. modal: tModal,
  723. progress: tProgress,
  724. size: tSize,
  725. footer: tFooter,
  726. indicator: tIndicator,
  727. actions: tActions,
  728. actionDelete: tActionDelete,
  729. actionUpload: tActionUpload,
  730. actionDownload: tActionDownload,
  731. actionZoom: tActionZoom,
  732. actionDrag: tActionDrag,
  733. btnDefault: tBtnDefault,
  734. btnLink: tBtnLink,
  735. btnBrowse: tBtnBrowse,
  736. zoomCache: tZoomCache
  737. },
  738. previewMarkupTags: {
  739. tagBefore1: tTagBef1,
  740. tagBefore2: tTagBef2,
  741. tagAfter: tTagAft
  742. },
  743. previewContentTemplates: {
  744. generic: tGeneric,
  745. html: tHtml,
  746. image: tImage,
  747. text: tText,
  748. office: tOffice,
  749. video: tVideo,
  750. audio: tAudio,
  751. flash: tFlash,
  752. object: tObject,
  753. pdf: tPdf,
  754. other: tOther
  755. },
  756. allowedPreviewTypes: ['image', 'html', 'text', 'video', 'audio', 'flash', 'pdf', 'object'],
  757. previewTemplates: {},
  758. previewSettings: {
  759. image: {width: "auto", height: "auto", 'max-width': "100%", 'max-height': "100%"},
  760. html: {width: "213px", height: "160px"},
  761. text: {width: "213px", height: "160px"},
  762. office: {width: "213px", height: "160px"},
  763. video: {width: "213px", height: "160px"},
  764. audio: {width: "100%", height: "30px"},
  765. flash: {width: "213px", height: "160px"},
  766. object: {width: "213px", height: "160px"},
  767. pdf: {width: "213px", height: "160px"},
  768. other: {width: "213px", height: "160px"}
  769. },
  770. previewSettingsSmall: {
  771. image: {width: "auto", height: "auto", 'max-width': "100%", 'max-height': "100%"},
  772. html: {width: "100%", height: "160px"},
  773. text: {width: "100%", height: "160px"},
  774. office: {width: "100%", height: "160px"},
  775. video: {width: "100%", height: "auto"},
  776. audio: {width: "100%", height: "30px"},
  777. flash: {width: "100%", height: "auto"},
  778. object: {width: "100%", height: "auto"},
  779. pdf: {width: "100%", height: "160px"},
  780. other: {width: "100%", height: "160px"}
  781. },
  782. previewZoomSettings: {
  783. image: {width: "auto", height: "auto", 'max-width': "100%", 'max-height': "100%"},
  784. html: vDefaultDim,
  785. text: vDefaultDim,
  786. office: {width: "100%", height: "100%", 'max-width': "100%", 'min-height': "480px"},
  787. video: {width: "auto", height: "100%", 'max-width': "100%"},
  788. audio: {width: "100%", height: "30px"},
  789. flash: {width: "auto", height: "480px"},
  790. object: {width: "auto", height: "100%", 'max-width': "100%", 'min-height': "480px"},
  791. pdf: vDefaultDim,
  792. other: {width: "auto", height: "100%", 'min-height': "480px"}
  793. },
  794. fileTypeSettings: {
  795. image: function (vType, vName) {
  796. return ($h.compare(vType, 'image.*') && !$h.compare(vType, /(tiff?|wmf)$/i) ||
  797. $h.compare(vName, /\.(gif|png|jpe?g)$/i)) ;
  798. },
  799. html: function (vType, vName) {
  800. return $h.compare(vType, 'text/html') || $h.compare(vName, /\.(htm|html)$/i);
  801. },
  802. office: function (vType, vName) {
  803. return $h.compare(vType, /(word|excel|powerpoint|office|iwork-pages|tiff?)$/i) ||
  804. $h.compare(vName, /\.(rtf|docx?|xlsx?|pptx?|pps|potx?|ods|odt|pages|ai|dxf|ttf|tiff?|wmf|e?ps)$/i);
  805. },
  806. text: function (vType, vName) {
  807. return $h.compare(vType, 'text.*') || $h.compare(vName, /\.(xml|javascript)$/i) ||
  808. $h.compare(vName, /\.(txt|md|csv|nfo|ini|json|php|js|css)$/i);
  809. },
  810. video: function (vType, vName) {
  811. return $h.compare(vType, 'video.*') && ($h.compare(vType, /(ogg|mp4|mp?g|mov|webm|3gp)$/i) ||
  812. $h.compare(vName, /\.(og?|mp4|webm|mp?g|mov|3gp)$/i));
  813. },
  814. audio: function (vType, vName) {
  815. return $h.compare(vType, 'audio.*') && ($h.compare(vName, /(ogg|mp3|mp?g|wav)$/i) ||
  816. $h.compare(vName, /\.(og?|mp3|mp?g|wav)$/i));
  817. },
  818. flash: function (vType, vName) {
  819. return $h.compare(vType, 'application/x-shockwave-flash', true) || $h.compare(vName, /\.(swf)$/i);
  820. },
  821. pdf: function (vType, vName) {
  822. return $h.compare(vType, 'application/pdf', true) || $h.compare(vName, /\.(pdf)$/i);
  823. },
  824. object: function () {
  825. return true;
  826. },
  827. other: function () {
  828. return true;
  829. }
  830. },
  831. fileActionSettings: {
  832. showRemove: true,
  833. showUpload: true,
  834. showDownload: true,
  835. showZoom: true,
  836. showDrag: true,
  837. removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
  838. removeClass: 'btn btn-kv btn-default btn-outline-secondary',
  839. removeErrorClass: 'btn btn-kv btn-danger',
  840. removeTitle: 'Remove file',
  841. uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
  842. uploadClass: 'btn btn-kv btn-default btn-outline-secondary',
  843. uploadTitle: 'Upload file',
  844. uploadRetryIcon: '<i class="glyphicon glyphicon-repeat"></i>',
  845. uploadRetryTitle: 'Retry upload',
  846. downloadIcon: '<i class="glyphicon glyphicon-download"></i>',
  847. downloadClass: 'btn btn-kv btn-default btn-outline-secondary',
  848. downloadTitle: 'Download file',
  849. zoomIcon: '<i class="glyphicon glyphicon-zoom-in"></i>',
  850. zoomClass: 'btn btn-kv btn-default btn-outline-secondary',
  851. zoomTitle: 'View Details',
  852. dragIcon: '<i class="glyphicon glyphicon-move"></i>',
  853. dragClass: 'text-info',
  854. dragTitle: 'Move / Rearrange',
  855. dragSettings: {},
  856. indicatorNew: '<i class="glyphicon glyphicon-plus-sign text-warning"></i>',
  857. indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign text-success"></i>',
  858. indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>',
  859. indicatorLoading: '<i class="glyphicon glyphicon-hourglass text-muted"></i>',
  860. indicatorNewTitle: 'Not uploaded yet',
  861. indicatorSuccessTitle: 'Uploaded',
  862. indicatorErrorTitle: 'Upload Error',
  863. indicatorLoadingTitle: 'Uploading ...'
  864. }
  865. };
  866. $.each(self.defaults, function (key, setting) {
  867. if (key === 'allowedPreviewTypes') {
  868. if (self.allowedPreviewTypes === undefined) {
  869. self.allowedPreviewTypes = setting;
  870. }
  871. return;
  872. }
  873. self[key] = $.extend(true, {}, setting, self[key]);
  874. });
  875. self._initPreviewTemplates();
  876. },
  877. _initPreviewTemplates: function () {
  878. var self = this, cfg = self.defaults, tags = self.previewMarkupTags, tagBef, tagAft = tags.tagAfter;
  879. $.each(cfg.previewContentTemplates, function (key, value) {
  880. if ($h.isEmpty(self.previewTemplates[key])) {
  881. tagBef = tags.tagBefore2;
  882. if (key === 'generic' || key === 'image' || key === 'html' || key === 'text') {
  883. tagBef = tags.tagBefore1;
  884. }
  885. self.previewTemplates[key] = tagBef + value + tagAft;
  886. }
  887. });
  888. },
  889. _initPreviewCache: function () {
  890. var self = this;
  891. self.previewCache = {
  892. data: {},
  893. init: function () {
  894. var content = self.initialPreview;
  895. if (content.length > 0 && !$h.isArray(content)) {
  896. content = content.split(self.initialPreviewDelimiter);
  897. }
  898. self.previewCache.data = {
  899. content: content,
  900. config: self.initialPreviewConfig,
  901. tags: self.initialPreviewThumbTags
  902. };
  903. },
  904. count: function () {
  905. return !!self.previewCache.data && !!self.previewCache.data.content ?
  906. self.previewCache.data.content.length : 0;
  907. },
  908. get: function (i, isDisabled) {
  909. var ind = 'init_' + i, data = self.previewCache.data, config = data.config[i],
  910. content = data.content[i], previewId = self.previewInitId + '-' + ind, out, $tmp, cat, ftr,
  911. fname, ftype, frameClass, asData = $h.ifSet('previewAsData', config, self.initialPreviewAsData),
  912. parseTemplate = function (cat, dat, fn, ft, id, ftr, ind, fc, t) {
  913. fc = ' file-preview-initial ' + $h.SORT_CSS + (fc ? ' ' + fc : '');
  914. return self._generatePreviewTemplate(cat, dat, fn, ft, id, false, null, fc, ftr, ind, t);
  915. };
  916. if (!content) {
  917. return '';
  918. }
  919. isDisabled = isDisabled === undefined ? true : isDisabled;
  920. cat = $h.ifSet('type', config, self.initialPreviewFileType || 'generic');
  921. fname = $h.ifSet('filename', config, $h.ifSet('caption', config));
  922. ftype = $h.ifSet('filetype', config, cat);
  923. ftr = self.previewCache.footer(i, isDisabled, (config && config.size || null));
  924. frameClass = $h.ifSet('frameClass', config);
  925. if (asData) {
  926. out = parseTemplate(cat, content, fname, ftype, previewId, ftr, ind, frameClass);
  927. } else {
  928. out = parseTemplate('generic', content, fname, ftype, previewId, ftr, ind, frameClass, cat)
  929. .setTokens({'content': data.content[i]});
  930. }
  931. if (data.tags.length && data.tags[i]) {
  932. out = $h.replaceTags(out, data.tags[i]);
  933. }
  934. /** @namespace config.frameAttr */
  935. if (!$h.isEmpty(config) && !$h.isEmpty(config.frameAttr)) {
  936. $tmp = $(document.createElement('div')).html(out);
  937. $tmp.find('.file-preview-initial').attr(config.frameAttr);
  938. out = $tmp.html();
  939. $tmp.remove();
  940. }
  941. return out;
  942. },
  943. add: function (content, config, tags, append) {
  944. var data = self.previewCache.data, index;
  945. if (!$h.isArray(content)) {
  946. content = content.split(self.initialPreviewDelimiter);
  947. }
  948. if (append) {
  949. index = data.content.push(content) - 1;
  950. data.config[index] = config;
  951. data.tags[index] = tags;
  952. } else {
  953. index = content.length - 1;
  954. data.content = content;
  955. data.config = config;
  956. data.tags = tags;
  957. }
  958. self.previewCache.data = data;
  959. return index;
  960. },
  961. set: function (content, config, tags, append) {
  962. var data = self.previewCache.data, i, chk;
  963. if (!content || !content.length) {
  964. return;
  965. }
  966. if (!$h.isArray(content)) {
  967. content = content.split(self.initialPreviewDelimiter);
  968. }
  969. chk = content.filter(function (n) {
  970. return n !== null;
  971. });
  972. if (!chk.length) {
  973. return;
  974. }
  975. if (data.content === undefined) {
  976. data.content = [];
  977. }
  978. if (data.config === undefined) {
  979. data.config = [];
  980. }
  981. if (data.tags === undefined) {
  982. data.tags = [];
  983. }
  984. if (append) {
  985. for (i = 0; i < content.length; i++) {
  986. if (content[i]) {
  987. data.content.push(content[i]);
  988. }
  989. }
  990. for (i = 0; i < config.length; i++) {
  991. if (config[i]) {
  992. data.config.push(config[i]);
  993. }
  994. }
  995. for (i = 0; i < tags.length; i++) {
  996. if (tags[i]) {
  997. data.tags.push(tags[i]);
  998. }
  999. }
  1000. } else {
  1001. data.content = content;
  1002. data.config = config;
  1003. data.tags = tags;
  1004. }
  1005. self.previewCache.data = data;
  1006. },
  1007. unset: function (index) {
  1008. var chk = self.previewCache.count();
  1009. if (!chk) {
  1010. return;
  1011. }
  1012. if (chk === 1) {
  1013. self.previewCache.data.content = [];
  1014. self.previewCache.data.config = [];
  1015. self.previewCache.data.tags = [];
  1016. self.initialPreview = [];
  1017. self.initialPreviewConfig = [];
  1018. self.initialPreviewThumbTags = [];
  1019. return;
  1020. }
  1021. self.previewCache.data.content.splice(index, 1);
  1022. self.previewCache.data.config.splice(index, 1);
  1023. self.previewCache.data.tags.splice(index, 1);
  1024. },
  1025. out: function () {
  1026. var html = '', caption, len = self.previewCache.count(), i;
  1027. if (len === 0) {
  1028. return {content: '', caption: ''};
  1029. }
  1030. for (i = 0; i < len; i++) {
  1031. html += self.previewCache.get(i);
  1032. }
  1033. caption = self._getMsgSelected(len);
  1034. return {content: html, caption: caption};
  1035. },
  1036. footer: function (i, isDisabled, size) {
  1037. var data = self.previewCache.data || {};
  1038. if ($h.isEmpty(data.content)) {
  1039. return '';
  1040. }
  1041. if ($h.isEmpty(data.config) || $h.isEmpty(data.config[i])) {
  1042. data.config[i] = {};
  1043. }
  1044. isDisabled = isDisabled === undefined ? true : isDisabled;
  1045. var config = data.config[i], caption = $h.ifSet('caption', config), a,
  1046. width = $h.ifSet('width', config, 'auto'), url = $h.ifSet('url', config, false),
  1047. key = $h.ifSet('key', config, null), fs = self.fileActionSettings,
  1048. initPreviewShowDel = self.initialPreviewShowDelete || false,
  1049. dUrl = config.downloadUrl || self.initialPreviewDownloadUrl || '',
  1050. dFil = config.filename || config.caption || '',
  1051. initPreviewShowDwl = !!(dUrl),
  1052. sDel = $h.ifSet('showDelete', config, $h.ifSet('showDelete', fs, initPreviewShowDel)),
  1053. sDwl = $h.ifSet('showDownload', config, $h.ifSet('showDownload', fs, initPreviewShowDwl)),
  1054. sZm = $h.ifSet('showZoom', config, $h.ifSet('showZoom', fs, true)),
  1055. sDrg = $h.ifSet('showDrag', config, $h.ifSet('showDrag', fs, true)),
  1056. dis = (url === false) && isDisabled;
  1057. sDwl = sDwl && config.downloadUrl !== false && !!dUrl;
  1058. a = self._renderFileActions(false, sDwl, sDel, sZm, sDrg, dis, url, key, true, dUrl, dFil);
  1059. return self._getLayoutTemplate('footer').setTokens({
  1060. 'progress': self._renderThumbProgress(),
  1061. 'actions': a,
  1062. 'caption': caption,
  1063. 'size': self._getSize(size),
  1064. 'width': width,
  1065. 'indicator': ''
  1066. });
  1067. }
  1068. };
  1069. self.previewCache.init();
  1070. },
  1071. _handler: function ($el, event, callback) {
  1072. var self = this, ns = self.namespace, ev = event.split(' ').join(ns + ' ') + ns;
  1073. if (!$el || !$el.length) {
  1074. return;
  1075. }
  1076. $el.off(ev).on(ev, callback);
  1077. },
  1078. _log: function (msg) {
  1079. var self = this, id = self.$element.attr('id');
  1080. if (id) {
  1081. msg = '"' + id + '": ' + msg;
  1082. }
  1083. if (typeof window.console.log !== "undefined") {
  1084. window.console.log(msg);
  1085. } else {
  1086. window.alert(msg);
  1087. }
  1088. },
  1089. _validate: function () {
  1090. var self = this, status = self.$element.attr('type') === 'file';
  1091. if (!status) {
  1092. self._log('The input "type" must be set to "file" for initializing the "bootstrap-fileinput" plugin.');
  1093. }
  1094. return status;
  1095. },
  1096. _errorsExist: function () {
  1097. var self = this, $err, $errList = self.$errorContainer.find('li');
  1098. if ($errList.length) {
  1099. return true;
  1100. }
  1101. $err = $(document.createElement('div')).html(self.$errorContainer.html());
  1102. $err.find('.kv-error-close').remove();
  1103. $err.find('ul').remove();
  1104. return !!$.trim($err.text()).length;
  1105. },
  1106. _errorHandler: function (evt, caption) {
  1107. var self = this, err = evt.target.error, showError = function (msg) {
  1108. self._showError(msg.replace('{name}', caption));
  1109. };
  1110. /** @namespace err.NOT_FOUND_ERR */
  1111. /** @namespace err.SECURITY_ERR */
  1112. /** @namespace err.NOT_READABLE_ERR */
  1113. if (err.code === err.NOT_FOUND_ERR) {
  1114. showError(self.msgFileNotFound);
  1115. } else if (err.code === err.SECURITY_ERR) {
  1116. showError(self.msgFileSecured);
  1117. } else if (err.code === err.NOT_READABLE_ERR) {
  1118. showError(self.msgFileNotReadable);
  1119. } else if (err.code === err.ABORT_ERR) {
  1120. showError(self.msgFilePreviewAborted);
  1121. } else {
  1122. showError(self.msgFilePreviewError);
  1123. }
  1124. },
  1125. _addError: function (msg) {
  1126. var self = this, $error = self.$errorContainer;
  1127. if (msg && $error.length) {
  1128. $error.html(self.errorCloseButton + msg);
  1129. self._handler($error.find('.kv-error-close'), 'click', function () {
  1130. $error.fadeOut('slow');
  1131. });
  1132. }
  1133. },
  1134. _setValidationError: function (css) {
  1135. var self = this;
  1136. css = (css ? css + ' ' : '') + 'has-error';
  1137. self.$container.removeClass(css).addClass('has-error');
  1138. $h.addCss(self.$captionContainer, 'is-invalid');
  1139. },
  1140. _resetErrors: function (fade) {
  1141. var self = this, $error = self.$errorContainer;
  1142. self.isError = false;
  1143. self.$container.removeClass('has-error');
  1144. self.$captionContainer.removeClass('is-invalid');
  1145. $error.html('');
  1146. if (fade) {
  1147. $error.fadeOut('slow');
  1148. } else {
  1149. $error.hide();
  1150. }
  1151. },
  1152. _showFolderError: function (folders) {
  1153. var self = this, $error = self.$errorContainer, msg;
  1154. if (!folders) {
  1155. return;
  1156. }
  1157. msg = self.msgFoldersNotAllowed.replace('{n}', folders);
  1158. self._addError(msg);
  1159. self._setValidationError();
  1160. $error.fadeIn(800);
  1161. self._raise('filefoldererror', [folders, msg]);
  1162. },
  1163. _showUploadError: function (msg, params, event) {
  1164. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror', e = params && params.id ?
  1165. '<li data-file-id="' + params.id + '">' + msg + '</li>' : '<li>' + msg + '</li>';
  1166. if ($error.find('ul').length === 0) {
  1167. self._addError('<ul>' + e + '</ul>');
  1168. } else {
  1169. $error.find('ul').append(e);
  1170. }
  1171. $error.fadeIn(800);
  1172. self._raise(ev, [params, msg]);
  1173. self._setValidationError('file-input-new');
  1174. return true;
  1175. },
  1176. _showError: function (msg, params, event) {
  1177. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  1178. params = params || {};
  1179. params.reader = self.reader;
  1180. self._addError(msg);
  1181. $error.fadeIn(800);
  1182. self._raise(ev, [params, msg]);
  1183. if (!self.isAjaxUpload) {
  1184. self._clearFileInput();
  1185. }
  1186. self._setValidationError('file-input-new');
  1187. self.$btnUpload.attr('disabled', true);
  1188. return true;
  1189. },
  1190. _noFilesError: function (params) {
  1191. var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle,
  1192. msg = self.msgFilesTooLess.replace('{n}', self.minFileCount).replace('{files}', label),
  1193. $error = self.$errorContainer;
  1194. self._addError(msg);
  1195. self.isError = true;
  1196. self._updateFileDetails(0);
  1197. $error.fadeIn(800);
  1198. self._raise('fileerror', [params, msg]);
  1199. self._clearFileInput();
  1200. self._setValidationError();
  1201. },
  1202. _parseError: function (operation, jqXHR, errorThrown, fileName) {
  1203. /** @namespace jqXHR.responseJSON */
  1204. var self = this, errMsg = $.trim(errorThrown + ''), textPre,
  1205. text = jqXHR.responseJSON !== undefined && jqXHR.responseJSON.error !== undefined ?
  1206. jqXHR.responseJSON.error : jqXHR.responseText;
  1207. if (self.cancelling && self.msgUploadAborted) {
  1208. errMsg = self.msgUploadAborted;
  1209. }
  1210. if (self.showAjaxErrorDetails && text) {
  1211. text = $.trim(text.replace(/\n\s*\n/g, '\n'));
  1212. textPre = text.length ? '<pre>' + text + '</pre>' : '';
  1213. errMsg += errMsg ? textPre : text;
  1214. }
  1215. if (!errMsg) {
  1216. errMsg = self.msgAjaxError.replace('{operation}', operation);
  1217. }
  1218. self.cancelling = false;
  1219. return fileName ? '<b>' + fileName + ': </b>' + errMsg : errMsg;
  1220. },
  1221. _parseFileType: function (type, name) {
  1222. var self = this, isValid, vType, cat, i, types = self.allowedPreviewTypes || [];
  1223. if (type === 'application/text-plain') {
  1224. return 'text';
  1225. }
  1226. for (i = 0; i < types.length; i++) {
  1227. cat = types[i];
  1228. isValid = self.fileTypeSettings[cat];
  1229. vType = isValid(type, name) ? cat : '';
  1230. if (!$h.isEmpty(vType)) {
  1231. return vType;
  1232. }
  1233. }
  1234. return 'other';
  1235. },
  1236. _getPreviewIcon: function (fname) {
  1237. var self = this, ext, out = null;
  1238. if (fname && fname.indexOf('.') > -1) {
  1239. ext = fname.split('.').pop();
  1240. if (self.previewFileIconSettings) {
  1241. out = self.previewFileIconSettings[ext] || self.previewFileIconSettings[ext.toLowerCase()] || null;
  1242. }
  1243. if (self.previewFileExtSettings) {
  1244. $.each(self.previewFileExtSettings, function (key, func) {
  1245. if (self.previewFileIconSettings[key] && func(ext)) {
  1246. out = self.previewFileIconSettings[key];
  1247. //noinspection UnnecessaryReturnStatementJS
  1248. return;
  1249. }
  1250. });
  1251. }
  1252. }
  1253. return out;
  1254. },
  1255. _parseFilePreviewIcon: function (content, fname) {
  1256. var self = this, icn = self._getPreviewIcon(fname) || self.previewFileIcon, out = content;
  1257. if (out.indexOf('{previewFileIcon}') > -1) {
  1258. out = out.setTokens({'previewFileIconClass': self.previewFileIconClass, 'previewFileIcon': icn});
  1259. }
  1260. return out;
  1261. },
  1262. _raise: function (event, params) {
  1263. var self = this, e = $.Event(event);
  1264. if (params !== undefined) {
  1265. self.$element.trigger(e, params);
  1266. } else {
  1267. self.$element.trigger(e);
  1268. }
  1269. if (e.isDefaultPrevented() || e.result === false) {
  1270. return false;
  1271. }
  1272. switch (event) {
  1273. // ignore these events
  1274. case 'filebatchuploadcomplete':
  1275. case 'filebatchuploadsuccess':
  1276. case 'fileuploaded':
  1277. case 'fileclear':
  1278. case 'filecleared':
  1279. case 'filereset':
  1280. case 'fileerror':
  1281. case 'filefoldererror':
  1282. case 'fileuploaderror':
  1283. case 'filebatchuploaderror':
  1284. case 'filedeleteerror':
  1285. case 'filecustomerror':
  1286. case 'filesuccessremove':
  1287. break;
  1288. // receive data response via `filecustomerror` event`
  1289. default:
  1290. if (!self.ajaxAborted) {
  1291. self.ajaxAborted = e.result;
  1292. }
  1293. break;
  1294. }
  1295. return true;
  1296. },
  1297. _listenFullScreen: function (isFullScreen) {
  1298. var self = this, $modal = self.$modal, $btnFull, $btnBord;
  1299. if (!$modal || !$modal.length) {
  1300. return;
  1301. }
  1302. $btnFull = $modal && $modal.find('.btn-fullscreen');
  1303. $btnBord = $modal && $modal.find('.btn-borderless');
  1304. if (!$btnFull.length || !$btnBord.length) {
  1305. return;
  1306. }
  1307. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  1308. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1309. if (isFullScreen) {
  1310. $btnFull.addClass('active').attr('aria-pressed', 'true');
  1311. } else {
  1312. $btnBord.addClass('active').attr('aria-pressed', 'true');
  1313. }
  1314. if ($modal.hasClass('file-zoom-fullscreen')) {
  1315. self._maximizeZoomDialog();
  1316. } else {
  1317. if (isFullScreen) {
  1318. self._maximizeZoomDialog();
  1319. } else {
  1320. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1321. }
  1322. }
  1323. },
  1324. _listen: function () {
  1325. var self = this, $el = self.$element, $form = self.$form, $cont = self.$container, fullScreenEvents;
  1326. self._handler($el, 'change', $.proxy(self._change, self));
  1327. if (self.showBrowse) {
  1328. self._handler(self.$btnFile, 'click', $.proxy(self._browse, self));
  1329. }
  1330. self._handler($cont.find('.fileinput-remove:not([disabled])'), 'click', $.proxy(self.clear, self));
  1331. self._handler($cont.find('.fileinput-cancel'), 'click', $.proxy(self.cancel, self));
  1332. self._initDragDrop();
  1333. self._handler($form, 'reset', $.proxy(self.clear, self));
  1334. if (!self.isAjaxUpload) {
  1335. self._handler($form, 'submit', $.proxy(self._submitForm, self));
  1336. }
  1337. self._handler(self.$container.find('.fileinput-upload'), 'click', $.proxy(self._uploadClick, self));
  1338. self._handler($(window), 'resize', function () {
  1339. self._listenFullScreen(screen.width === window.innerWidth && screen.height === window.innerHeight);
  1340. });
  1341. fullScreenEvents = 'webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange';
  1342. self._handler($(document), fullScreenEvents, function () {
  1343. self._listenFullScreen($h.checkFullScreen());
  1344. });
  1345. self._autoFitContent();
  1346. self._initClickable();
  1347. },
  1348. _autoFitContent: function () {
  1349. var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
  1350. self = this, config = width < 400 ? (self.previewSettingsSmall || self.defaults.previewSettingsSmall) :
  1351. (self.previewSettings || self.defaults.previewSettings), sel;
  1352. $.each(config, function (cat, settings) {
  1353. sel = '.file-preview-frame .file-preview-' + cat;
  1354. self.$preview.find(sel + '.kv-preview-data,' + sel + ' .kv-preview-data').css(settings);
  1355. });
  1356. },
  1357. _initClickable: function () {
  1358. var self = this, $zone;
  1359. if (!self.isClickable) {
  1360. return;
  1361. }
  1362. $zone = self.isAjaxUpload ? self.$dropZone : self.$preview.find('.file-default-preview');
  1363. $h.addCss($zone, 'clickable');
  1364. $zone.attr('tabindex', -1);
  1365. self._handler($zone, 'click', function (e) {
  1366. var $tar = $(e.target);
  1367. if (!$tar.parents('.file-preview-thumbnails').length || $tar.parents('.file-default-preview').length) {
  1368. self.$element.trigger('click');
  1369. $zone.blur();
  1370. }
  1371. });
  1372. },
  1373. _initDragDrop: function () {
  1374. var self = this, $zone = self.$dropZone;
  1375. if (self.isAjaxUpload && self.dropZoneEnabled && self.showPreview) {
  1376. self._handler($zone, 'dragenter dragover', $.proxy(self._zoneDragEnter, self));
  1377. self._handler($zone, 'dragleave', $.proxy(self._zoneDragLeave, self));
  1378. self._handler($zone, 'drop', $.proxy(self._zoneDrop, self));
  1379. self._handler($(document), 'dragenter dragover drop', self._zoneDragDropInit);
  1380. }
  1381. },
  1382. _zoneDragDropInit: function (e) {
  1383. e.stopPropagation();
  1384. e.preventDefault();
  1385. },
  1386. _zoneDragEnter: function (e) {
  1387. var self = this, hasFiles = $.inArray('Files', e.originalEvent.dataTransfer.types) > -1;
  1388. self._zoneDragDropInit(e);
  1389. if (self.isDisabled || !hasFiles) {
  1390. e.originalEvent.dataTransfer.effectAllowed = 'none';
  1391. e.originalEvent.dataTransfer.dropEffect = 'none';
  1392. return;
  1393. }
  1394. $h.addCss(self.$dropZone, 'file-highlighted');
  1395. },
  1396. _zoneDragLeave: function (e) {
  1397. var self = this;
  1398. self._zoneDragDropInit(e);
  1399. if (self.isDisabled) {
  1400. return;
  1401. }
  1402. self.$dropZone.removeClass('file-highlighted');
  1403. },
  1404. _zoneDrop: function (e) {
  1405. var self = this;
  1406. e.preventDefault();
  1407. /** @namespace e.originalEvent.dataTransfer */
  1408. if (self.isDisabled || $h.isEmpty(e.originalEvent.dataTransfer.files)) {
  1409. return;
  1410. }
  1411. self._change(e, 'dragdrop');
  1412. self.$dropZone.removeClass('file-highlighted');
  1413. },
  1414. _uploadClick: function (e) {
  1415. var self = this, $btn = self.$container.find('.fileinput-upload'), $form,
  1416. isEnabled = !$btn.hasClass('disabled') && $h.isEmpty($btn.attr('disabled'));
  1417. if (e && e.isDefaultPrevented()) {
  1418. return;
  1419. }
  1420. if (!self.isAjaxUpload) {
  1421. if (isEnabled && $btn.attr('type') !== 'submit') {
  1422. $form = $btn.closest('form');
  1423. // downgrade to normal form submit if possible
  1424. if ($form.length) {
  1425. $form.trigger('submit');
  1426. }
  1427. e.preventDefault();
  1428. }
  1429. return;
  1430. }
  1431. e.preventDefault();
  1432. if (isEnabled) {
  1433. self.upload();
  1434. }
  1435. },
  1436. _submitForm: function () {
  1437. var self = this;
  1438. return self._isFileSelectionValid() && !self._abort({});
  1439. },
  1440. _clearPreview: function () {
  1441. var self = this, $p = self.$preview,
  1442. $thumbs = self.showUploadedThumbs ? self.getFrames(':not(.file-preview-success)') : self.getFrames();
  1443. $thumbs.each(function () {
  1444. var $thumb = $(this);
  1445. $thumb.remove();
  1446. $h.cleanZoomCache($p.find('#zoom-' + $thumb.attr('id')));
  1447. });
  1448. if (!self.getFrames().length || !self.showPreview) {
  1449. self._resetUpload();
  1450. }
  1451. self._validateDefaultPreview();
  1452. },
  1453. _initSortable: function () {
  1454. var self = this, $el = self.$preview, settings, selector = '.' + $h.SORT_CSS;
  1455. if (!window.KvSortable || $el.find(selector).length === 0) {
  1456. return;
  1457. }
  1458. //noinspection JSUnusedGlobalSymbols
  1459. settings = {
  1460. handle: '.drag-handle-init',
  1461. dataIdAttr: 'data-preview-id',
  1462. scroll: false,
  1463. draggable: selector,
  1464. onSort: function (e) {
  1465. var oldIndex = e.oldIndex, newIndex = e.newIndex, $frame, $dragEl;
  1466. self.initialPreview = $h.moveArray(self.initialPreview, oldIndex, newIndex);
  1467. self.initialPreviewConfig = $h.moveArray(self.initialPreviewConfig, oldIndex, newIndex);
  1468. self.previewCache.init();
  1469. for (var i = 0; i < self.initialPreviewConfig.length; i++) {
  1470. if (self.initialPreviewConfig[i] !== null) {
  1471. $dragEl = $(e.item);
  1472. $frame = $dragEl.closest($h.FRAMES);
  1473. $frame.attr('data-fileindex', 'init_' + i).attr('data-fileindex', 'init_' + i);
  1474. }
  1475. }
  1476. self._raise('filesorted', {
  1477. previewId: $(e.item).attr('id'),
  1478. 'oldIndex': oldIndex,
  1479. 'newIndex': newIndex,
  1480. stack: self.initialPreviewConfig
  1481. });
  1482. }
  1483. };
  1484. if ($el.data('kvsortable')) {
  1485. $el.kvsortable('destroy');
  1486. }
  1487. $.extend(true, settings, self.fileActionSettings.dragSettings);
  1488. $el.kvsortable(settings);
  1489. },
  1490. _setPreviewContent: function (content) {
  1491. var self = this;
  1492. self.$preview.html(content);
  1493. self._autoFitContent();
  1494. },
  1495. _initPreview: function (isInit) {
  1496. var self = this, cap = self.initialCaption || '', out;
  1497. if (!self.previewCache.count()) {
  1498. self._clearPreview();
  1499. if (isInit) {
  1500. self._setCaption(cap);
  1501. } else {
  1502. self._initCaption();
  1503. }
  1504. return;
  1505. }
  1506. out = self.previewCache.out();
  1507. cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
  1508. self._setPreviewContent(out.content);
  1509. self._setInitThumbAttr();
  1510. self._setCaption(cap);
  1511. self._initSortable();
  1512. if (!$h.isEmpty(out.content)) {
  1513. self.$container.removeClass('file-input-new');
  1514. }
  1515. },
  1516. _getZoomButton: function (type) {
  1517. var self = this, label = self.previewZoomButtonIcons[type], css = self.previewZoomButtonClasses[type],
  1518. title = ' title="' + (self.previewZoomButtonTitles[type] || '') + '" ',
  1519. params = title + (type === 'close' ? ' data-dismiss="modal" aria-hidden="true"' : '');
  1520. if (type === 'fullscreen' || type === 'borderless' || type === 'toggleheader') {
  1521. params += ' data-toggle="button" aria-pressed="false" autocomplete="off"';
  1522. }
  1523. return '<button type="button" class="' + css + ' btn-' + type + '"' + params + '>' + label + '</button>';
  1524. },
  1525. _getModalContent: function () {
  1526. var self = this;
  1527. return self._getLayoutTemplate('modal').setTokens({
  1528. 'rtl': self.rtl ? ' kv-rtl' : '',
  1529. 'zoomFrameClass': self.frameClass,
  1530. 'heading': self.msgZoomModalHeading,
  1531. 'prev': self._getZoomButton('prev'),
  1532. 'next': self._getZoomButton('next'),
  1533. 'toggleheader': self._getZoomButton('toggleheader'),
  1534. 'fullscreen': self._getZoomButton('fullscreen'),
  1535. 'borderless': self._getZoomButton('borderless'),
  1536. 'close': self._getZoomButton('close')
  1537. });
  1538. },
  1539. _listenModalEvent: function (event) {
  1540. var self = this, $modal = self.$modal, getParams = function (e) {
  1541. return {
  1542. sourceEvent: e,
  1543. previewId: $modal.data('previewId'),
  1544. modal: $modal
  1545. };
  1546. };
  1547. $modal.on(event + '.bs.modal', function (e) {
  1548. var $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless');
  1549. self._raise('filezoom' + event, getParams(e));
  1550. if (event === 'shown') {
  1551. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1552. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  1553. if ($modal.hasClass('file-zoom-fullscreen')) {
  1554. self._maximizeZoomDialog();
  1555. if ($h.checkFullScreen()) {
  1556. $btnFull.addClass('active').attr('aria-pressed', 'true');
  1557. } else {
  1558. $btnBord.addClass('active').attr('aria-pressed', 'true');
  1559. }
  1560. }
  1561. }
  1562. });
  1563. },
  1564. _initZoom: function () {
  1565. var self = this, $dialog, modalMain = self._getLayoutTemplate('modalMain'), modalId = '#' + $h.MODAL_ID;
  1566. if (!self.showPreview) {
  1567. return;
  1568. }
  1569. self.$modal = $(modalId);
  1570. if (!self.$modal || !self.$modal.length) {
  1571. $dialog = $(document.createElement('div')).html(modalMain).insertAfter(self.$container);
  1572. self.$modal = $(modalId).insertBefore($dialog);
  1573. $dialog.remove();
  1574. }
  1575. $h.initModal(self.$modal);
  1576. self.$modal.html(self._getModalContent());
  1577. $.each($h.MODAL_EVENTS, function (key, event) {
  1578. self._listenModalEvent(event);
  1579. });
  1580. },
  1581. _initZoomButtons: function () {
  1582. var self = this, previewId = self.$modal.data('previewId') || '', $first, $last,
  1583. thumbs = self.getFrames().toArray(), len = thumbs.length, $prev = self.$modal.find('.btn-prev'),
  1584. $next = self.$modal.find('.btn-next');
  1585. if (thumbs.length < 2) {
  1586. $prev.hide();
  1587. $next.hide();
  1588. return;
  1589. } else {
  1590. $prev.show();
  1591. $next.show();
  1592. }
  1593. if (!len) {
  1594. return;
  1595. }
  1596. $first = $(thumbs[0]);
  1597. $last = $(thumbs[len - 1]);
  1598. $prev.removeAttr('disabled');
  1599. $next.removeAttr('disabled');
  1600. if ($first.length && $first.attr('id') === previewId) {
  1601. $prev.attr('disabled', true);
  1602. }
  1603. if ($last.length && $last.attr('id') === previewId) {
  1604. $next.attr('disabled', true);
  1605. }
  1606. },
  1607. _maximizeZoomDialog: function () {
  1608. var self = this, $modal = self.$modal, $head = $modal.find('.modal-header:visible'),
  1609. $foot = $modal.find('.modal-footer:visible'), $body = $modal.find('.modal-body'),
  1610. h = $(window).height(), diff = 0;
  1611. $modal.addClass('file-zoom-fullscreen');
  1612. if ($head && $head.length) {
  1613. h -= $head.outerHeight(true);
  1614. }
  1615. if ($foot && $foot.length) {
  1616. h -= $foot.outerHeight(true);
  1617. }
  1618. if ($body && $body.length) {
  1619. diff = $body.outerHeight(true) - $body.height();
  1620. h -= diff;
  1621. }
  1622. $modal.find('.kv-zoom-body').height(h);
  1623. },
  1624. _resizeZoomDialog: function (fullScreen) {
  1625. var self = this, $modal = self.$modal, $btnFull = $modal.find('.btn-fullscreen'),
  1626. $btnBord = $modal.find('.btn-borderless');
  1627. if ($modal.hasClass('file-zoom-fullscreen')) {
  1628. $h.toggleFullScreen(false);
  1629. if (!fullScreen) {
  1630. if (!$btnFull.hasClass('active')) {
  1631. $modal.removeClass('file-zoom-fullscreen');
  1632. self.$modal.find('.kv-zoom-body').css('height', self.zoomModalHeight);
  1633. } else {
  1634. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  1635. }
  1636. } else {
  1637. if (!$btnFull.hasClass('active')) {
  1638. $modal.removeClass('file-zoom-fullscreen');
  1639. self._resizeZoomDialog(true);
  1640. if ($btnBord.hasClass('active')) {
  1641. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  1642. }
  1643. }
  1644. }
  1645. } else {
  1646. if (!fullScreen) {
  1647. self._maximizeZoomDialog();
  1648. return;
  1649. }
  1650. $h.toggleFullScreen(true);
  1651. }
  1652. $modal.focus();
  1653. },
  1654. _setZoomContent: function ($frame, animate) {
  1655. var self = this, $content, tmplt, body, title, $body, $dataEl, config, pid = $frame.attr('id'),
  1656. $modal = self.$modal, $prev = $modal.find('.btn-prev'), $next = $modal.find('.btn-next'), $tmp,
  1657. $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless'), cap, size,
  1658. $btnTogh = $modal.find('.btn-toggleheader'), $zoomPreview = self.$preview.find('#zoom-' + pid);
  1659. tmplt = $zoomPreview.attr('data-template') || 'generic';
  1660. $content = $zoomPreview.find('.kv-file-content');
  1661. body = $content.length ? $content.html() : '';
  1662. cap = $frame.data('caption') || '';
  1663. size = $frame.data('size') || '';
  1664. title = cap + ' ' + size;
  1665. $modal.find('.kv-zoom-title').attr('title', $('<div/>').html(title).text()).html(title);
  1666. $body = $modal.find('.kv-zoom-body');
  1667. $modal.removeClass('kv-single-content');
  1668. if (animate) {
  1669. $tmp = $body.addClass('file-thumb-loading').clone().insertAfter($body);
  1670. $body.html(body).hide();
  1671. $tmp.fadeOut('fast', function () {
  1672. $body.fadeIn('fast', function () {
  1673. $body.removeClass('file-thumb-loading');
  1674. });
  1675. $tmp.remove();
  1676. });
  1677. } else {
  1678. $body.html(body);
  1679. }
  1680. config = self.previewZoomSettings[tmplt];
  1681. if (config) {
  1682. $dataEl = $body.find('.kv-preview-data');
  1683. $h.addCss($dataEl, 'file-zoom-detail');
  1684. $.each(config, function (key, value) {
  1685. $dataEl.css(key, value);
  1686. if (($dataEl.attr('width') && key === 'width') || ($dataEl.attr('height') && key === 'height')) {
  1687. $dataEl.removeAttr(key);
  1688. }
  1689. });
  1690. }
  1691. $modal.data('previewId', pid);
  1692. var $img = $body.find('img');
  1693. if ($img.length) {
  1694. $h.adjustOrientedImage($img, true);
  1695. }
  1696. self._handler($prev, 'click', function () {
  1697. self._zoomSlideShow('prev', pid);
  1698. });
  1699. self._handler($next, 'click', function () {
  1700. self._zoomSlideShow('next', pid);
  1701. });
  1702. self._handler($btnFull, 'click', function () {
  1703. self._resizeZoomDialog(true);
  1704. });
  1705. self._handler($btnBord, 'click', function () {
  1706. self._resizeZoomDialog(false);
  1707. });
  1708. self._handler($btnTogh, 'click', function () {
  1709. var $header = $modal.find('.modal-header'), $floatBar = $modal.find('.modal-body .floating-buttons'),
  1710. ht, $actions = $header.find('.kv-zoom-actions'), resize = function (height) {
  1711. var $body = self.$modal.find('.kv-zoom-body'), h = self.zoomModalHeight;
  1712. if ($modal.hasClass('file-zoom-fullscreen')) {
  1713. h = $body.outerHeight(true);
  1714. if (!height) {
  1715. h = h - $header.outerHeight(true);
  1716. }
  1717. }
  1718. $body.css('height', height ? h + height : h);
  1719. };
  1720. if ($header.is(':visible')) {
  1721. ht = $header.outerHeight(true);
  1722. $header.slideUp('slow', function () {
  1723. $actions.find('.btn').appendTo($floatBar);
  1724. resize(ht);
  1725. });
  1726. } else {
  1727. $floatBar.find('.btn').appendTo($actions);
  1728. $header.slideDown('slow', function () {
  1729. resize();
  1730. });
  1731. }
  1732. $modal.focus();
  1733. });
  1734. self._handler($modal, 'keydown', function (e) {
  1735. var key = e.which || e.keyCode;
  1736. if (key === 37 && !$prev.attr('disabled')) {
  1737. self._zoomSlideShow('prev', pid);
  1738. }
  1739. if (key === 39 && !$next.attr('disabled')) {
  1740. self._zoomSlideShow('next', pid);
  1741. }
  1742. });
  1743. },
  1744. _zoomPreview: function ($btn) {
  1745. var self = this, $frame, $modal = self.$modal;
  1746. if (!$btn.length) {
  1747. throw 'Cannot zoom to detailed preview!';
  1748. }
  1749. $h.initModal($modal);
  1750. $modal.html(self._getModalContent());
  1751. $frame = $btn.closest($h.FRAMES);
  1752. self._setZoomContent($frame);
  1753. $modal.modal('show');
  1754. self._initZoomButtons();
  1755. },
  1756. _zoomSlideShow: function (dir, previewId) {
  1757. var self = this, $btn = self.$modal.find('.kv-zoom-actions .btn-' + dir), $targFrame, i,
  1758. thumbs = self.getFrames().toArray(), len = thumbs.length, out;
  1759. if ($btn.attr('disabled')) {
  1760. return;
  1761. }
  1762. for (i = 0; i < len; i++) {
  1763. if ($(thumbs[i]).attr('id') === previewId) {
  1764. out = dir === 'prev' ? i - 1 : i + 1;
  1765. break;
  1766. }
  1767. }
  1768. if (out < 0 || out >= len || !thumbs[out]) {
  1769. return;
  1770. }
  1771. $targFrame = $(thumbs[out]);
  1772. if ($targFrame.length) {
  1773. self._setZoomContent($targFrame, true);
  1774. }
  1775. self._initZoomButtons();
  1776. self._raise('filezoom' + dir, {'previewId': previewId, modal: self.$modal});
  1777. },
  1778. _initZoomButton: function () {
  1779. var self = this;
  1780. self.$preview.find('.kv-file-zoom').each(function () {
  1781. var $el = $(this);
  1782. self._handler($el, 'click', function () {
  1783. self._zoomPreview($el);
  1784. });
  1785. });
  1786. },
  1787. _clearObjects: function ($el) {
  1788. $el.find('video audio').each(function () {
  1789. this.pause();
  1790. $(this).remove();
  1791. });
  1792. $el.find('img object div').each(function () {
  1793. $(this).remove();
  1794. });
  1795. },
  1796. _clearFileInput: function () {
  1797. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  1798. self.fileInputCleared = true;
  1799. if ($h.isEmpty($el.val())) {
  1800. return;
  1801. }
  1802. // Fix for IE ver < 11, that does not clear file inputs. Requires a sequence of steps to prevent IE
  1803. // crashing but still allow clearing of the file input.
  1804. if (self.isIE9 || self.isIE10) {
  1805. $srcFrm = $el.closest('form');
  1806. $tmpFrm = $(document.createElement('form'));
  1807. $tmpEl = $(document.createElement('div'));
  1808. $el.before($tmpEl);
  1809. if ($srcFrm.length) {
  1810. $srcFrm.after($tmpFrm);
  1811. } else {
  1812. $tmpEl.after($tmpFrm);
  1813. }
  1814. $tmpFrm.append($el).trigger('reset');
  1815. $tmpEl.before($el).remove();
  1816. $tmpFrm.remove();
  1817. } else { // normal input clear behavior for other sane browsers
  1818. $el.val('');
  1819. }
  1820. },
  1821. _resetUpload: function () {
  1822. var self = this;
  1823. self.uploadCache = {content: [], config: [], tags: [], append: true};
  1824. self.uploadCount = 0;
  1825. self.uploadStatus = {};
  1826. self.uploadLog = [];
  1827. self.uploadAsyncCount = 0;
  1828. self.loadedImages = [];
  1829. self.totalImagesCount = 0;
  1830. self.$btnUpload.removeAttr('disabled');
  1831. self._setProgress(0);
  1832. self.$progress.hide();
  1833. self._resetErrors(false);
  1834. self.ajaxAborted = false;
  1835. self.ajaxRequests = [];
  1836. self._resetCanvas();
  1837. self.cacheInitialPreview = {};
  1838. if (self.overwriteInitial) {
  1839. self.initialPreview = [];
  1840. self.initialPreviewConfig = [];
  1841. self.initialPreviewThumbTags = [];
  1842. self.previewCache.data = {
  1843. content: [],
  1844. config: [],
  1845. tags: []
  1846. };
  1847. }
  1848. },
  1849. _resetCanvas: function () {
  1850. var self = this;
  1851. if (self.canvas && self.imageCanvasContext) {
  1852. self.imageCanvasContext.clearRect(0, 0, self.canvas.width, self.canvas.height);
  1853. }
  1854. },
  1855. _hasInitialPreview: function () {
  1856. var self = this;
  1857. return !self.overwriteInitial && self.previewCache.count();
  1858. },
  1859. _resetPreview: function () {
  1860. var self = this, out, cap;
  1861. if (self.previewCache.count()) {
  1862. out = self.previewCache.out();
  1863. self._setPreviewContent(out.content);
  1864. self._setInitThumbAttr();
  1865. cap = self.initialCaption ? self.initialCaption : out.caption;
  1866. self._setCaption(cap);
  1867. } else {
  1868. self._clearPreview();
  1869. self._initCaption();
  1870. }
  1871. if (self.showPreview) {
  1872. self._initZoom();
  1873. self._initSortable();
  1874. }
  1875. },
  1876. _clearDefaultPreview: function () {
  1877. var self = this;
  1878. self.$preview.find('.file-default-preview').remove();
  1879. },
  1880. _validateDefaultPreview: function () {
  1881. var self = this;
  1882. if (!self.showPreview || $h.isEmpty(self.defaultPreviewContent)) {
  1883. return;
  1884. }
  1885. self._setPreviewContent('<div class="file-default-preview">' + self.defaultPreviewContent + '</div>');
  1886. self.$container.removeClass('file-input-new');
  1887. self._initClickable();
  1888. },
  1889. _resetPreviewThumbs: function (isAjax) {
  1890. var self = this, out;
  1891. if (isAjax) {
  1892. self._clearPreview();
  1893. self.clearStack();
  1894. return;
  1895. }
  1896. if (self._hasInitialPreview()) {
  1897. out = self.previewCache.out();
  1898. self._setPreviewContent(out.content);
  1899. self._setInitThumbAttr();
  1900. self._setCaption(out.caption);
  1901. self._initPreviewActions();
  1902. } else {
  1903. self._clearPreview();
  1904. }
  1905. },
  1906. _getLayoutTemplate: function (t) {
  1907. var self = this, template = self.layoutTemplates[t];
  1908. if ($h.isEmpty(self.customLayoutTags)) {
  1909. return template;
  1910. }
  1911. return $h.replaceTags(template, self.customLayoutTags);
  1912. },
  1913. _getPreviewTemplate: function (t) {
  1914. var self = this, template = self.previewTemplates[t];
  1915. if ($h.isEmpty(self.customPreviewTags)) {
  1916. return template;
  1917. }
  1918. return $h.replaceTags(template, self.customPreviewTags);
  1919. },
  1920. _getOutData: function (jqXHR, responseData, filesData) {
  1921. var self = this;
  1922. jqXHR = jqXHR || {};
  1923. responseData = responseData || {};
  1924. filesData = filesData || self.filestack.slice(0) || {};
  1925. return {
  1926. form: self.formdata,
  1927. files: filesData,
  1928. filenames: self.filenames,
  1929. filescount: self.getFilesCount(),
  1930. extra: self._getExtraData(),
  1931. response: responseData,
  1932. reader: self.reader,
  1933. jqXHR: jqXHR
  1934. };
  1935. },
  1936. _getMsgSelected: function (n) {
  1937. var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural;
  1938. return n > 0 ? self.msgSelected.replace('{n}', n).replace('{files}', strFiles) : self.msgNoFilesSelected;
  1939. },
  1940. _getFrame: function (id) {
  1941. var self = this, $frame = $('#' + id);
  1942. if (!$frame.length) {
  1943. self._log('Invalid thumb frame with id: "' + id + '".');
  1944. return null;
  1945. }
  1946. return $frame;
  1947. },
  1948. _getThumbs: function (css) {
  1949. css = css || '';
  1950. return this.getFrames(':not(.file-preview-initial)' + css);
  1951. },
  1952. _getExtraData: function (previewId, index) {
  1953. var self = this, data = self.uploadExtraData;
  1954. if (typeof self.uploadExtraData === "function") {
  1955. data = self.uploadExtraData(previewId, index);
  1956. }
  1957. return data;
  1958. },
  1959. _initXhr: function (xhrobj, previewId, fileCount) {
  1960. var self = this;
  1961. if (xhrobj.upload) {
  1962. xhrobj.upload.addEventListener('progress', function (event) {
  1963. var pct = 0, total = event.total, position = event.loaded || event.position;
  1964. /** @namespace event.lengthComputable */
  1965. if (event.lengthComputable) {
  1966. pct = Math.floor(position / total * 100);
  1967. }
  1968. if (previewId) {
  1969. self._setAsyncUploadStatus(previewId, pct, fileCount);
  1970. } else {
  1971. self._setProgress(pct);
  1972. }
  1973. }, false);
  1974. }
  1975. return xhrobj;
  1976. },
  1977. _mergeAjaxCallback: function (funcName, srcFunc, type) {
  1978. var self = this, settings = self.ajaxSettings, flag = self.mergeAjaxCallbacks, targFunc;
  1979. if (type === 'delete') {
  1980. settings = self.ajaxDeleteSettings;
  1981. flag = self.mergeAjaxDeleteCallbacks;
  1982. }
  1983. targFunc = settings[funcName];
  1984. if (flag && typeof targFunc === "function") {
  1985. if (flag === 'before') {
  1986. settings[funcName] = function () {
  1987. targFunc.apply(this, arguments);
  1988. srcFunc.apply(this, arguments);
  1989. };
  1990. } else {
  1991. settings[funcName] = function () {
  1992. srcFunc.apply(this, arguments);
  1993. targFunc.apply(this, arguments);
  1994. };
  1995. }
  1996. } else {
  1997. settings[funcName] = srcFunc;
  1998. }
  1999. if (type === 'delete') {
  2000. self.ajaxDeleteSettings = settings;
  2001. } else {
  2002. self.ajaxSettings = settings;
  2003. }
  2004. },
  2005. _ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, previewId, index) {
  2006. var self = this, settings;
  2007. if (!self._raise('filepreajax', [previewId, index])) {
  2008. return;
  2009. }
  2010. self._uploadExtra(previewId, index);
  2011. self._mergeAjaxCallback('beforeSend', fnBefore);
  2012. self._mergeAjaxCallback('success', fnSuccess);
  2013. self._mergeAjaxCallback('complete', fnComplete);
  2014. self._mergeAjaxCallback('error', fnError);
  2015. settings = $.extend(true, {}, {
  2016. xhr: function () {
  2017. var xhrobj = $.ajaxSettings.xhr();
  2018. return self._initXhr(xhrobj, previewId, self.getFileStack().length);
  2019. },
  2020. url: index && self.uploadUrlThumb ? self.uploadUrlThumb : self.uploadUrl,
  2021. type: 'POST',
  2022. dataType: 'json',
  2023. data: self.formdata,
  2024. cache: false,
  2025. processData: false,
  2026. contentType: false
  2027. }, self.ajaxSettings);
  2028. self.ajaxRequests.push($.ajax(settings));
  2029. },
  2030. _mergeArray: function (prop, content) {
  2031. var self = this, arr1 = $h.cleanArray(self[prop]), arr2 = $h.cleanArray(content);
  2032. self[prop] = arr1.concat(arr2);
  2033. },
  2034. _initUploadSuccess: function (out, $thumb, allFiles) {
  2035. var self = this, append, data, index, $div, $newCache, content, config, tags, i;
  2036. if (!self.showPreview || typeof out !== 'object' || $.isEmptyObject(out)) {
  2037. return;
  2038. }
  2039. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  2040. self.hasInitData = true;
  2041. content = out.initialPreview || [];
  2042. config = out.initialPreviewConfig || [];
  2043. tags = out.initialPreviewThumbTags || [];
  2044. append = out.append === undefined || out.append;
  2045. if (content.length > 0 && !$h.isArray(content)) {
  2046. content = content.split(self.initialPreviewDelimiter);
  2047. }
  2048. self._mergeArray('initialPreview', content);
  2049. self._mergeArray('initialPreviewConfig', config);
  2050. self._mergeArray('initialPreviewThumbTags', tags);
  2051. if ($thumb !== undefined) {
  2052. if (!allFiles) {
  2053. index = self.previewCache.add(content, config[0], tags[0], append);
  2054. data = self.previewCache.get(index, false);
  2055. $div = $(document.createElement('div')).html(data).hide().insertAfter($thumb);
  2056. $newCache = $div.find('.kv-zoom-cache');
  2057. if ($newCache && $newCache.length) {
  2058. $newCache.insertAfter($thumb);
  2059. }
  2060. $thumb.fadeOut('slow', function () {
  2061. var $newThumb = $div.find('.file-preview-frame');
  2062. if ($newThumb && $newThumb.length) {
  2063. $newThumb.insertBefore($thumb).fadeIn('slow').css('display:inline-block');
  2064. }
  2065. self._initPreviewActions();
  2066. self._clearFileInput();
  2067. $h.cleanZoomCache(self.$preview.find('#zoom-' + $thumb.attr('id')));
  2068. $thumb.remove();
  2069. $div.remove();
  2070. self._initSortable();
  2071. });
  2072. } else {
  2073. i = $thumb.attr('data-fileindex');
  2074. self.uploadCache.content[i] = content[0];
  2075. self.uploadCache.config[i] = config[0] || [];
  2076. self.uploadCache.tags[i] = tags[0] || [];
  2077. self.uploadCache.append = append;
  2078. }
  2079. } else {
  2080. self.previewCache.set(content, config, tags, append);
  2081. self._initPreview();
  2082. self._initPreviewActions();
  2083. }
  2084. }
  2085. },
  2086. _initSuccessThumbs: function () {
  2087. var self = this;
  2088. if (!self.showPreview) {
  2089. return;
  2090. }
  2091. self._getThumbs($h.FRAMES + '.file-preview-success').each(function () {
  2092. var $thumb = $(this), $preview = self.$preview, $remove = $thumb.find('.kv-file-remove');
  2093. $remove.removeAttr('disabled');
  2094. self._handler($remove, 'click', function () {
  2095. var id = $thumb.attr('id'),
  2096. out = self._raise('filesuccessremove', [id, $thumb.attr('data-fileindex')]);
  2097. $h.cleanMemory($thumb);
  2098. if (out === false) {
  2099. return;
  2100. }
  2101. $thumb.fadeOut('slow', function () {
  2102. $h.cleanZoomCache($preview.find('#zoom-' + id));
  2103. $thumb.remove();
  2104. if (!self.getFrames().length) {
  2105. self.reset();
  2106. }
  2107. });
  2108. });
  2109. });
  2110. },
  2111. _checkAsyncComplete: function () {
  2112. var self = this, previewId, i;
  2113. for (i = 0; i < self.filestack.length; i++) {
  2114. if (self.filestack[i]) {
  2115. previewId = self.previewInitId + "-" + i;
  2116. if ($.inArray(previewId, self.uploadLog) === -1) {
  2117. return false;
  2118. }
  2119. }
  2120. }
  2121. return (self.uploadAsyncCount === self.uploadLog.length);
  2122. },
  2123. _uploadExtra: function (previewId, index) {
  2124. var self = this, data = self._getExtraData(previewId, index);
  2125. if (data.length === 0) {
  2126. return;
  2127. }
  2128. $.each(data, function (key, value) {
  2129. self.formdata.append(key, value);
  2130. });
  2131. },
  2132. _uploadSingle: function (i, isBatch) {
  2133. var self = this, total = self.getFileStack().length, formdata = new FormData(), outData,
  2134. previewId = self.previewInitId + "-" + i, $thumb, chkComplete, $btnUpload, $btnDelete,
  2135. hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData), uploadFailed,
  2136. $prog = $('#' + previewId).find('.file-thumb-progress'), fnBefore, fnSuccess, fnComplete, fnError,
  2137. updateUploadLog, params = {id: previewId, index: i};
  2138. self.formdata = formdata;
  2139. if (self.showPreview) {
  2140. $thumb = $('#' + previewId + ':not(.file-preview-initial)');
  2141. $btnUpload = $thumb.find('.kv-file-upload');
  2142. $btnDelete = $thumb.find('.kv-file-remove');
  2143. $prog.show();
  2144. }
  2145. if (total === 0 || !hasPostData || ($btnUpload && $btnUpload.hasClass('disabled')) || self._abort(params)) {
  2146. return;
  2147. }
  2148. updateUploadLog = function (i, previewId) {
  2149. if (!uploadFailed) {
  2150. self.updateStack(i, undefined);
  2151. }
  2152. self.uploadLog.push(previewId);
  2153. if (self._checkAsyncComplete()) {
  2154. self.fileBatchCompleted = true;
  2155. }
  2156. };
  2157. chkComplete = function () {
  2158. var u = self.uploadCache, $initThumbs, i, j, len = 0, data = self.cacheInitialPreview;
  2159. if (!self.fileBatchCompleted) {
  2160. return;
  2161. }
  2162. if (data && data.content) {
  2163. len = data.content.length;
  2164. }
  2165. setTimeout(function () {
  2166. var triggerReset = self.getFileStack(true).length === 0;
  2167. if (self.showPreview) {
  2168. self.previewCache.set(u.content, u.config, u.tags, u.append);
  2169. if (len) {
  2170. for (i = 0; i < u.content.length; i++) {
  2171. j = i + len;
  2172. data.content[j] = u.content[i];
  2173. //noinspection JSUnresolvedVariable
  2174. if (data.config.length) {
  2175. data.config[j] = u.config[i];
  2176. }
  2177. if (data.tags.length) {
  2178. data.tags[j] = u.tags[i];
  2179. }
  2180. }
  2181. self.initialPreview = $h.cleanArray(data.content);
  2182. self.initialPreviewConfig = $h.cleanArray(data.config);
  2183. self.initialPreviewThumbTags = $h.cleanArray(data.tags);
  2184. } else {
  2185. self.initialPreview = u.content;
  2186. self.initialPreviewConfig = u.config;
  2187. self.initialPreviewThumbTags = u.tags;
  2188. }
  2189. self.cacheInitialPreview = {};
  2190. if (self.hasInitData) {
  2191. self._initPreview();
  2192. self._initPreviewActions();
  2193. }
  2194. }
  2195. self.unlock(triggerReset);
  2196. if (triggerReset) {
  2197. self._clearFileInput();
  2198. }
  2199. $initThumbs = self.$preview.find('.file-preview-initial');
  2200. if (self.uploadAsync && $initThumbs.length) {
  2201. $h.addCss($initThumbs, $h.SORT_CSS);
  2202. self._initSortable();
  2203. }
  2204. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  2205. self.uploadCount = 0;
  2206. self.uploadStatus = {};
  2207. self.uploadLog = [];
  2208. self._setProgress(101);
  2209. self.ajaxAborted = false;
  2210. }, 100);
  2211. };
  2212. fnBefore = function (jqXHR) {
  2213. outData = self._getOutData(jqXHR);
  2214. self.fileBatchCompleted = false;
  2215. if (!isBatch) {
  2216. self.ajaxAborted = false;
  2217. }
  2218. if (self.showPreview) {
  2219. if (!$thumb.hasClass('file-preview-success')) {
  2220. self._setThumbStatus($thumb, 'Loading');
  2221. $h.addCss($thumb, 'file-uploading');
  2222. }
  2223. $btnUpload.attr('disabled', true);
  2224. $btnDelete.attr('disabled', true);
  2225. }
  2226. if (!isBatch) {
  2227. self.lock();
  2228. }
  2229. self._raise('filepreupload', [outData, previewId, i]);
  2230. $.extend(true, params, outData);
  2231. if (self._abort(params)) {
  2232. jqXHR.abort();
  2233. self._setProgressCancelled();
  2234. }
  2235. };
  2236. fnSuccess = function (data, textStatus, jqXHR) {
  2237. var pid = self.showPreview && $thumb.attr('id') ? $thumb.attr('id') : previewId;
  2238. outData = self._getOutData(jqXHR, data);
  2239. $.extend(true, params, outData);
  2240. setTimeout(function () {
  2241. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  2242. if (self.showPreview) {
  2243. self._setThumbStatus($thumb, 'Success');
  2244. $btnUpload.hide();
  2245. self._initUploadSuccess(data, $thumb, isBatch);
  2246. self._setProgress(101, $prog);
  2247. }
  2248. self._raise('fileuploaded', [outData, pid, i]);
  2249. if (!isBatch) {
  2250. self.updateStack(i, undefined);
  2251. } else {
  2252. updateUploadLog(i, pid);
  2253. }
  2254. } else {
  2255. uploadFailed = true;
  2256. self._showUploadError(data.error, params);
  2257. self._setPreviewError($thumb, i, self.filestack[i], self.retryErrorUploads);
  2258. if (!self.retryErrorUploads) {
  2259. $btnUpload.hide();
  2260. }
  2261. if (isBatch) {
  2262. updateUploadLog(i, pid);
  2263. }
  2264. self._setProgress(101, $('#' + pid).find('.file-thumb-progress'), self.msgUploadError);
  2265. }
  2266. }, 100);
  2267. };
  2268. fnComplete = function () {
  2269. setTimeout(function () {
  2270. if (self.showPreview) {
  2271. $btnUpload.removeAttr('disabled');
  2272. $btnDelete.removeAttr('disabled');
  2273. $thumb.removeClass('file-uploading');
  2274. }
  2275. if (!isBatch) {
  2276. self.unlock(false);
  2277. self._clearFileInput();
  2278. } else {
  2279. chkComplete();
  2280. }
  2281. self._initSuccessThumbs();
  2282. }, 100);
  2283. };
  2284. fnError = function (jqXHR, textStatus, errorThrown) {
  2285. var op = self.ajaxOperations.uploadThumb,
  2286. errMsg = self._parseError(op, jqXHR, errorThrown, (isBatch && self.filestack[i].name ? self.filestack[i].name : null));
  2287. uploadFailed = true;
  2288. setTimeout(function () {
  2289. if (isBatch) {
  2290. updateUploadLog(i, previewId);
  2291. }
  2292. self.uploadStatus[previewId] = 100;
  2293. self._setPreviewError($thumb, i, self.filestack[i], self.retryErrorUploads);
  2294. if (!self.retryErrorUploads) {
  2295. $btnUpload.hide();
  2296. }
  2297. $.extend(true, params, self._getOutData(jqXHR));
  2298. self._setProgress(101, $prog, self.msgAjaxProgressError.replace('{operation}', op));
  2299. self._setProgress(101, $('#' + previewId).find('.file-thumb-progress'), self.msgUploadError);
  2300. self._showUploadError(errMsg, params);
  2301. }, 100);
  2302. };
  2303. formdata.append(self.uploadFileAttr, self.filestack[i], self.filenames[i]);
  2304. formdata.append('file_id', i);
  2305. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, previewId, i);
  2306. },
  2307. _uploadBatch: function () {
  2308. var self = this, files = self.filestack, total = files.length, params = {}, fnBefore, fnSuccess, fnError,
  2309. fnComplete, hasPostData = self.filestack.length > 0 || !$.isEmptyObject(self.uploadExtraData),
  2310. setAllUploaded;
  2311. self.formdata = new FormData();
  2312. if (total === 0 || !hasPostData || self._abort(params)) {
  2313. return;
  2314. }
  2315. setAllUploaded = function () {
  2316. $.each(files, function (key) {
  2317. self.updateStack(key, undefined);
  2318. });
  2319. self._clearFileInput();
  2320. };
  2321. fnBefore = function (jqXHR) {
  2322. self.lock();
  2323. var outData = self._getOutData(jqXHR);
  2324. self.ajaxAborted = false;
  2325. if (self.showPreview) {
  2326. self._getThumbs().each(function () {
  2327. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  2328. $btnDelete = $thumb.find('.kv-file-remove');
  2329. if (!$thumb.hasClass('file-preview-success')) {
  2330. self._setThumbStatus($thumb, 'Loading');
  2331. $h.addCss($thumb, 'file-uploading');
  2332. }
  2333. $btnUpload.attr('disabled', true);
  2334. $btnDelete.attr('disabled', true);
  2335. });
  2336. }
  2337. self._raise('filebatchpreupload', [outData]);
  2338. if (self._abort(outData)) {
  2339. jqXHR.abort();
  2340. self._setProgressCancelled();
  2341. }
  2342. };
  2343. fnSuccess = function (data, textStatus, jqXHR) {
  2344. /** @namespace data.errorkeys */
  2345. var outData = self._getOutData(jqXHR, data), key = 0,
  2346. $thumbs = self._getThumbs(':not(.file-preview-success)'),
  2347. keys = $h.isEmpty(data) || $h.isEmpty(data.errorkeys) ? [] : data.errorkeys;
  2348. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  2349. self._raise('filebatchuploadsuccess', [outData]);
  2350. setAllUploaded();
  2351. if (self.showPreview) {
  2352. $thumbs.each(function () {
  2353. var $thumb = $(this);
  2354. self._setThumbStatus($thumb, 'Success');
  2355. $thumb.removeClass('file-uploading');
  2356. $thumb.find('.kv-file-upload').hide().removeAttr('disabled');
  2357. });
  2358. self._initUploadSuccess(data);
  2359. } else {
  2360. self.reset();
  2361. }
  2362. self._setProgress(101);
  2363. } else {
  2364. if (self.showPreview) {
  2365. $thumbs.each(function () {
  2366. var $thumb = $(this), i = $thumb.attr('data-fileindex');
  2367. $thumb.removeClass('file-uploading');
  2368. $thumb.find('.kv-file-upload').removeAttr('disabled');
  2369. $thumb.find('.kv-file-remove').removeAttr('disabled');
  2370. if (keys.length === 0 || $.inArray(key, keys) !== -1) {
  2371. self._setPreviewError($thumb, i, self.filestack[i], self.retryErrorUploads);
  2372. if (!self.retryErrorUploads) {
  2373. $thumb.find('.kv-file-upload').hide();
  2374. self.updateStack(i, undefined);
  2375. }
  2376. } else {
  2377. $thumb.find('.kv-file-upload').hide();
  2378. self._setThumbStatus($thumb, 'Success');
  2379. self.updateStack(i, undefined);
  2380. }
  2381. if (!$thumb.hasClass('file-preview-error') || self.retryErrorUploads) {
  2382. key++;
  2383. }
  2384. });
  2385. self._initUploadSuccess(data);
  2386. }
  2387. self._showUploadError(data.error, outData, 'filebatchuploaderror');
  2388. self._setProgress(101, self.$progress, self.msgUploadError);
  2389. }
  2390. };
  2391. fnComplete = function () {
  2392. self.unlock();
  2393. self._initSuccessThumbs();
  2394. self._clearFileInput();
  2395. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  2396. };
  2397. fnError = function (jqXHR, textStatus, errorThrown) {
  2398. var outData = self._getOutData(jqXHR), op = self.ajaxOperations.uploadBatch,
  2399. errMsg = self._parseError(op, jqXHR, errorThrown);
  2400. self._showUploadError(errMsg, outData, 'filebatchuploaderror');
  2401. self.uploadFileCount = total - 1;
  2402. if (!self.showPreview) {
  2403. return;
  2404. }
  2405. self._getThumbs().each(function () {
  2406. var $thumb = $(this), key = $thumb.attr('data-fileindex');
  2407. $thumb.removeClass('file-uploading');
  2408. if (self.filestack[key] !== undefined) {
  2409. self._setPreviewError($thumb);
  2410. }
  2411. });
  2412. self._getThumbs().removeClass('file-uploading');
  2413. self._getThumbs(' .kv-file-upload').removeAttr('disabled');
  2414. self._getThumbs(' .kv-file-delete').removeAttr('disabled');
  2415. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  2416. };
  2417. $.each(files, function (key, data) {
  2418. if (!$h.isEmpty(files[key])) {
  2419. self.formdata.append(self.uploadFileAttr, data, self.filenames[key]);
  2420. }
  2421. });
  2422. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  2423. },
  2424. _uploadExtraOnly: function () {
  2425. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError;
  2426. self.formdata = new FormData();
  2427. if (self._abort(params)) {
  2428. return;
  2429. }
  2430. fnBefore = function (jqXHR) {
  2431. self.lock();
  2432. var outData = self._getOutData(jqXHR);
  2433. self._raise('filebatchpreupload', [outData]);
  2434. self._setProgress(50);
  2435. params.data = outData;
  2436. params.xhr = jqXHR;
  2437. if (self._abort(params)) {
  2438. jqXHR.abort();
  2439. self._setProgressCancelled();
  2440. }
  2441. };
  2442. fnSuccess = function (data, textStatus, jqXHR) {
  2443. var outData = self._getOutData(jqXHR, data);
  2444. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  2445. self._raise('filebatchuploadsuccess', [outData]);
  2446. self._clearFileInput();
  2447. self._initUploadSuccess(data);
  2448. self._setProgress(101);
  2449. } else {
  2450. self._showUploadError(data.error, outData, 'filebatchuploaderror');
  2451. }
  2452. };
  2453. fnComplete = function () {
  2454. self.unlock();
  2455. self._clearFileInput();
  2456. self._raise('filebatchuploadcomplete', [self.filestack, self._getExtraData()]);
  2457. };
  2458. fnError = function (jqXHR, textStatus, errorThrown) {
  2459. var outData = self._getOutData(jqXHR), op = self.ajaxOperations.uploadExtra,
  2460. errMsg = self._parseError(op, jqXHR, errorThrown);
  2461. params.data = outData;
  2462. self._showUploadError(errMsg, outData, 'filebatchuploaderror');
  2463. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  2464. };
  2465. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError);
  2466. },
  2467. _deleteFileIndex: function ($frame) {
  2468. var self = this, ind = $frame.attr('data-fileindex');
  2469. if (ind.substring(0, 5) === 'init_') {
  2470. ind = parseInt(ind.replace('init_', ''));
  2471. self.initialPreview = $h.spliceArray(self.initialPreview, ind);
  2472. self.initialPreviewConfig = $h.spliceArray(self.initialPreviewConfig, ind);
  2473. self.initialPreviewThumbTags = $h.spliceArray(self.initialPreviewThumbTags, ind);
  2474. self.getFrames().each(function () {
  2475. var $nFrame = $(this), nInd = $nFrame.attr('data-fileindex');
  2476. if (nInd.substring(0, 5) === 'init_') {
  2477. nInd = parseInt(nInd.replace('init_', ''));
  2478. if (nInd > ind) {
  2479. nInd--;
  2480. $nFrame.attr('data-fileindex', 'init_' + nInd);
  2481. }
  2482. }
  2483. });
  2484. if (self.uploadAsync) {
  2485. self.cacheInitialPreview = self.getPreview();
  2486. }
  2487. }
  2488. },
  2489. _initFileActions: function () {
  2490. var self = this, $preview = self.$preview;
  2491. if (!self.showPreview) {
  2492. return;
  2493. }
  2494. self._initZoomButton();
  2495. self.getFrames(' .kv-file-remove').each(function () {
  2496. var $el = $(this), $frame = $el.closest($h.FRAMES), hasError, id = $frame.attr('id'),
  2497. ind = $frame.attr('data-fileindex'), n, cap, status;
  2498. self._handler($el, 'click', function () {
  2499. status = self._raise('filepreremove', [id, ind]);
  2500. if (status === false || !self._validateMinCount()) {
  2501. return false;
  2502. }
  2503. hasError = $frame.hasClass('file-preview-error');
  2504. $h.cleanMemory($frame);
  2505. $frame.fadeOut('slow', function () {
  2506. $h.cleanZoomCache($preview.find('#zoom-' + id));
  2507. self.updateStack(ind, undefined);
  2508. self._clearObjects($frame);
  2509. $frame.remove();
  2510. if (id && hasError) {
  2511. self.$errorContainer.find('li[data-file-id="' + id + '"]').fadeOut('fast', function () {
  2512. $(this).remove();
  2513. if (!self._errorsExist()) {
  2514. self._resetErrors();
  2515. }
  2516. });
  2517. }
  2518. self._clearFileInput();
  2519. var filestack = self.getFileStack(true), chk = self.previewCache.count(),
  2520. len = filestack.length, hasThumb = self.showPreview && self.getFrames().length;
  2521. if (len === 0 && chk === 0 && !hasThumb) {
  2522. self.reset();
  2523. } else {
  2524. n = chk + len;
  2525. cap = n > 1 ? self._getMsgSelected(n) : (filestack[0] ? self._getFileNames()[0] : '');
  2526. self._setCaption(cap);
  2527. }
  2528. self._raise('fileremoved', [id, ind]);
  2529. });
  2530. });
  2531. });
  2532. self.getFrames(' .kv-file-upload').each(function () {
  2533. var $el = $(this);
  2534. self._handler($el, 'click', function () {
  2535. var $frame = $el.closest($h.FRAMES), ind = $frame.attr('data-fileindex');
  2536. self.$progress.hide();
  2537. if ($frame.hasClass('file-preview-error') && !self.retryErrorUploads) {
  2538. return;
  2539. }
  2540. self._uploadSingle(ind, false);
  2541. });
  2542. });
  2543. },
  2544. _initPreviewActions: function () {
  2545. var self = this, $preview = self.$preview, deleteExtraData = self.deleteExtraData || {},
  2546. btnRemove = $h.FRAMES + ' .kv-file-remove', settings = self.fileActionSettings,
  2547. origClass = settings.removeClass, errClass = settings.removeErrorClass,
  2548. resetProgress = function () {
  2549. var hasFiles = self.isAjaxUpload ? self.previewCache.count() : self.$element.get(0).files.length;
  2550. if (!$preview.find($h.FRAMES).length && !hasFiles) {
  2551. self._setCaption('');
  2552. self.reset();
  2553. self.initialCaption = '';
  2554. }
  2555. };
  2556. self._initZoomButton();
  2557. $preview.find(btnRemove).each(function () {
  2558. var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key'),
  2559. fnBefore, fnSuccess, fnError;
  2560. if ($h.isEmpty(vUrl) || vKey === undefined) {
  2561. return;
  2562. }
  2563. var $frame = $el.closest($h.FRAMES), cache = self.previewCache.data,
  2564. settings, params, index = $frame.attr('data-fileindex'), config, extraData;
  2565. index = parseInt(index.replace('init_', ''));
  2566. config = $h.isEmpty(cache.config) && $h.isEmpty(cache.config[index]) ? null : cache.config[index];
  2567. extraData = $h.isEmpty(config) || $h.isEmpty(config.extra) ? deleteExtraData : config.extra;
  2568. if (typeof extraData === "function") {
  2569. extraData = extraData();
  2570. }
  2571. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  2572. fnBefore = function (jqXHR) {
  2573. self.ajaxAborted = false;
  2574. self._raise('filepredelete', [vKey, jqXHR, extraData]);
  2575. $el.removeClass(errClass);
  2576. if (self._abort()) {
  2577. jqXHR.abort();
  2578. } else {
  2579. $h.addCss($frame, 'file-uploading');
  2580. $h.addCss($el, 'disabled ' + origClass);
  2581. }
  2582. };
  2583. fnSuccess = function (data, textStatus, jqXHR) {
  2584. var n, cap;
  2585. if (!$h.isEmpty(data) && !$h.isEmpty(data.error)) {
  2586. params.jqXHR = jqXHR;
  2587. params.response = data;
  2588. self._showError(data.error, params, 'filedeleteerror');
  2589. $frame.removeClass('file-uploading');
  2590. $el.removeClass('disabled ' + origClass).addClass(errClass);
  2591. resetProgress();
  2592. return;
  2593. }
  2594. $frame.removeClass('file-uploading').addClass('file-deleted');
  2595. $frame.fadeOut('slow', function () {
  2596. index = parseInt(($frame.attr('data-fileindex')).replace('init_', ''));
  2597. self.previewCache.unset(index);
  2598. n = self.previewCache.count();
  2599. cap = n > 0 ? self._getMsgSelected(n) : '';
  2600. self._deleteFileIndex($frame);
  2601. self._setCaption(cap);
  2602. self._raise('filedeleted', [vKey, jqXHR, extraData]);
  2603. $h.cleanZoomCache($preview.find('#zoom-' + $frame.attr('id')));
  2604. self._clearObjects($frame);
  2605. $frame.remove();
  2606. resetProgress();
  2607. });
  2608. };
  2609. fnError = function (jqXHR, textStatus, errorThrown) {
  2610. var op = self.ajaxOperations.deleteThumb, errMsg = self._parseError(op, jqXHR, errorThrown);
  2611. params.jqXHR = jqXHR;
  2612. params.response = {};
  2613. self._showError(errMsg, params, 'filedeleteerror');
  2614. $frame.removeClass('file-uploading');
  2615. $el.removeClass('disabled ' + origClass).addClass(errClass);
  2616. resetProgress();
  2617. };
  2618. self._mergeAjaxCallback('beforeSend', fnBefore, 'delete');
  2619. self._mergeAjaxCallback('success', fnSuccess, 'delete');
  2620. self._mergeAjaxCallback('error', fnError, 'delete');
  2621. settings = $.extend(true, {}, {
  2622. url: vUrl,
  2623. type: 'POST',
  2624. dataType: 'json',
  2625. data: $.extend(true, {}, {key: vKey}, extraData)
  2626. }, self.ajaxDeleteSettings);
  2627. self._handler($el, 'click', function () {
  2628. if (!self._validateMinCount()) {
  2629. return false;
  2630. }
  2631. self.ajaxAborted = false;
  2632. self._raise('filebeforedelete', [vKey, extraData]);
  2633. //noinspection JSUnresolvedVariable,JSHint
  2634. if (self.ajaxAborted instanceof Promise) {
  2635. self.ajaxAborted.then(function (result) {
  2636. if (!result) {
  2637. $.ajax(settings);
  2638. }
  2639. });
  2640. } else {
  2641. if (!self.ajaxAborted) {
  2642. $.ajax(settings);
  2643. }
  2644. }
  2645. });
  2646. });
  2647. self.getFrames(' .kv-file-download').each(function () {
  2648. var $el = $(this);
  2649. self._handler($el, 'click', function () {
  2650. var a = document.createElement('a');
  2651. a.href = $el.attr('data-url');
  2652. a.download = $el.attr('data-caption');
  2653. a.target = '_blank';
  2654. a.click();
  2655. });
  2656. });
  2657. },
  2658. _hideFileIcon: function () {
  2659. var self = this;
  2660. if (self.overwriteInitial) {
  2661. self.$captionContainer.removeClass('icon-visible');
  2662. }
  2663. },
  2664. _showFileIcon: function () {
  2665. var self = this;
  2666. $h.addCss(self.$captionContainer, 'icon-visible');
  2667. },
  2668. _getSize: function (bytes) {
  2669. var self = this, size = parseFloat(bytes), i, func = self.fileSizeGetter, sizes, out;
  2670. if (!$.isNumeric(bytes) || !$.isNumeric(size)) {
  2671. return '';
  2672. }
  2673. if (typeof func === 'function') {
  2674. out = func(size);
  2675. } else {
  2676. if (size === 0) {
  2677. out = '0.00 B';
  2678. } else {
  2679. i = Math.floor(Math.log(size) / Math.log(1024));
  2680. sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  2681. out = (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + sizes[i];
  2682. }
  2683. }
  2684. return self._getLayoutTemplate('size').replace('{sizeText}', out);
  2685. },
  2686. _generatePreviewTemplate: function (cat, data, fname, ftype, previewId, isError, size, frameClass, foot, ind, templ) {
  2687. var self = this, caption = self.slug(fname), prevContent, zoomContent = '', styleAttribs = '',
  2688. screenW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
  2689. config = screenW < 400 ? (self.previewSettingsSmall[cat] || self.defaults.previewSettingsSmall[cat]) :
  2690. (self.previewSettings[cat] || self.defaults.previewSettings[cat]),
  2691. footer = foot || self._renderFileFooter(caption, size, 'auto', isError),
  2692. hasIconSetting = self._getPreviewIcon(fname), typeCss = 'type-default',
  2693. forcePrevIcon = hasIconSetting && self.preferIconicPreview,
  2694. forceZoomIcon = hasIconSetting && self.preferIconicZoomPreview, getContent;
  2695. if (config) {
  2696. $.each(config, function (key, val) {
  2697. styleAttribs += key + ':' + val + ';';
  2698. });
  2699. }
  2700. getContent = function (c, d, zoom, frameCss) {
  2701. var id = zoom ? 'zoom-' + previewId : previewId, tmplt = self._getPreviewTemplate(c),
  2702. css = (frameClass || '') + ' ' + frameCss;
  2703. if (self.frameClass) {
  2704. css = self.frameClass + ' ' + css;
  2705. }
  2706. if (zoom) {
  2707. css = css.replace(' ' + $h.SORT_CSS, '');
  2708. }
  2709. tmplt = self._parseFilePreviewIcon(tmplt, fname);
  2710. if (c === 'text') {
  2711. d = $h.htmlEncode(d);
  2712. }
  2713. if (cat === 'object' && !ftype) {
  2714. $.each(self.defaults.fileTypeSettings, function (key, func) {
  2715. if (key === 'object' || key === 'other') {
  2716. return;
  2717. }
  2718. if (func(fname, ftype)) {
  2719. typeCss = 'type-' + key;
  2720. }
  2721. });
  2722. }
  2723. return tmplt.setTokens({
  2724. 'previewId': id,
  2725. 'caption': caption,
  2726. 'frameClass': css,
  2727. 'type': ftype,
  2728. 'fileindex': ind,
  2729. 'typeCss': typeCss,
  2730. 'footer': footer,
  2731. 'data': d,
  2732. 'template': templ || cat,
  2733. 'style': styleAttribs ? 'style="' + styleAttribs + '"' : ''
  2734. });
  2735. };
  2736. ind = ind || previewId.slice(previewId.lastIndexOf('-') + 1);
  2737. if (self.fileActionSettings.showZoom) {
  2738. zoomContent = getContent((forceZoomIcon ? 'other' : cat), data, true, 'kv-zoom-thumb');
  2739. }
  2740. zoomContent = '\n' + self._getLayoutTemplate('zoomCache').replace('{zoomContent}', zoomContent);
  2741. prevContent = getContent((forcePrevIcon ? 'other' : cat), data, false, 'kv-preview-thumb');
  2742. return prevContent + zoomContent;
  2743. },
  2744. _previewDefault: function (file, previewId, isDisabled) {
  2745. var self = this, $preview = self.$preview;
  2746. if (!self.showPreview) {
  2747. return;
  2748. }
  2749. var fname = file ? file.name : '', ftype = file ? file.type : '', content, size = file.size || 0,
  2750. caption = self.slug(fname), isError = isDisabled === true && !self.isAjaxUpload,
  2751. data = $h.objUrl.createObjectURL(file);
  2752. self._clearDefaultPreview();
  2753. content = self._generatePreviewTemplate('other', data, fname, ftype, previewId, isError, size);
  2754. $preview.append("\n" + content);
  2755. self._setThumbAttr(previewId, caption, size);
  2756. if (isDisabled === true && self.isAjaxUpload) {
  2757. self._setThumbStatus($('#' + previewId), 'Error');
  2758. }
  2759. },
  2760. _previewFile: function (i, file, theFile, previewId, data, fileInfo) {
  2761. if (!this.showPreview) {
  2762. return;
  2763. }
  2764. var self = this, fname = file ? file.name : '', ftype = fileInfo.type, caption = fileInfo.name,
  2765. cat = self._parseFileType(ftype, fname), types = self.allowedPreviewTypes, content,
  2766. mimes = self.allowedPreviewMimeTypes, $preview = self.$preview, fsize = file.size || 0,
  2767. chkTypes = types && types.indexOf(cat) >= 0, chkMimes = mimes && mimes.indexOf(ftype) !== -1,
  2768. iData = (cat === 'text' || cat === 'html' || cat === 'image') ? theFile.target.result : data;
  2769. /** @namespace window.DOMPurify */
  2770. if (cat === 'html' && self.purifyHtml && window.DOMPurify) {
  2771. iData = window.DOMPurify.sanitize(iData);
  2772. }
  2773. if (chkTypes || chkMimes) {
  2774. content = self._generatePreviewTemplate(cat, iData, fname, ftype, previewId, false, fsize);
  2775. self._clearDefaultPreview();
  2776. $preview.append("\n" + content);
  2777. var $img = $preview.find('#' + previewId + ' img');
  2778. if ($img.length && self.autoOrientImage) {
  2779. $h.validateOrientation(file, function (value) {
  2780. if (!value) {
  2781. self._validateImage(previewId, caption, ftype, fsize, iData);
  2782. return;
  2783. }
  2784. var $zoomImg = $preview.find('#zoom-' + previewId + ' img'), css = 'rotate-' + value;
  2785. if (value > 4) {
  2786. css += ($img.width() > $img.height() ? ' is-portrait-gt4' : ' is-landscape-gt4');
  2787. }
  2788. $h.addCss($img, css);
  2789. $h.addCss($zoomImg, css);
  2790. self._raise('fileimageoriented', {'$img': $img, 'file': file});
  2791. self._validateImage(previewId, caption, ftype, fsize, iData);
  2792. $h.adjustOrientedImage($img);
  2793. });
  2794. } else {
  2795. self._validateImage(previewId, caption, ftype, fsize, iData);
  2796. }
  2797. } else {
  2798. self._previewDefault(file, previewId);
  2799. }
  2800. self._setThumbAttr(previewId, caption, fsize);
  2801. self._initSortable();
  2802. },
  2803. _setThumbAttr: function (id, caption, size) {
  2804. var self = this, $frame = $('#' + id);
  2805. if ($frame.length) {
  2806. size = size && size > 0 ? self._getSize(size) : '';
  2807. $frame.data({'caption': caption, 'size': size});
  2808. }
  2809. },
  2810. _setInitThumbAttr: function () {
  2811. var self = this, data = self.previewCache.data, len = self.previewCache.count(), config,
  2812. caption, size, previewId;
  2813. if (len === 0) {
  2814. return;
  2815. }
  2816. for (var i = 0; i < len; i++) {
  2817. config = data.config[i];
  2818. previewId = self.previewInitId + '-' + 'init_' + i;
  2819. caption = $h.ifSet('caption', config, $h.ifSet('filename', config));
  2820. size = $h.ifSet('size', config);
  2821. self._setThumbAttr(previewId, caption, size);
  2822. }
  2823. },
  2824. _slugDefault: function (text) {
  2825. return $h.isEmpty(text) ? '' : String(text).replace(/[\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_');
  2826. },
  2827. _readFiles: function (files) {
  2828. this.reader = new FileReader();
  2829. var self = this, $el = self.$element, $preview = self.$preview, reader = self.reader,
  2830. $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
  2831. msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
  2832. settings = self.fileTypeSettings, ctr = self.filestack.length, readFile,
  2833. fileTypes = self.allowedFileTypes, typLen = fileTypes ? fileTypes.length : 0,
  2834. fileExt = self.allowedFileExtensions, strExt = $h.isEmpty(fileExt) ? '' : fileExt.join(', '),
  2835. maxPreviewSize = self.maxFilePreviewSize && parseFloat(self.maxFilePreviewSize),
  2836. canPreview = $preview.length && (!maxPreviewSize || isNaN(maxPreviewSize)),
  2837. throwError = function (msg, 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}, $thumb;
  2840. self._previewDefault(file, previewId, true);
  2841. if (self.isAjaxUpload) {
  2842. self.addToStack(undefined);
  2843. setTimeout(function () {
  2844. readFile(index + 1);
  2845. }, 100);
  2846. } else {
  2847. numFiles = 0;
  2848. }
  2849. self._initFileActions();
  2850. $thumb = $('#' + previewId);
  2851. $thumb.find('.kv-file-upload').hide();
  2852. if (self.removeFromPreviewOnError) {
  2853. $thumb.remove();
  2854. }
  2855. self.isError = self.isAjaxUpload ? self._showUploadError(msg, p1) : self._showError(msg, p2);
  2856. self._updateFileDetails(numFiles);
  2857. };
  2858. self.loadedImages = [];
  2859. self.totalImagesCount = 0;
  2860. $.each(files, function (key, file) {
  2861. var func = self.fileTypeSettings.image;
  2862. if (func && func(file.type)) {
  2863. self.totalImagesCount++;
  2864. }
  2865. });
  2866. readFile = function (i) {
  2867. if ($h.isEmpty($el.attr('multiple'))) {
  2868. numFiles = 1;
  2869. }
  2870. if (i >= numFiles) {
  2871. if (self.isAjaxUpload && self.filestack.length > 0) {
  2872. self._raise('filebatchselected', [self.getFileStack()]);
  2873. } else {
  2874. self._raise('filebatchselected', [files]);
  2875. }
  2876. $container.removeClass('file-thumb-loading');
  2877. $status.html('');
  2878. return;
  2879. }
  2880. var node = ctr + i, previewId = previewInitId + "-" + node, file = files[i], fSizeKB, j, msg,
  2881. fnText = settings.text, fnImage = settings.image, fnHtml = settings.html, typ, chk, typ1, typ2,
  2882. caption = file.name ? self.slug(file.name) : '', fileSize = (file.size || 0) / 1000,
  2883. fileExtExpr = '', previewData = $h.objUrl.createObjectURL(file), fileCount = 0, strTypes = '',
  2884. func, knownTypes = 0, isText, isHtml, isImage, txtFlag, processFileLoaded = function () {
  2885. var msg = msgProgress.setTokens({
  2886. 'index': i + 1,
  2887. 'files': numFiles,
  2888. 'percent': 50,
  2889. 'name': caption
  2890. });
  2891. setTimeout(function () {
  2892. $status.html(msg);
  2893. self._updateFileDetails(numFiles);
  2894. readFile(i + 1);
  2895. }, 100);
  2896. self._raise('fileloaded', [file, previewId, i, reader]);
  2897. };
  2898. if (typLen > 0) {
  2899. for (j = 0; j < typLen; j++) {
  2900. typ1 = fileTypes[j];
  2901. typ2 = self.msgFileTypes[typ1] || typ1;
  2902. strTypes += j === 0 ? typ2 : ', ' + typ2;
  2903. }
  2904. }
  2905. if (caption === false) {
  2906. readFile(i + 1);
  2907. return;
  2908. }
  2909. if (caption.length === 0) {
  2910. msg = self.msgInvalidFileName.replace('{name}', $h.htmlEncode(file.name));
  2911. throwError(msg, file, previewId, i);
  2912. return;
  2913. }
  2914. if (!$h.isEmpty(fileExt)) {
  2915. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  2916. }
  2917. fSizeKB = fileSize.toFixed(2);
  2918. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  2919. msg = self.msgSizeTooLarge.setTokens({
  2920. 'name': caption,
  2921. 'size': fSizeKB,
  2922. 'maxSize': self.maxFileSize
  2923. });
  2924. throwError(msg, file, previewId, i);
  2925. return;
  2926. }
  2927. if (self.minFileSize !== null && fileSize <= $h.getNum(self.minFileSize)) {
  2928. msg = self.msgSizeTooSmall.setTokens({
  2929. 'name': caption,
  2930. 'size': fSizeKB,
  2931. 'minSize': self.minFileSize
  2932. });
  2933. throwError(msg, file, previewId, i);
  2934. return;
  2935. }
  2936. if (!$h.isEmpty(fileTypes) && $h.isArray(fileTypes)) {
  2937. for (j = 0; j < fileTypes.length; j += 1) {
  2938. typ = fileTypes[j];
  2939. func = settings[typ];
  2940. fileCount += !func || (typeof func !== 'function') ? 0 : (func(file.type, file.name) ? 1 : 0);
  2941. }
  2942. if (fileCount === 0) {
  2943. msg = self.msgInvalidFileType.setTokens({'name': caption, 'types': strTypes});
  2944. throwError(msg, file, previewId, i);
  2945. return;
  2946. }
  2947. }
  2948. if (fileCount === 0 && !$h.isEmpty(fileExt) && $h.isArray(fileExt) && !$h.isEmpty(fileExtExpr)) {
  2949. chk = $h.compare(caption, fileExtExpr);
  2950. fileCount += $h.isEmpty(chk) ? 0 : chk.length;
  2951. if (fileCount === 0) {
  2952. msg = self.msgInvalidFileExtension.setTokens({'name': caption, 'extensions': strExt});
  2953. throwError(msg, file, previewId, i);
  2954. return;
  2955. }
  2956. }
  2957. if (!self.showPreview) {
  2958. if (self.isAjaxUpload) {
  2959. self.addToStack(file);
  2960. }
  2961. setTimeout(function () {
  2962. readFile(i + 1);
  2963. self._updateFileDetails(numFiles);
  2964. }, 100);
  2965. self._raise('fileloaded', [file, previewId, i, reader]);
  2966. return;
  2967. }
  2968. if (!canPreview && fileSize > maxPreviewSize) {
  2969. self.addToStack(file);
  2970. $container.addClass('file-thumb-loading');
  2971. self._previewDefault(file, previewId);
  2972. self._initFileActions();
  2973. self._updateFileDetails(numFiles);
  2974. readFile(i + 1);
  2975. return;
  2976. }
  2977. if ($preview.length && FileReader !== undefined) {
  2978. isText = fnText(file.type, caption);
  2979. isHtml = fnHtml(file.type, caption);
  2980. isImage = fnImage(file.type, caption);
  2981. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  2982. $container.addClass('file-thumb-loading');
  2983. reader.onerror = function (evt) {
  2984. self._errorHandler(evt, caption);
  2985. };
  2986. reader.onload = function (theFile) {
  2987. var hex, fileInfo, uint, byte, bytes = [], contents, mime, readTextImage = function (textFlag) {
  2988. var newReader = new FileReader();
  2989. newReader.onerror = function (theFileNew) {
  2990. self._errorHandler(theFileNew, caption);
  2991. };
  2992. newReader.onload = function (theFileNew) {
  2993. self._previewFile(i, file, theFileNew, previewId, previewData, fileInfo);
  2994. self._initFileActions();
  2995. processFileLoaded();
  2996. };
  2997. if (textFlag) {
  2998. newReader.readAsText(file, self.textEncoding);
  2999. } else {
  3000. newReader.readAsDataURL(file);
  3001. }
  3002. };
  3003. fileInfo = {'name': caption, 'type': file.type};
  3004. $.each(settings, function (key, func) {
  3005. if (key !== 'object' && key !== 'other' && func(file.type, caption)) {
  3006. knownTypes++;
  3007. }
  3008. });
  3009. if (knownTypes === 0) {// auto detect mime types from content if no known file types detected
  3010. uint = new Uint8Array(theFile.target.result);
  3011. for (j = 0; j < uint.length; j++) {
  3012. byte = uint[j].toString(16);
  3013. bytes.push(byte);
  3014. }
  3015. hex = bytes.join('').toLowerCase().substring(0, 8);
  3016. mime = $h.getMimeType(hex, '', '');
  3017. if ($h.isEmpty(mime)) { // look for ascii text content
  3018. contents = $h.arrayBuffer2String(reader.result);
  3019. mime = $h.isSvg(contents) ? 'image/svg+xml' : $h.getMimeType(hex, contents, file.type);
  3020. }
  3021. fileInfo = {'name': caption, 'type': mime};
  3022. isText = fnText(mime, '');
  3023. isHtml = fnHtml(mime, '');
  3024. isImage = fnImage(mime, '');
  3025. txtFlag = isText || isHtml;
  3026. if (txtFlag || isImage) {
  3027. readTextImage(txtFlag);
  3028. return;
  3029. }
  3030. }
  3031. self._previewFile(i, file, theFile, previewId, previewData, fileInfo);
  3032. self._initFileActions();
  3033. processFileLoaded();
  3034. };
  3035. reader.onprogress = function (data) {
  3036. if (data.lengthComputable) {
  3037. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  3038. msg = msgProgress.setTokens({
  3039. 'index': i + 1,
  3040. 'files': numFiles,
  3041. 'percent': progress,
  3042. 'name': caption
  3043. });
  3044. setTimeout(function () {
  3045. $status.html(msg);
  3046. }, 100);
  3047. }
  3048. };
  3049. if (isText || isHtml) {
  3050. reader.readAsText(file, self.textEncoding);
  3051. } else {
  3052. if (isImage) {
  3053. reader.readAsDataURL(file);
  3054. } else {
  3055. reader.readAsArrayBuffer(file);
  3056. }
  3057. }
  3058. } else {
  3059. self._previewDefault(file, previewId);
  3060. setTimeout(function () {
  3061. readFile(i + 1);
  3062. self._updateFileDetails(numFiles);
  3063. }, 100);
  3064. self._raise('fileloaded', [file, previewId, i, reader]);
  3065. }
  3066. self.addToStack(file);
  3067. };
  3068. readFile(0);
  3069. self._updateFileDetails(numFiles, false);
  3070. },
  3071. _updateFileDetails: function (numFiles) {
  3072. var self = this, $el = self.$element, fileStack = self.getFileStack(),
  3073. name = ($h.isIE(9) && $h.findFileName($el.val())) ||
  3074. ($el[0].files[0] && $el[0].files[0].name) || (fileStack.length && fileStack[0].name) || '',
  3075. label = self.slug(name), n = self.isAjaxUpload ? fileStack.length : numFiles,
  3076. nFiles = self.previewCache.count() + n, log = n === 1 ? label : self._getMsgSelected(nFiles);
  3077. if (self.isError) {
  3078. self.$previewContainer.removeClass('file-thumb-loading');
  3079. self.$previewStatus.html('');
  3080. self.$captionContainer.removeClass('icon-visible');
  3081. } else {
  3082. self._showFileIcon();
  3083. }
  3084. self._setCaption(log, self.isError);
  3085. self.$container.removeClass('file-input-new file-input-ajax-new');
  3086. if (arguments.length === 1) {
  3087. self._raise('fileselect', [numFiles, label]);
  3088. }
  3089. if (self.previewCache.count()) {
  3090. self._initPreviewActions();
  3091. }
  3092. },
  3093. _setThumbStatus: function ($thumb, status) {
  3094. var self = this;
  3095. if (!self.showPreview) {
  3096. return;
  3097. }
  3098. var icon = 'indicator' + status, msg = icon + 'Title',
  3099. css = 'file-preview-' + status.toLowerCase(),
  3100. $indicator = $thumb.find('.file-upload-indicator'),
  3101. config = self.fileActionSettings;
  3102. $thumb.removeClass('file-preview-success file-preview-error file-preview-loading');
  3103. if (status === 'Success') {
  3104. $thumb.find('.file-drag-handle').remove();
  3105. }
  3106. $indicator.html(config[icon]);
  3107. $indicator.attr('title', config[msg]);
  3108. $thumb.addClass(css);
  3109. if (status === 'Error' && !self.retryErrorUploads) {
  3110. $thumb.find('.kv-file-upload').attr('disabled', true);
  3111. }
  3112. },
  3113. _setProgressCancelled: function () {
  3114. var self = this;
  3115. self._setProgress(101, self.$progress, self.msgCancelled);
  3116. },
  3117. _setProgress: function (p, $el, error) {
  3118. var self = this, pct = Math.min(p, 100), out, pctLimit = self.progressUploadThreshold,
  3119. t = p <= 100 ? self.progressTemplate : self.progressCompleteTemplate,
  3120. template = pct < 100 ? self.progressTemplate : (error ? self.progressErrorTemplate : t);
  3121. $el = $el || self.$progress;
  3122. if (!$h.isEmpty(template)) {
  3123. if (pctLimit && pct > pctLimit && p <= 100) {
  3124. out = template.setTokens({'percent': pctLimit, 'status': self.msgUploadThreshold});
  3125. } else {
  3126. out = template.setTokens({'percent': pct, 'status': (p > 100 ? self.msgUploadEnd : pct + '%')});
  3127. }
  3128. $el.html(out);
  3129. if (error) {
  3130. $el.find('[role="progressbar"]').html(error);
  3131. }
  3132. }
  3133. },
  3134. _setFileDropZoneTitle: function () {
  3135. var self = this, $zone = self.$container.find('.file-drop-zone'), title = self.dropZoneTitle, strFiles;
  3136. if (self.isClickable) {
  3137. strFiles = $h.isEmpty(self.$element.attr('multiple')) ? self.fileSingle : self.filePlural;
  3138. title += self.dropZoneClickTitle.replace('{files}', strFiles);
  3139. }
  3140. $zone.find('.' + self.dropZoneTitleClass).remove();
  3141. if (!self.isAjaxUpload || !self.showPreview || $zone.length === 0 || self.getFileStack().length > 0 || !self.dropZoneEnabled) {
  3142. return;
  3143. }
  3144. if ($zone.find($h.FRAMES).length === 0 && $h.isEmpty(self.defaultPreviewContent)) {
  3145. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + title + '</div>');
  3146. }
  3147. self.$container.removeClass('file-input-new');
  3148. $h.addCss(self.$container, 'file-input-ajax-new');
  3149. },
  3150. _setAsyncUploadStatus: function (previewId, pct, total) {
  3151. var self = this, sum = 0;
  3152. self._setProgress(pct, $('#' + previewId).find('.file-thumb-progress'));
  3153. self.uploadStatus[previewId] = pct;
  3154. $.each(self.uploadStatus, function (key, value) {
  3155. sum += value;
  3156. });
  3157. self._setProgress(Math.floor(sum / total));
  3158. },
  3159. _validateMinCount: function () {
  3160. var self = this, len = self.isAjaxUpload ? self.getFileStack().length : self.$element.get(0).files.length;
  3161. if (self.validateInitialCount && self.minFileCount > 0 && self._getFileCount(len - 1) < self.minFileCount) {
  3162. self._noFilesError({});
  3163. return false;
  3164. }
  3165. return true;
  3166. },
  3167. _getFileCount: function (fileCount) {
  3168. var self = this, addCount = 0;
  3169. if (self.validateInitialCount && !self.overwriteInitial) {
  3170. addCount = self.previewCache.count();
  3171. fileCount += addCount;
  3172. }
  3173. return fileCount;
  3174. },
  3175. _getFileId: function (file) {
  3176. var self = this, custom = self.generateFileId, relativePath;
  3177. if (typeof custom === 'function') {
  3178. return custom(file, event);
  3179. }
  3180. if (!file) {
  3181. return null;
  3182. }
  3183. /** @namespace file.webkitRelativePath */
  3184. relativePath = String(file.webkitRelativePath || file.fileName || file.name || null);
  3185. if (!relativePath) {
  3186. return null;
  3187. }
  3188. return (file.size + '-' + relativePath.replace(/[^0-9a-zA-Z_-]/img, ''));
  3189. },
  3190. _getFileName: function (file) {
  3191. return file && file.name ? this.slug(file.name) : undefined;
  3192. },
  3193. _getFileIds: function (skipNull) {
  3194. var self = this;
  3195. return self.fileids.filter(function (n) {
  3196. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  3197. });
  3198. },
  3199. _getFileNames: function (skipNull) {
  3200. var self = this;
  3201. return self.filenames.filter(function (n) {
  3202. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  3203. });
  3204. },
  3205. _setPreviewError: function ($thumb, i, val, repeat) {
  3206. var self = this;
  3207. if (i !== undefined) {
  3208. self.updateStack(i, val);
  3209. }
  3210. if (!self.showPreview) {
  3211. return;
  3212. }
  3213. if (self.removeFromPreviewOnError && !repeat) {
  3214. $thumb.remove();
  3215. return;
  3216. } else {
  3217. self._setThumbStatus($thumb, 'Error');
  3218. }
  3219. self._refreshUploadButton($thumb, repeat);
  3220. },
  3221. _refreshUploadButton: function ($thumb, repeat) {
  3222. var self = this, $btn = $thumb.find('.kv-file-upload'), cfg = self.fileActionSettings,
  3223. icon = cfg.uploadIcon, title = cfg.uploadTitle;
  3224. if (!$btn.length) {
  3225. return;
  3226. }
  3227. if (repeat) {
  3228. icon = cfg.uploadRetryIcon;
  3229. title = cfg.uploadRetryTitle;
  3230. }
  3231. $btn.attr('title', title).html(icon);
  3232. },
  3233. _checkDimensions: function (i, chk, $img, $thumb, fname, type, params) {
  3234. var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max', limit = self[tag + 'Image' + type],
  3235. $imgEl, isValid;
  3236. if ($h.isEmpty(limit) || !$img.length) {
  3237. return;
  3238. }
  3239. $imgEl = $img[0];
  3240. dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height;
  3241. isValid = chk === 'Small' ? dim >= limit : dim <= limit;
  3242. if (isValid) {
  3243. return;
  3244. }
  3245. msg = self['msgImage' + type + chk].setTokens({'name': fname, 'size': limit});
  3246. self._showUploadError(msg, params);
  3247. self._setPreviewError($thumb, i, null);
  3248. },
  3249. _validateImage: function (previewId, fname, ftype, fsize, iData) {
  3250. var self = this, $preview = self.$preview, params, w1, w2, $thumb = $preview.find("#" + previewId),
  3251. i = $thumb.attr('data-fileindex'), $img = $thumb.find('img'), exifObject;
  3252. fname = fname || 'Untitled';
  3253. $img.one('load', function () {
  3254. w1 = $thumb.width();
  3255. w2 = $preview.width();
  3256. if (w1 > w2) {
  3257. $img.css('width', '100%');
  3258. }
  3259. params = {ind: i, id: previewId};
  3260. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
  3261. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
  3262. if (!self.resizeImage) {
  3263. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
  3264. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
  3265. }
  3266. self._raise('fileimageloaded', [previewId]);
  3267. try {
  3268. exifObject = window.piexif ? window.piexif.load(iData) : null;
  3269. } catch (err) {
  3270. exifObject = null;
  3271. }
  3272. self.loadedImages.push({
  3273. ind: i,
  3274. img: $img,
  3275. thumb: $thumb,
  3276. pid: previewId,
  3277. typ: ftype,
  3278. siz: fsize,
  3279. validated: false,
  3280. imgData: iData,
  3281. exifObj: exifObject
  3282. });
  3283. $thumb.data('exif', exifObject);
  3284. self._validateAllImages();
  3285. }).one('error', function () {
  3286. self._raise('fileimageloaderror', [previewId]);
  3287. }).each(function () {
  3288. if (this.complete) {
  3289. $(this).trigger('load');
  3290. } else {
  3291. if (this.error) {
  3292. $(this).trigger('error');
  3293. }
  3294. }
  3295. });
  3296. },
  3297. _validateAllImages: function () {
  3298. var self = this, i, counter = {val: 0}, numImgs = self.loadedImages.length, config,
  3299. fsize, minSize = self.resizeIfSizeMoreThan;
  3300. if (numImgs !== self.totalImagesCount) {
  3301. return;
  3302. }
  3303. self._raise('fileimagesloaded');
  3304. if (!self.resizeImage) {
  3305. return;
  3306. }
  3307. for (i = 0; i < self.loadedImages.length; i++) {
  3308. config = self.loadedImages[i];
  3309. if (config.validated) {
  3310. continue;
  3311. }
  3312. fsize = config.siz;
  3313. if (fsize && fsize > minSize * 1000) {
  3314. self._getResizedImage(config, counter, numImgs);
  3315. }
  3316. self.loadedImages[i].validated = true;
  3317. }
  3318. },
  3319. _getResizedImage: function (config, counter, numImgs) {
  3320. var self = this, img = $(config.img)[0], width = img.naturalWidth, height = img.naturalHeight, blob,
  3321. ratio = 1, maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height,
  3322. isValidImage = !!(width && height), chkWidth, chkHeight, canvas = self.imageCanvas, dataURI,
  3323. context = self.imageCanvasContext, type = config.typ, pid = config.pid, ind = config.ind,
  3324. $thumb = config.thumb, throwError, msg, exifObj = config.exifObj, exifStr;
  3325. throwError = function (msg, params, ev) {
  3326. if (self.isAjaxUpload) {
  3327. self._showUploadError(msg, params, ev);
  3328. } else {
  3329. self._showError(msg, params, ev);
  3330. }
  3331. self._setPreviewError($thumb, ind);
  3332. };
  3333. if (!self.filestack[ind] || !isValidImage || (width <= maxWidth && height <= maxHeight)) {
  3334. if (isValidImage && self.filestack[ind]) {
  3335. self._raise('fileimageresized', [pid, ind]);
  3336. }
  3337. counter.val++;
  3338. if (counter.val === numImgs) {
  3339. self._raise('fileimagesresized');
  3340. }
  3341. if (!isValidImage) {
  3342. throwError(self.msgImageResizeError, {id: pid, 'index': ind}, 'fileimageresizeerror');
  3343. return;
  3344. }
  3345. }
  3346. type = type || self.resizeDefaultImageType;
  3347. chkWidth = width > maxWidth;
  3348. chkHeight = height > maxHeight;
  3349. if (self.resizePreference === 'width') {
  3350. ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1);
  3351. } else {
  3352. ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1);
  3353. }
  3354. self._resetCanvas();
  3355. width *= ratio;
  3356. height *= ratio;
  3357. canvas.width = width;
  3358. canvas.height = height;
  3359. try {
  3360. context.drawImage(img, 0, 0, width, height);
  3361. dataURI = canvas.toDataURL(type, self.resizeQuality);
  3362. if (exifObj) {
  3363. exifStr = window.piexif.dump(exifObj);
  3364. dataURI = window.piexif.insert(exifStr, dataURI);
  3365. }
  3366. blob = $h.dataURI2Blob(dataURI);
  3367. self.filestack[ind] = blob;
  3368. self._raise('fileimageresized', [pid, ind]);
  3369. counter.val++;
  3370. if (counter.val === numImgs) {
  3371. self._raise('fileimagesresized', [undefined, undefined]);
  3372. }
  3373. if (!(blob instanceof Blob)) {
  3374. throwError(self.msgImageResizeError, {id: pid, 'index': ind}, 'fileimageresizeerror');
  3375. }
  3376. }
  3377. catch (err) {
  3378. counter.val++;
  3379. if (counter.val === numImgs) {
  3380. self._raise('fileimagesresized', [undefined, undefined]);
  3381. }
  3382. msg = self.msgImageResizeException.replace('{errors}', err.message);
  3383. throwError(msg, {id: pid, 'index': ind}, 'fileimageresizeexception');
  3384. }
  3385. },
  3386. _initBrowse: function ($container) {
  3387. var self = this;
  3388. if (self.showBrowse) {
  3389. self.$btnFile = $container.find('.btn-file');
  3390. self.$btnFile.append(self.$element);
  3391. } else {
  3392. self.$element.hide();
  3393. }
  3394. },
  3395. _initCaption: function () {
  3396. var self = this, cap = self.initialCaption || '';
  3397. if (self.overwriteInitial || $h.isEmpty(cap)) {
  3398. self.$caption.val('');
  3399. return false;
  3400. }
  3401. self._setCaption(cap);
  3402. return true;
  3403. },
  3404. _setCaption: function (content, isError) {
  3405. var self = this, title, out, icon, n, cap, stack = self.getFileStack();
  3406. if (!self.$caption.length) {
  3407. return;
  3408. }
  3409. self.$captionContainer.removeClass('icon-visible');
  3410. if (isError) {
  3411. title = $('<div>' + self.msgValidationError + '</div>').text();
  3412. n = stack.length;
  3413. if (n) {
  3414. cap = n === 1 && stack[0] ? self._getFileNames()[0] : self._getMsgSelected(n);
  3415. } else {
  3416. cap = self._getMsgSelected(self.msgNo);
  3417. }
  3418. out = $h.isEmpty(content) ? cap : content;
  3419. icon = '<span class="' + self.msgValidationErrorClass + '">' + self.msgValidationErrorIcon + '</span>';
  3420. } else {
  3421. if ($h.isEmpty(content)) {
  3422. return;
  3423. }
  3424. title = $('<div>' + content + '</div>').text();
  3425. out = title;
  3426. icon = self._getLayoutTemplate('fileIcon');
  3427. }
  3428. self.$captionContainer.addClass('icon-visible');
  3429. self.$caption.attr('title', title).val(out);
  3430. self.$captionIcon.html(icon);
  3431. },
  3432. _createContainer: function () {
  3433. var self = this, attribs = {"class": 'file-input file-input-new' + (self.rtl ? ' kv-rtl' : '')},
  3434. $container = $(document.createElement("div")).attr(attribs).html(self._renderMain());
  3435. self.$element.before($container);
  3436. self._initBrowse($container);
  3437. if (self.theme) {
  3438. $container.addClass('theme-' + self.theme);
  3439. }
  3440. return $container;
  3441. },
  3442. _refreshContainer: function () {
  3443. var self = this, $container = self.$container;
  3444. $container.before(self.$element);
  3445. $container.html(self._renderMain());
  3446. self._initBrowse($container);
  3447. self._validateDisabled();
  3448. },
  3449. _validateDisabled: function () {
  3450. var self = this;
  3451. self.$caption.attr({readonly: self.isDisabled});
  3452. },
  3453. _renderMain: function () {
  3454. var self = this,
  3455. dropCss = (self.isAjaxUpload && self.dropZoneEnabled) ? ' file-drop-zone' : 'file-drop-disabled',
  3456. close = !self.showClose ? '' : self._getLayoutTemplate('close'),
  3457. preview = !self.showPreview ? '' : self._getLayoutTemplate('preview')
  3458. .setTokens({'class': self.previewClass, 'dropClass': dropCss}),
  3459. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  3460. caption = self.captionTemplate.setTokens({'class': css + ' kv-fileinput-caption'});
  3461. return self.mainTemplate.setTokens({
  3462. 'class': self.mainClass + (!self.showBrowse && self.showCaption ? ' no-browse' : ''),
  3463. 'preview': preview,
  3464. 'close': close,
  3465. 'caption': caption,
  3466. 'upload': self._renderButton('upload'),
  3467. 'remove': self._renderButton('remove'),
  3468. 'cancel': self._renderButton('cancel'),
  3469. 'browse': self._renderButton('browse')
  3470. });
  3471. },
  3472. _renderButton: function (type) {
  3473. var self = this, tmplt = self._getLayoutTemplate('btnDefault'), css = self[type + 'Class'],
  3474. title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'],
  3475. status = self.isDisabled ? ' disabled' : '', btnType = 'button';
  3476. switch (type) {
  3477. case 'remove':
  3478. if (!self.showRemove) {
  3479. return '';
  3480. }
  3481. break;
  3482. case 'cancel':
  3483. if (!self.showCancel) {
  3484. return '';
  3485. }
  3486. css += ' kv-hidden';
  3487. break;
  3488. case 'upload':
  3489. if (!self.showUpload) {
  3490. return '';
  3491. }
  3492. if (self.isAjaxUpload && !self.isDisabled) {
  3493. tmplt = self._getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl);
  3494. } else {
  3495. btnType = 'submit';
  3496. }
  3497. break;
  3498. case 'browse':
  3499. if (!self.showBrowse) {
  3500. return '';
  3501. }
  3502. tmplt = self._getLayoutTemplate('btnBrowse');
  3503. break;
  3504. default:
  3505. return '';
  3506. }
  3507. css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button';
  3508. if (!$h.isEmpty(label)) {
  3509. label = ' <span class="' + self.buttonLabelClass + '">' + label + '</span>';
  3510. }
  3511. return tmplt.setTokens({
  3512. 'type': btnType, 'css': css, 'title': title, 'status': status, 'icon': icon, 'label': label
  3513. });
  3514. },
  3515. _renderThumbProgress: function () {
  3516. var self = this;
  3517. return '<div class="file-thumb-progress kv-hidden">' +
  3518. self.progressTemplate.setTokens({'percent': '0', 'status': self.msgUploadBegin}) +
  3519. '</div>';
  3520. },
  3521. _renderFileFooter: function (caption, size, width, isError) {
  3522. var self = this, config = self.fileActionSettings, rem = config.showRemove, drg = config.showDrag,
  3523. upl = config.showUpload, zoom = config.showZoom, out,
  3524. template = self._getLayoutTemplate('footer'), tInd = self._getLayoutTemplate('indicator'),
  3525. ind = isError ? config.indicatorError : config.indicatorNew,
  3526. title = isError ? config.indicatorErrorTitle : config.indicatorNewTitle,
  3527. indicator = tInd.setTokens({'indicator': ind, 'indicatorTitle': title});
  3528. size = self._getSize(size);
  3529. if (self.isAjaxUpload) {
  3530. out = template.setTokens({
  3531. 'actions': self._renderFileActions(upl, false, rem, zoom, drg, false, false, false),
  3532. 'caption': caption,
  3533. 'size': size,
  3534. 'width': width,
  3535. 'progress': self._renderThumbProgress(),
  3536. 'indicator': indicator
  3537. });
  3538. } else {
  3539. out = template.setTokens({
  3540. 'actions': self._renderFileActions(false, false, false, zoom, drg, false, false, false),
  3541. 'caption': caption,
  3542. 'size': size,
  3543. 'width': width,
  3544. 'progress': '',
  3545. 'indicator': indicator
  3546. });
  3547. }
  3548. out = $h.replaceTags(out, self.previewThumbTags);
  3549. return out;
  3550. },
  3551. _renderFileActions: function (showUpl, showDwn, showDel, showZoom, showDrag, disabled, url, key, isInit, dUrl, dFile) {
  3552. if (!showUpl && !showDwn && !showDel && !showZoom && !showDrag) {
  3553. return '';
  3554. }
  3555. var self = this, vUrl = url === false ? '' : ' data-url="' + url + '"',
  3556. vKey = key === false ? '' : ' data-key="' + key + '"', btnDelete = '', btnUpload = '', btnDownload = '',
  3557. btnZoom = '', btnDrag = '', css, template = self._getLayoutTemplate('actions'),
  3558. config = self.fileActionSettings,
  3559. otherButtons = self.otherActionButtons.setTokens({'dataKey': vKey, 'key': key}),
  3560. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  3561. if (showDel) {
  3562. btnDelete = self._getLayoutTemplate('actionDelete').setTokens({
  3563. 'removeClass': removeClass,
  3564. 'removeIcon': config.removeIcon,
  3565. 'removeTitle': config.removeTitle,
  3566. 'dataUrl': vUrl,
  3567. 'dataKey': vKey,
  3568. 'key': key
  3569. });
  3570. }
  3571. if (showUpl) {
  3572. btnUpload = self._getLayoutTemplate('actionUpload').setTokens({
  3573. 'uploadClass': config.uploadClass,
  3574. 'uploadIcon': config.uploadIcon,
  3575. 'uploadTitle': config.uploadTitle
  3576. });
  3577. }
  3578. if (showDwn) {
  3579. btnDownload = self._getLayoutTemplate('actionDownload').setTokens({
  3580. 'downloadClass': config.downloadClass,
  3581. 'downloadIcon': config.downloadIcon,
  3582. 'downloadTitle': config.downloadTitle,
  3583. 'downloadUrl': dUrl || self.initialPreviewDownloadUrl
  3584. });
  3585. btnDownload = btnDownload.setTokens({'filename': dFile, 'key': key});
  3586. }
  3587. if (showZoom) {
  3588. btnZoom = self._getLayoutTemplate('actionZoom').setTokens({
  3589. 'zoomClass': config.zoomClass,
  3590. 'zoomIcon': config.zoomIcon,
  3591. 'zoomTitle': config.zoomTitle
  3592. });
  3593. }
  3594. if (showDrag && isInit) {
  3595. css = 'drag-handle-init ' + config.dragClass;
  3596. btnDrag = self._getLayoutTemplate('actionDrag').setTokens({
  3597. 'dragClass': css,
  3598. 'dragTitle': config.dragTitle,
  3599. 'dragIcon': config.dragIcon
  3600. });
  3601. }
  3602. return template.setTokens({
  3603. 'delete': btnDelete,
  3604. 'upload': btnUpload,
  3605. 'download': btnDownload,
  3606. 'zoom': btnZoom,
  3607. 'drag': btnDrag,
  3608. 'other': otherButtons
  3609. });
  3610. },
  3611. _browse: function (e) {
  3612. var self = this;
  3613. self._raise('filebrowse');
  3614. if (e && e.isDefaultPrevented()) {
  3615. return;
  3616. }
  3617. if (self.isError && !self.isAjaxUpload) {
  3618. self.clear();
  3619. }
  3620. self.$captionContainer.focus();
  3621. },
  3622. _filterDuplicate: function (file, files, fileIds) {
  3623. var self = this, fileId = self._getFileId(file);
  3624. if (fileId && fileIds && fileIds.indexOf(fileId) > -1) {
  3625. return;
  3626. }
  3627. if (!fileIds) {
  3628. fileIds = [];
  3629. }
  3630. files.push(file);
  3631. fileIds.push(fileId);
  3632. },
  3633. _change: function (e) {
  3634. var self = this, $el = self.$element;
  3635. if (!self.isAjaxUpload && $h.isEmpty($el.val()) && self.fileInputCleared) { // IE 11 fix
  3636. self.fileInputCleared = false;
  3637. return;
  3638. }
  3639. self.fileInputCleared = false;
  3640. var tfiles = [], msg, total, isDragDrop = arguments.length > 1, isAjaxUpload = self.isAjaxUpload, n, len,
  3641. files = isDragDrop ? e.originalEvent.dataTransfer.files : $el.get(0).files, ctr = self.filestack.length,
  3642. isSingleUpload = $h.isEmpty($el.attr('multiple')), flagSingle = (isSingleUpload && ctr > 0),
  3643. folders = 0, fileIds = self._getFileIds(), throwError = function (mesg, file, previewId, index) {
  3644. var p1 = $.extend(true, {}, self._getOutData({}, {}, files), {id: previewId, index: index}),
  3645. p2 = {id: previewId, index: index, file: file, files: files};
  3646. return self.isAjaxUpload ? self._showUploadError(mesg, p1) : self._showError(mesg, p2);
  3647. };
  3648. self.reader = null;
  3649. self._resetUpload();
  3650. self._hideFileIcon();
  3651. if (self.isAjaxUpload) {
  3652. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  3653. }
  3654. if (isDragDrop) {
  3655. $.each(files, function (i, f) {
  3656. if (f && !f.type && f.size !== undefined && f.size % 4096 === 0) {
  3657. folders++;
  3658. } else {
  3659. self._filterDuplicate(f, tfiles, fileIds);
  3660. }
  3661. });
  3662. } else {
  3663. if (e.target && e.target.files === undefined) {
  3664. files = e.target.value ? [{name: e.target.value.replace(/^.+\\/, '')}] : [];
  3665. } else {
  3666. files = e.target.files || {};
  3667. }
  3668. if (isAjaxUpload) {
  3669. $.each(files, function (i, f) {
  3670. self._filterDuplicate(f, tfiles, fileIds);
  3671. });
  3672. } else {
  3673. tfiles = files;
  3674. }
  3675. }
  3676. if ($h.isEmpty(tfiles) || tfiles.length === 0) {
  3677. if (!isAjaxUpload) {
  3678. self.clear();
  3679. }
  3680. self._showFolderError(folders);
  3681. self._raise('fileselectnone');
  3682. return;
  3683. }
  3684. self._resetErrors();
  3685. len = tfiles.length;
  3686. total = self._getFileCount(self.isAjaxUpload ? (self.getFileStack().length + len) : len);
  3687. if (self.maxFileCount > 0 && total > self.maxFileCount) {
  3688. if (!self.autoReplace || len > self.maxFileCount) {
  3689. n = (self.autoReplace && len > self.maxFileCount) ? len : total;
  3690. msg = self.msgFilesTooMany.replace('{m}', self.maxFileCount).replace('{n}', n);
  3691. self.isError = throwError(msg, null, null, null);
  3692. self.$captionContainer.removeClass('icon-visible');
  3693. self._setCaption('', true);
  3694. self.$container.removeClass('file-input-new file-input-ajax-new');
  3695. return;
  3696. }
  3697. if (total > self.maxFileCount) {
  3698. self._resetPreviewThumbs(isAjaxUpload);
  3699. }
  3700. } else {
  3701. if (!isAjaxUpload || flagSingle) {
  3702. self._resetPreviewThumbs(false);
  3703. if (flagSingle) {
  3704. self.clearStack();
  3705. }
  3706. } else {
  3707. if (isAjaxUpload && ctr === 0 && (!self.previewCache.count() || self.overwriteInitial)) {
  3708. self._resetPreviewThumbs(true);
  3709. }
  3710. }
  3711. }
  3712. if (self.isPreviewable) {
  3713. self._readFiles(tfiles);
  3714. } else {
  3715. self._updateFileDetails(1);
  3716. }
  3717. self._showFolderError(folders);
  3718. },
  3719. _abort: function (params) {
  3720. var self = this, data;
  3721. if (self.ajaxAborted && typeof self.ajaxAborted === "object" && self.ajaxAborted.message !== undefined) {
  3722. data = $.extend(true, {}, self._getOutData(), params);
  3723. data.abortData = self.ajaxAborted.data || {};
  3724. data.abortMessage = self.ajaxAborted.message;
  3725. self._setProgress(101, self.$progress, self.msgCancelled);
  3726. self._showUploadError(self.ajaxAborted.message, data, 'filecustomerror');
  3727. self.cancel();
  3728. return true;
  3729. }
  3730. return !!self.ajaxAborted;
  3731. },
  3732. _resetFileStack: function () {
  3733. var self = this, i = 0, newstack = [], newnames = [], newids = [];
  3734. self._getThumbs().each(function () {
  3735. var $thumb = $(this), ind = $thumb.attr('data-fileindex'), file = self.filestack[ind],
  3736. pid = $thumb.attr('id'), newId;
  3737. if (ind === '-1' || ind === -1) {
  3738. return;
  3739. }
  3740. if (file !== undefined) {
  3741. newstack[i] = file;
  3742. newnames[i] = self._getFileName(file);
  3743. newids[i] = self._getFileId(file);
  3744. $thumb.attr({'id': self.previewInitId + '-' + i, 'data-fileindex': i});
  3745. i++;
  3746. } else {
  3747. newId = 'uploaded-' + $h.uniqId();
  3748. $thumb.attr({'id': newId, 'data-fileindex': '-1'});
  3749. self.$preview.find('#zoom-' + pid).attr('id', 'zoom-' + newId);
  3750. }
  3751. });
  3752. self.filestack = newstack;
  3753. self.filenames = newnames;
  3754. self.fileids = newids;
  3755. },
  3756. _isFileSelectionValid: function (cnt) {
  3757. var self = this;
  3758. cnt = cnt || 0;
  3759. if (self.required && !self.getFilesCount()) {
  3760. self.$errorContainer.html('');
  3761. self._showUploadError(self.msgFileRequired);
  3762. return false;
  3763. }
  3764. if (self.minFileCount > 0 && self._getFileCount(cnt) < self.minFileCount) {
  3765. self._noFilesError({});
  3766. return false;
  3767. }
  3768. return true;
  3769. },
  3770. clearStack: function () {
  3771. var self = this;
  3772. self.filestack = [];
  3773. self.filenames = [];
  3774. self.fileids = [];
  3775. return self.$element;
  3776. },
  3777. updateStack: function (i, file) {
  3778. var self = this;
  3779. self.filestack[i] = file;
  3780. self.filenames[i] = self._getFileName(file);
  3781. self.fileids[i] = file && self._getFileId(file) || null;
  3782. return self.$element;
  3783. },
  3784. addToStack: function (file) {
  3785. var self = this;
  3786. self.filestack.push(file);
  3787. self.filenames.push(self._getFileName(file));
  3788. self.fileids.push(self._getFileId(file));
  3789. return self.$element;
  3790. },
  3791. getFileStack: function (skipNull) {
  3792. var self = this;
  3793. return self.filestack.filter(function (n) {
  3794. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  3795. });
  3796. },
  3797. getFilesCount: function () {
  3798. var self = this, len = self.isAjaxUpload ? self.getFileStack().length : self.$element.get(0).files.length;
  3799. return self._getFileCount(len);
  3800. },
  3801. lock: function () {
  3802. var self = this;
  3803. self._resetErrors();
  3804. self.disable();
  3805. if (self.showRemove) {
  3806. self.$container.find('.fileinput-remove').hide();
  3807. }
  3808. if (self.showCancel) {
  3809. self.$container.find('.fileinput-cancel').show();
  3810. }
  3811. self._raise('filelock', [self.filestack, self._getExtraData()]);
  3812. return self.$element;
  3813. },
  3814. unlock: function (reset) {
  3815. var self = this;
  3816. if (reset === undefined) {
  3817. reset = true;
  3818. }
  3819. self.enable();
  3820. if (self.showCancel) {
  3821. self.$container.find('.fileinput-cancel').hide();
  3822. }
  3823. if (self.showRemove) {
  3824. self.$container.find('.fileinput-remove').show();
  3825. }
  3826. if (reset) {
  3827. self._resetFileStack();
  3828. }
  3829. self._raise('fileunlock', [self.filestack, self._getExtraData()]);
  3830. return self.$element;
  3831. },
  3832. cancel: function () {
  3833. var self = this, xhr = self.ajaxRequests, len = xhr.length, i;
  3834. if (len > 0) {
  3835. for (i = 0; i < len; i += 1) {
  3836. self.cancelling = true;
  3837. xhr[i].abort();
  3838. }
  3839. }
  3840. self._setProgressCancelled();
  3841. self._getThumbs().each(function () {
  3842. var $thumb = $(this), ind = $thumb.attr('data-fileindex');
  3843. $thumb.removeClass('file-uploading');
  3844. if (self.filestack[ind] !== undefined) {
  3845. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  3846. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  3847. }
  3848. self.unlock();
  3849. });
  3850. return self.$element;
  3851. },
  3852. clear: function () {
  3853. var self = this, cap;
  3854. if (!self._raise('fileclear')) {
  3855. return;
  3856. }
  3857. self.$btnUpload.removeAttr('disabled');
  3858. self._getThumbs().find('video,audio,img').each(function () {
  3859. $h.cleanMemory($(this));
  3860. });
  3861. self._resetUpload();
  3862. self.clearStack();
  3863. self._clearFileInput();
  3864. self._resetErrors(true);
  3865. if (self._hasInitialPreview()) {
  3866. self._showFileIcon();
  3867. self._resetPreview();
  3868. self._initPreviewActions();
  3869. self.$container.removeClass('file-input-new');
  3870. } else {
  3871. self._getThumbs().each(function () {
  3872. self._clearObjects($(this));
  3873. });
  3874. if (self.isAjaxUpload) {
  3875. self.previewCache.data = {};
  3876. }
  3877. self.$preview.html('');
  3878. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  3879. self.$caption.attr('title', '').val(cap);
  3880. $h.addCss(self.$container, 'file-input-new');
  3881. self._validateDefaultPreview();
  3882. }
  3883. if (self.$container.find($h.FRAMES).length === 0) {
  3884. if (!self._initCaption()) {
  3885. self.$captionContainer.removeClass('icon-visible');
  3886. }
  3887. }
  3888. self._hideFileIcon();
  3889. self._raise('filecleared');
  3890. self.$captionContainer.focus();
  3891. self._setFileDropZoneTitle();
  3892. return self.$element;
  3893. },
  3894. reset: function () {
  3895. var self = this;
  3896. if (!self._raise('filereset')) {
  3897. return;
  3898. }
  3899. self._resetPreview();
  3900. self.$container.find('.fileinput-filename').text('');
  3901. $h.addCss(self.$container, 'file-input-new');
  3902. if (self.getFrames().length || self.isAjaxUpload && self.dropZoneEnabled) {
  3903. self.$container.removeClass('file-input-new');
  3904. }
  3905. self.clearStack();
  3906. self.formdata = {};
  3907. self._setFileDropZoneTitle();
  3908. return self.$element;
  3909. },
  3910. disable: function () {
  3911. var self = this;
  3912. self.isDisabled = true;
  3913. self._raise('filedisabled');
  3914. self.$element.attr('disabled', 'disabled');
  3915. self.$container.find(".kv-fileinput-caption").addClass("file-caption-disabled");
  3916. self.$container.find(".fileinput-remove, .fileinput-upload, .file-preview-frame button")
  3917. .attr("disabled", true);
  3918. $h.addCss(self.$container.find('.btn-file'), 'disabled');
  3919. self._initDragDrop();
  3920. return self.$element;
  3921. },
  3922. enable: function () {
  3923. var self = this;
  3924. self.isDisabled = false;
  3925. self._raise('fileenabled');
  3926. self.$element.removeAttr('disabled');
  3927. self.$container.find(".kv-fileinput-caption").removeClass("file-caption-disabled");
  3928. self.$container.find(".fileinput-remove, .fileinput-upload, .file-preview-frame button")
  3929. .removeAttr("disabled");
  3930. self.$container.find('.btn-file').removeClass('disabled');
  3931. self._initDragDrop();
  3932. return self.$element;
  3933. },
  3934. upload: function () {
  3935. var self = this, totLen = self.getFileStack().length, i, outData, len,
  3936. hasExtraData = !$.isEmptyObject(self._getExtraData());
  3937. if (!self.isAjaxUpload || self.isDisabled || !self._isFileSelectionValid(totLen)) {
  3938. return;
  3939. }
  3940. self._resetUpload();
  3941. if (totLen === 0 && !hasExtraData) {
  3942. self._showUploadError(self.msgUploadEmpty);
  3943. return;
  3944. }
  3945. self.$progress.show();
  3946. self.uploadCount = 0;
  3947. self.uploadStatus = {};
  3948. self.uploadLog = [];
  3949. self.lock();
  3950. self._setProgress(2);
  3951. if (totLen === 0 && hasExtraData) {
  3952. self._uploadExtraOnly();
  3953. return;
  3954. }
  3955. len = self.filestack.length;
  3956. self.hasInitData = false;
  3957. if (self.uploadAsync) {
  3958. outData = self._getOutData();
  3959. self._raise('filebatchpreupload', [outData]);
  3960. self.fileBatchCompleted = false;
  3961. self.uploadCache = {content: [], config: [], tags: [], append: true};
  3962. self.uploadAsyncCount = self.getFileStack().length;
  3963. for (i = 0; i < len; i++) {
  3964. self.uploadCache.content[i] = null;
  3965. self.uploadCache.config[i] = null;
  3966. self.uploadCache.tags[i] = null;
  3967. }
  3968. self.$preview.find('.file-preview-initial').removeClass($h.SORT_CSS);
  3969. self._initSortable();
  3970. self.cacheInitialPreview = self.getPreview();
  3971. for (i = 0; i < len; i++) {
  3972. if (self.filestack[i]) {
  3973. self._uploadSingle(i, true);
  3974. }
  3975. }
  3976. return;
  3977. }
  3978. self._uploadBatch();
  3979. return self.$element;
  3980. },
  3981. destroy: function () {
  3982. var self = this, $form = self.$form, $cont = self.$container, $el = self.$element, ns = self.namespace;
  3983. $(document).off(ns);
  3984. $(window).off(ns);
  3985. if ($form && $form.length) {
  3986. $form.off(ns);
  3987. }
  3988. if (self.isAjaxUpload) {
  3989. self._clearFileInput();
  3990. }
  3991. self._cleanup();
  3992. self._initPreviewCache();
  3993. $el.insertBefore($cont).off(ns).removeData();
  3994. $cont.off().remove();
  3995. return $el;
  3996. },
  3997. refresh: function (options, triggerChange) {
  3998. var self = this, $el = self.$element;
  3999. if (typeof options !== 'object' || $h.isEmpty(options)) {
  4000. options = self.options;
  4001. } else {
  4002. options = $.extend(true, {}, self.options, options);
  4003. }
  4004. self._init(options, true);
  4005. self._listen();
  4006. if (triggerChange) {
  4007. $el.trigger('change' + self.namespace);
  4008. }
  4009. return $el;
  4010. },
  4011. zoom: function (frameId) {
  4012. var self = this, $frame = self._getFrame(frameId), $modal = self.$modal;
  4013. if (!$frame) {
  4014. return;
  4015. }
  4016. $h.initModal($modal);
  4017. $modal.html(self._getModalContent());
  4018. self._setZoomContent($frame);
  4019. $modal.modal('show');
  4020. self._initZoomButtons();
  4021. },
  4022. getExif: function (frameId) {
  4023. var self = this, $frame = self._getFrame(frameId);
  4024. return $frame && $frame.data('exif') || null;
  4025. },
  4026. getFrames: function (cssFilter) {
  4027. var self = this;
  4028. cssFilter = cssFilter || '';
  4029. return self.$preview.find($h.FRAMES + cssFilter);
  4030. },
  4031. getPreview: function () {
  4032. var self = this;
  4033. return {
  4034. content: self.initialPreview,
  4035. config: self.initialPreviewConfig,
  4036. tags: self.initialPreviewThumbTags
  4037. };
  4038. }
  4039. };
  4040. $.fn.fileinput = function (option) {
  4041. if (!$h.hasFileAPISupport() && !$h.isIE(9)) {
  4042. return;
  4043. }
  4044. var args = Array.apply(null, arguments), retvals = [];
  4045. args.shift();
  4046. this.each(function () {
  4047. var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option,
  4048. theme = options.theme || self.data('theme'), l = {}, t = {},
  4049. lang = options.language || self.data('language') || $.fn.fileinput.defaults.language || 'en', opt;
  4050. if (!data) {
  4051. if (theme) {
  4052. t = $.fn.fileinputThemes[theme] || {};
  4053. }
  4054. if (lang !== 'en' && !$h.isEmpty($.fn.fileinputLocales[lang])) {
  4055. l = $.fn.fileinputLocales[lang] || {};
  4056. }
  4057. opt = $.extend(true, {}, $.fn.fileinput.defaults, t, $.fn.fileinputLocales.en, l, options, self.data());
  4058. data = new FileInput(this, opt);
  4059. self.data('fileinput', data);
  4060. }
  4061. if (typeof option === 'string') {
  4062. retvals.push(data[option].apply(data, args));
  4063. }
  4064. });
  4065. switch (retvals.length) {
  4066. case 0:
  4067. return this;
  4068. case 1:
  4069. return retvals[0];
  4070. default:
  4071. return retvals;
  4072. }
  4073. };
  4074. $.fn.fileinput.defaults = {
  4075. language: 'en',
  4076. showCaption: true,
  4077. showBrowse: true,
  4078. showPreview: true,
  4079. showRemove: true,
  4080. showUpload: true,
  4081. showCancel: true,
  4082. showClose: true,
  4083. showUploadedThumbs: true,
  4084. browseOnZoneClick: false,
  4085. autoReplace: false,
  4086. autoOrientImage: true, // for JPEG images based on EXIF orientation tag
  4087. required: false,
  4088. rtl: false,
  4089. hideThumbnailContent: false,
  4090. generateFileId: null,
  4091. previewClass: '',
  4092. captionClass: '',
  4093. frameClass: 'krajee-default',
  4094. mainClass: 'file-caption-main',
  4095. mainTemplate: null,
  4096. purifyHtml: true,
  4097. fileSizeGetter: null,
  4098. initialCaption: '',
  4099. initialPreview: [],
  4100. initialPreviewDelimiter: '*$$*',
  4101. initialPreviewAsData: false,
  4102. initialPreviewFileType: 'image',
  4103. initialPreviewConfig: [],
  4104. initialPreviewThumbTags: [],
  4105. previewThumbTags: {},
  4106. initialPreviewShowDelete: true,
  4107. initialPreviewDownloadUrl: '',
  4108. removeFromPreviewOnError: false,
  4109. deleteUrl: '',
  4110. deleteExtraData: {},
  4111. overwriteInitial: true,
  4112. previewZoomButtonIcons: {
  4113. prev: '<i class="glyphicon glyphicon-triangle-left"></i>',
  4114. next: '<i class="glyphicon glyphicon-triangle-right"></i>',
  4115. toggleheader: '<i class="glyphicon glyphicon-resize-vertical"></i>',
  4116. fullscreen: '<i class="glyphicon glyphicon-fullscreen"></i>',
  4117. borderless: '<i class="glyphicon glyphicon-resize-full"></i>',
  4118. close: '<i class="glyphicon glyphicon-remove"></i>'
  4119. },
  4120. previewZoomButtonClasses: {
  4121. prev: 'btn btn-navigate',
  4122. next: 'btn btn-navigate',
  4123. toggleheader: 'btn btn-kv btn-default btn-outline-secondary',
  4124. fullscreen: 'btn btn-kv btn-default btn-outline-secondary',
  4125. borderless: 'btn btn-kv btn-default btn-outline-secondary',
  4126. close: 'btn btn-kv btn-default btn-outline-secondary'
  4127. },
  4128. preferIconicPreview: false,
  4129. preferIconicZoomPreview: false,
  4130. allowedPreviewTypes: undefined,
  4131. allowedPreviewMimeTypes: null,
  4132. allowedFileTypes: null,
  4133. allowedFileExtensions: null,
  4134. defaultPreviewContent: null,
  4135. customLayoutTags: {},
  4136. customPreviewTags: {},
  4137. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  4138. previewFileIconClass: 'file-other-icon',
  4139. previewFileIconSettings: {},
  4140. previewFileExtSettings: {},
  4141. buttonLabelClass: 'hidden-xs',
  4142. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i>&nbsp;',
  4143. browseClass: 'btn btn-primary',
  4144. removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
  4145. removeClass: 'btn btn-default btn-secondary',
  4146. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i>',
  4147. cancelClass: 'btn btn-default btn-secondary',
  4148. uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
  4149. uploadClass: 'btn btn-default btn-secondary',
  4150. uploadUrl: null,
  4151. uploadUrlThumb: null,
  4152. uploadAsync: true,
  4153. uploadExtraData: {},
  4154. zoomModalHeight: 480,
  4155. minImageWidth: null,
  4156. minImageHeight: null,
  4157. maxImageWidth: null,
  4158. maxImageHeight: null,
  4159. resizeImage: false,
  4160. resizePreference: 'width',
  4161. resizeQuality: 0.92,
  4162. resizeDefaultImageType: 'image/jpeg',
  4163. resizeIfSizeMoreThan: 0, // in KB
  4164. minFileSize: 0,
  4165. maxFileSize: 0,
  4166. maxFilePreviewSize: 25600, // 25 MB
  4167. minFileCount: 0,
  4168. maxFileCount: 0,
  4169. validateInitialCount: false,
  4170. msgValidationErrorClass: 'text-danger',
  4171. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  4172. msgErrorClass: 'file-error-message',
  4173. progressThumbClass: "progress-bar bg-success progress-bar-success progress-bar-striped active",
  4174. progressClass: "progress-bar bg-success progress-bar-success progress-bar-striped active",
  4175. progressCompleteClass: "progress-bar bg-success progress-bar-success",
  4176. progressErrorClass: "progress-bar bg-danger progress-bar-danger",
  4177. progressUploadThreshold: 99,
  4178. previewFileType: 'image',
  4179. elCaptionContainer: null,
  4180. elCaptionText: null,
  4181. elPreviewContainer: null,
  4182. elPreviewImage: null,
  4183. elPreviewStatus: null,
  4184. elErrorContainer: null,
  4185. errorCloseButton: '<button type="button" class="close kv-error-close">&times;</button>',
  4186. slugCallback: null,
  4187. dropZoneEnabled: true,
  4188. dropZoneTitleClass: 'file-drop-zone-title',
  4189. fileActionSettings: {},
  4190. otherActionButtons: '',
  4191. textEncoding: 'UTF-8',
  4192. ajaxSettings: {},
  4193. ajaxDeleteSettings: {},
  4194. showAjaxErrorDetails: true,
  4195. mergeAjaxCallbacks: false,
  4196. mergeAjaxDeleteCallbacks: false,
  4197. retryErrorUploads: true
  4198. };
  4199. $.fn.fileinputLocales.en = {
  4200. fileSingle: 'file',
  4201. filePlural: 'files',
  4202. browseLabel: 'Browse &hellip;',
  4203. removeLabel: 'Remove',
  4204. removeTitle: 'Clear selected files',
  4205. cancelLabel: 'Cancel',
  4206. cancelTitle: 'Abort ongoing upload',
  4207. uploadLabel: 'Upload',
  4208. uploadTitle: 'Upload selected files',
  4209. msgNo: 'No',
  4210. msgNoFilesSelected: 'No files selected',
  4211. msgCancelled: 'Cancelled',
  4212. msgPlaceholder: 'Select {files}...',
  4213. msgZoomModalHeading: 'Detailed Preview',
  4214. msgFileRequired: 'You must select a file to upload.',
  4215. msgSizeTooSmall: 'File "{name}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.',
  4216. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
  4217. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
  4218. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
  4219. msgFileNotFound: 'File "{name}" not found!',
  4220. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  4221. msgFileNotReadable: 'File "{name}" is not readable.',
  4222. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  4223. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  4224. msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".',
  4225. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  4226. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  4227. msgFileTypes: {
  4228. 'image': 'image',
  4229. 'html': 'HTML',
  4230. 'text': 'text',
  4231. 'video': 'video',
  4232. 'audio': 'audio',
  4233. 'flash': 'flash',
  4234. 'pdf': 'PDF',
  4235. 'object': 'object'
  4236. },
  4237. msgUploadAborted: 'The file upload was aborted',
  4238. msgUploadThreshold: 'Processing...',
  4239. msgUploadBegin: 'Initializing...',
  4240. msgUploadEnd: 'Done',
  4241. msgUploadEmpty: 'No valid data available for upload.',
  4242. msgUploadError: 'Error',
  4243. msgValidationError: 'Validation Error',
  4244. msgLoading: 'Loading file {index} of {files} &hellip;',
  4245. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  4246. msgSelected: '{n} {files} selected',
  4247. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  4248. msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
  4249. msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
  4250. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
  4251. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
  4252. msgImageResizeError: 'Could not get the image dimensions to resize.',
  4253. msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>',
  4254. msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!',
  4255. msgAjaxProgressError: '{operation} failed',
  4256. ajaxOperations: {
  4257. deleteThumb: 'file delete',
  4258. uploadThumb: 'file upload',
  4259. uploadBatch: 'batch file upload',
  4260. uploadExtra: 'form data upload'
  4261. },
  4262. dropZoneTitle: 'Drag & drop files here &hellip;',
  4263. dropZoneClickTitle: '<br>(or click to select {files})',
  4264. previewZoomButtonTitles: {
  4265. prev: 'View previous file',
  4266. next: 'View next file',
  4267. toggleheader: 'Toggle header',
  4268. fullscreen: 'Toggle full screen',
  4269. borderless: 'Toggle borderless mode',
  4270. close: 'Close detailed preview'
  4271. }
  4272. };
  4273. $.fn.fileinput.Constructor = FileInput;
  4274. /**
  4275. * Convert automatically file inputs with class 'file' into a bootstrap fileinput control.
  4276. */
  4277. $(document).ready(function () {
  4278. var $input = $('input.file[type=file]');
  4279. if ($input.length) {
  4280. $input.fileinput();
  4281. }
  4282. });
  4283. }));