123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697 |
- /*!
- * bootstrap-fileinput v5.0.4
- * http://plugins.krajee.com/file-input
- *
- * Author: Kartik Visweswaran
- * Copyright: 2014 - 2019, Kartik Visweswaran, Krajee.com
- *
- * Licensed under the BSD-3-Clause
- * https://github.com/kartik-v/bootstrap-fileinput/blob/master/LICENSE.md
- */
- (function (factory) {
- 'use strict';
- //noinspection JSUnresolvedVariable
- if (typeof define === 'function' && define.amd) { // jshint ignore:line
- // AMD. Register as an anonymous module.
- define(['jquery'], factory); // jshint ignore:line
- } else { // noinspection JSUnresolvedVariable
- if (typeof module === 'object' && module.exports) { // jshint ignore:line
- // Node/CommonJS
- // noinspection JSUnresolvedVariable
- module.exports = factory(require('jquery')); // jshint ignore:line
- } else {
- // Browser globals
- factory(window.jQuery);
- }
- }
- }(function ($) {
- 'use strict';
- $.fn.fileinputLocales = {};
- $.fn.fileinputThemes = {};
- String.prototype.setTokens = function (replacePairs) {
- var str = this.toString(), key, re;
- for (key in replacePairs) {
- if (replacePairs.hasOwnProperty(key)) {
- re = new RegExp('\{' + key + '\}', 'g');
- str = str.replace(re, replacePairs[key]);
- }
- }
- return str;
- };
- var $h, FileInput;
- // fileinput helper object for all global variables and internal helper methods
- //noinspection JSUnresolvedVariable
- $h = {
- FRAMES: '.kv-preview-thumb',
- SORT_CSS: 'file-sortable',
- OBJECT_PARAMS: '<param name="controller" value="true" />\n' +
- '<param name="allowFullScreen" value="true" />\n' +
- '<param name="allowScriptAccess" value="always" />\n' +
- '<param name="autoPlay" value="false" />\n' +
- '<param name="autoStart" value="false" />\n' +
- '<param name="quality" value="high" />\n',
- DEFAULT_PREVIEW: '<div class="file-preview-other">\n' +
- '<span class="{previewFileIconClass}">{previewFileIcon}</span>\n' +
- '</div>',
- MODAL_ID: 'kvFileinputModal',
- MODAL_EVENTS: ['show', 'shown', 'hide', 'hidden', 'loaded'],
- logMessages: {
- ajaxError: '{status}: {error}. Error Details: {text}.',
- badDroppedFiles: 'Error scanning dropped files!',
- badExifParser: 'Error loading the piexif.js library. {details}',
- badInputType: 'The input "type" must be set to "file" for initializing the "bootstrap-fileinput" plugin.',
- exifWarning: 'To avoid this warning, either set "autoOrientImage" to "false" OR ensure you have loaded ' +
- 'the "piexif.js" library correctly on your page before the "fileinput.js" script.',
- invalidChunkSize: 'Invalid upload chunk size: "{chunkSize}". Resumable uploads are disabled.',
- invalidThumb: 'Invalid thumb frame with id: "{id}".',
- noResumableSupport: 'The browser does not support resumable or chunk uploads.',
- noUploadUrl: 'The "uploadUrl" is not set. Ajax uploads and resumable uploads have been disabled.',
- retryStatus: 'Retrying upload for chunk # {chunk} for {filename}... retry # {retry}.'
- },
- objUrl: window.URL || window.webkitURL,
- now: function () {
- return new Date();
- },
- round: function (num) {
- num = parseFloat(num);
- return isNaN(num) ? 0 : Math.floor(Math.round(num));
- },
- getFileRelativePath: function (file) {
- /** @namespace file.relativePath */
- /** @namespace file.webkitRelativePath */
- return String(file.relativePath || file.webkitRelativePath || $h.getFileName(file) || null);
- },
- getFileId: function (file, generateFileId) {
- var relativePath = $h.getFileRelativePath(file);
- if (typeof generateFileId === 'function') {
- return generateFileId(file);
- }
- if (!file) {
- return null;
- }
- if (!relativePath) {
- return null;
- }
- return (file.size + '_' + relativePath.replace(/\s/img, '_'));
- },
- getElapsed: function (seconds) {
- var delta = seconds, out = '', result = {}, structure = {
- year: 31536000,
- month: 2592000,
- week: 604800, // uncomment row to ignore
- day: 86400, // feel free to add your own row
- hour: 3600,
- minute: 60,
- second: 1
- };
- Object.keys(structure).forEach(function (key) {
- result[key] = Math.floor(delta / structure[key]);
- delta -= result[key] * structure[key];
- });
- $.each(result, function (key, value) {
- if (value > 0) {
- out += (out ? ' ' : '') + value + key.substring(0, 1);
- }
- });
- return out;
- },
- debounce: function (func, delay) {
- var inDebounce;
- return function () {
- var args = arguments, context = this;
- clearTimeout(inDebounce);
- inDebounce = setTimeout(function () {
- func.apply(context, args);
- }, delay);
- };
- },
- stopEvent: function (e) {
- e.stopPropagation();
- e.preventDefault();
- },
- getFileName: function (file) {
- /** @namespace file.fileName */
- return file ? (file.fileName || file.name || '') : ''; // some confusion in different versions of Firefox
- },
- createObjectURL: function (data) {
- if ($h.objUrl && $h.objUrl.createObjectURL && data) {
- return $h.objUrl.createObjectURL(data);
- }
- return '';
- },
- revokeObjectURL: function (data) {
- if ($h.objUrl && $h.objUrl.revokeObjectURL && data) {
- $h.objUrl.revokeObjectURL(data);
- }
- },
- compare: function (input, str, exact) {
- return input !== undefined && (exact ? input === str : input.match(str));
- },
- isIE: function (ver) {
- var div, status;
- // check for IE versions < 11
- if (navigator.appName !== 'Microsoft Internet Explorer') {
- return false;
- }
- if (ver === 10) {
- return new RegExp('msie\\s' + ver, 'i').test(navigator.userAgent);
- }
- div = document.createElement('div');
- div.innerHTML = '<!--[if IE ' + ver + ']> <i></i> <![endif]-->';
- status = div.getElementsByTagName('i').length;
- document.body.appendChild(div);
- div.parentNode.removeChild(div);
- return status;
- },
- canAssignFilesToInput: function () {
- var input = document.createElement('input');
- try {
- input.type = 'file';
- input.files = null;
- return true;
- } catch (err) {
- return false;
- }
- },
- getDragDropFolders: function (items) {
- var i, item, len = items ? items.length : 0, folders = 0;
- if (len > 0 && items[0].webkitGetAsEntry()) {
- for (i = 0; i < len; i++) {
- item = items[i].webkitGetAsEntry();
- if (item && item.isDirectory) {
- folders++;
- }
- }
- }
- return folders;
- },
- initModal: function ($modal) {
- var $body = $('body');
- if ($body.length) {
- $modal.appendTo($body);
- }
- },
- isEmpty: function (value, trim) {
- return value === undefined || value === null || value.length === 0 || (trim && $.trim(value) === '');
- },
- isArray: function (a) {
- return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]';
- },
- ifSet: function (needle, haystack, def) {
- def = def || '';
- return (haystack && typeof haystack === 'object' && needle in haystack) ? haystack[needle] : def;
- },
- cleanArray: function (arr) {
- if (!(arr instanceof Array)) {
- arr = [];
- }
- return arr.filter(function (e) {
- return (e !== undefined && e !== null);
- });
- },
- spliceArray: function (arr, index, reverseOrder) {
- var i, j = 0, out = [], newArr;
- if (!(arr instanceof Array)) {
- return [];
- }
- newArr = $.extend(true, [], arr);
- if (reverseOrder) {
- newArr.reverse();
- }
- for (i = 0; i < newArr.length; i++) {
- if (i !== index) {
- out[j] = newArr[i];
- j++;
- }
- }
- if (reverseOrder) {
- out.reverse();
- }
- return out;
- },
- getNum: function (num, def) {
- def = def || 0;
- if (typeof num === 'number') {
- return num;
- }
- if (typeof num === 'string') {
- num = parseFloat(num);
- }
- return isNaN(num) ? def : num;
- },
- hasFileAPISupport: function () {
- return !!(window.File && window.FileReader);
- },
- hasDragDropSupport: function () {
- var div = document.createElement('div');
- /** @namespace div.draggable */
- /** @namespace div.ondragstart */
- /** @namespace div.ondrop */
- return !$h.isIE(9) &&
- (div.draggable !== undefined || (div.ondragstart !== undefined && div.ondrop !== undefined));
- },
- hasFileUploadSupport: function () {
- return $h.hasFileAPISupport() && window.FormData;
- },
- hasBlobSupport: function () {
- try {
- return !!window.Blob && Boolean(new Blob());
- } catch (e) {
- return false;
- }
- },
- hasArrayBufferViewSupport: function () {
- try {
- return new Blob([new Uint8Array(100)]).size === 100;
- } catch (e) {
- return false;
- }
- },
- hasResumableUploadSupport: function () {
- /** @namespace Blob.prototype.webkitSlice */
- /** @namespace Blob.prototype.mozSlice */
- return $h.hasFileUploadSupport() && $h.hasBlobSupport() && $h.hasArrayBufferViewSupport() &&
- (!!Blob.prototype.webkitSlice || !!Blob.prototype.mozSlice || !!Blob.prototype.slice || false);
- },
- dataURI2Blob: function (dataURI) {
- //noinspection JSUnresolvedVariable
- var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder ||
- window.MSBlobBuilder, canBlob = $h.hasBlobSupport(), byteStr, arrayBuffer, intArray, i, mimeStr, bb,
- canProceed = (canBlob || BlobBuilder) && window.atob && window.ArrayBuffer && window.Uint8Array;
- if (!canProceed) {
- return null;
- }
- if (dataURI.split(',')[0].indexOf('base64') >= 0) {
- byteStr = atob(dataURI.split(',')[1]);
- } else {
- byteStr = decodeURIComponent(dataURI.split(',')[1]);
- }
- arrayBuffer = new ArrayBuffer(byteStr.length);
- intArray = new Uint8Array(arrayBuffer);
- for (i = 0; i < byteStr.length; i += 1) {
- intArray[i] = byteStr.charCodeAt(i);
- }
- mimeStr = dataURI.split(',')[0].split(':')[1].split(';')[0];
- if (canBlob) {
- return new Blob([$h.hasArrayBufferViewSupport() ? intArray : arrayBuffer], {type: mimeStr});
- }
- bb = new BlobBuilder();
- bb.append(arrayBuffer);
- return bb.getBlob(mimeStr);
- },
- arrayBuffer2String: function (buffer) {
- //noinspection JSUnresolvedVariable
- if (window.TextDecoder) {
- // noinspection JSUnresolvedFunction
- return new TextDecoder('utf-8').decode(buffer);
- }
- var array = Array.prototype.slice.apply(new Uint8Array(buffer)), out = '', i = 0, len, c, char2, char3;
- len = array.length;
- while (i < len) {
- c = array[i++];
- switch (c >> 4) { // jshint ignore:line
- case 0:
- case 1:
- case 2:
- case 3:
- case 4:
- case 5:
- case 6:
- case 7:
- // 0xxxxxxx
- out += String.fromCharCode(c);
- break;
- case 12:
- case 13:
- // 110x xxxx 10xx xxxx
- char2 = array[i++];
- out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); // jshint ignore:line
- break;
- case 14:
- // 1110 xxxx 10xx xxxx 10xx xxxx
- char2 = array[i++];
- char3 = array[i++];
- out += String.fromCharCode(((c & 0x0F) << 12) | // jshint ignore:line
- ((char2 & 0x3F) << 6) | // jshint ignore:line
- ((char3 & 0x3F) << 0)); // jshint ignore:line
- break;
- }
- }
- return out;
- },
- isHtml: function (str) {
- var a = document.createElement('div');
- a.innerHTML = str;
- for (var c = a.childNodes, i = c.length; i--;) {
- if (c[i].nodeType === 1) {
- return true;
- }
- }
- return false;
- },
- isSvg: function (str) {
- return str.match(/^\s*<\?xml/i) && (str.match(/<!DOCTYPE svg/i) || str.match(/<svg/i));
- },
- getMimeType: function (signature, contents, type) {
- switch (signature) {
- case 'ffd8ffe0':
- case 'ffd8ffe1':
- case 'ffd8ffe2':
- return 'image/jpeg';
- case '89504E47':
- return 'image/png';
- case '47494638':
- return 'image/gif';
- case '49492a00':
- return 'image/tiff';
- case '52494646':
- return 'image/webp';
- case '66747970':
- return 'video/3gp';
- case '4f676753':
- return 'video/ogg';
- case '1a45dfa3':
- return 'video/mkv';
- case '000001ba':
- case '000001b3':
- return 'video/mpeg';
- case '3026b275':
- return 'video/wmv';
- case '25504446':
- return 'application/pdf';
- case '25215053':
- return 'application/ps';
- case '504b0304':
- case '504b0506':
- case '504b0508':
- return 'application/zip';
- case '377abcaf':
- return 'application/7z';
- case '75737461':
- return 'application/tar';
- case '7801730d':
- return 'application/dmg';
- default:
- switch (signature.substring(0, 6)) {
- case '435753':
- return 'application/x-shockwave-flash';
- case '494433':
- return 'audio/mp3';
- case '425a68':
- return 'application/bzip';
- default:
- switch (signature.substring(0, 4)) {
- case '424d':
- return 'image/bmp';
- case 'fffb':
- return 'audio/mp3';
- case '4d5a':
- return 'application/exe';
- case '1f9d':
- case '1fa0':
- return 'application/zip';
- case '1f8b':
- return 'application/gzip';
- default:
- return contents && !contents.match(
- /[^\u0000-\u007f]/) ? 'application/text-plain' : type;
- }
- }
- }
- },
- addCss: function ($el, css) {
- $el.removeClass(css).addClass(css);
- },
- getElement: function (options, param, value) {
- return ($h.isEmpty(options) || $h.isEmpty(options[param])) ? value : $(options[param]);
- },
- uniqId: function () {
- return Math.round(new Date().getTime()) + '_' + Math.round(Math.random() * 100);
- },
- htmlEncode: function (str, undefVal) {
- if (str === undefined) {
- return undefVal || null;
- }
- return str.replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, ''');
- },
- replaceTags: function (str, tags) {
- var out = str;
- if (!tags) {
- return out;
- }
- $.each(tags, function (key, value) {
- if (typeof value === 'function') {
- value = value();
- }
- out = out.split(key).join(value);
- });
- return out;
- },
- cleanMemory: function ($thumb) {
- var data = $thumb.is('img') ? $thumb.attr('src') : $thumb.find('source').attr('src');
- $h.revokeObjectURL(data);
- },
- findFileName: function (filePath) {
- var sepIndex = filePath.lastIndexOf('/');
- if (sepIndex === -1) {
- sepIndex = filePath.lastIndexOf('\\');
- }
- return filePath.split(filePath.substring(sepIndex, sepIndex + 1)).pop();
- },
- checkFullScreen: function () {
- //noinspection JSUnresolvedVariable
- return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement ||
- document.msFullscreenElement;
- },
- toggleFullScreen: function (maximize) {
- var doc = document, de = doc.documentElement;
- if (de && maximize && !$h.checkFullScreen()) {
- /** @namespace document.requestFullscreen */
- /** @namespace document.msRequestFullscreen */
- /** @namespace document.mozRequestFullScreen */
- /** @namespace document.webkitRequestFullscreen */
- /** @namespace Element.ALLOW_KEYBOARD_INPUT */
- if (de.requestFullscreen) {
- de.requestFullscreen();
- } else {
- if (de.msRequestFullscreen) {
- de.msRequestFullscreen();
- } else {
- if (de.mozRequestFullScreen) {
- de.mozRequestFullScreen();
- } else {
- if (de.webkitRequestFullscreen) {
- de.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
- }
- }
- }
- }
- } else {
- /** @namespace document.exitFullscreen */
- /** @namespace document.msExitFullscreen */
- /** @namespace document.mozCancelFullScreen */
- /** @namespace document.webkitExitFullscreen */
- if (doc.exitFullscreen) {
- doc.exitFullscreen();
- } else {
- if (doc.msExitFullscreen) {
- doc.msExitFullscreen();
- } else {
- if (doc.mozCancelFullScreen) {
- doc.mozCancelFullScreen();
- } else {
- if (doc.webkitExitFullscreen) {
- doc.webkitExitFullscreen();
- }
- }
- }
- }
- }
- },
- moveArray: function (arr, oldIndex, newIndex, reverseOrder) {
- var newArr = $.extend(true, [], arr);
- if (reverseOrder) {
- newArr.reverse();
- }
- if (newIndex >= newArr.length) {
- var k = newIndex - newArr.length;
- while ((k--) + 1) {
- newArr.push(undefined);
- }
- }
- newArr.splice(newIndex, 0, newArr.splice(oldIndex, 1)[0]);
- if (reverseOrder) {
- newArr.reverse();
- }
- return newArr;
- },
- cleanZoomCache: function ($el) {
- var $cache = $el.closest('.kv-zoom-cache-theme');
- if (!$cache.length) {
- $cache = $el.closest('.kv-zoom-cache');
- }
- $cache.remove();
- },
- closeButton: function (css) {
- css = css ? 'close ' + css : 'close';
- return '<button type="button" class="' + css + '" aria-label="Close">\n' +
- ' <span aria-hidden="true">×</span>\n' +
- '</button>';
- },
- getRotation: function (value) {
- switch (value) {
- case 2:
- return 'rotateY(180deg)';
- case 3:
- return 'rotate(180deg)';
- case 4:
- return 'rotate(180deg) rotateY(180deg)';
- case 5:
- return 'rotate(270deg) rotateY(180deg)';
- case 6:
- return 'rotate(90deg)';
- case 7:
- return 'rotate(90deg) rotateY(180deg)';
- case 8:
- return 'rotate(270deg)';
- default:
- return '';
- }
- },
- setTransform: function (el, val) {
- if (!el) {
- return;
- }
- el.style.transform = val;
- el.style.webkitTransform = val;
- el.style['-moz-transform'] = val;
- el.style['-ms-transform'] = val;
- el.style['-o-transform'] = val;
- }
- };
- FileInput = function (element, options) {
- var self = this;
- self.$element = $(element);
- self.$parent = self.$element.parent();
- if (!self._validate()) {
- return;
- }
- self.isPreviewable = $h.hasFileAPISupport();
- self.isIE9 = $h.isIE(9);
- self.isIE10 = $h.isIE(10);
- if (self.isPreviewable || self.isIE9) {
- self._init(options);
- self._listen();
- }
- self.$element.removeClass('file-loading');
- };
- //noinspection JSUnusedGlobalSymbols
- FileInput.prototype = {
- constructor: FileInput,
- _cleanup: function () {
- var self = this;
- self.reader = null;
- self.clearFileStack();
- self.fileBatchCompleted = true;
- self.isError = false;
- self.cancelling = false;
- self.paused = false;
- self.lastProgress = 0;
- self._initAjax();
- },
- _initAjax: function () {
- var self = this;
- self.ajaxQueue = [];
- self.ajaxRequests = [];
- self.ajaxQueueIntervalId = null;
- self.ajaxCurrentThreads = 0;
- self.ajaxAborted = false;
- },
- _init: function (options, refreshMode) {
- var self = this, f, $el = self.$element, $cont, t, tmp;
- self.options = options;
- $.each(options, function (key, value) {
- switch (key) {
- case 'minFileCount':
- case 'maxFileCount':
- case 'minFileSize':
- case 'maxFileSize':
- case 'maxFilePreviewSize':
- case 'resizeImageQuality':
- case 'resizeIfSizeMoreThan':
- case 'progressUploadThreshold':
- case 'initialPreviewCount':
- case 'zoomModalHeight':
- case 'minImageHeight':
- case 'maxImageHeight':
- case 'minImageWidth':
- case 'maxImageWidth':
- self[key] = $h.getNum(value);
- break;
- default:
- self[key] = value;
- break;
- }
- });
- if (self.rtl) { // swap buttons for rtl
- tmp = self.previewZoomButtonIcons.prev;
- self.previewZoomButtonIcons.prev = self.previewZoomButtonIcons.next;
- self.previewZoomButtonIcons.next = tmp;
- }
- // validate chunk threads to not exceed maxAjaxThreads
- if (!isNaN(self.maxAjaxThreads) && self.maxAjaxThreads < self.resumableUploadOptions.maxThreads) {
- self.resumableUploadOptions.maxThreads = self.maxAjaxThreads;
- }
- self._initFileManager();
- if (typeof self.autoOrientImage === 'function') {
- self.autoOrientImage = self.autoOrientImage();
- }
- if (typeof self.autoOrientImageInitial === 'function') {
- self.autoOrientImageInitial = self.autoOrientImageInitial();
- }
- if (!refreshMode) {
- self._cleanup();
- }
- self.$form = $el.closest('form');
- self._initTemplateDefaults();
- self.uploadFileAttr = !$h.isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data';
- t = self._getLayoutTemplate('progress');
- self.progressTemplate = t.replace('{class}', self.progressClass);
- self.progressInfoTemplate = t.replace('{class}', self.progressInfoClass);
- self.progressPauseTemplate = t.replace('{class}', self.progressPauseClass);
- self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass);
- self.progressErrorTemplate = t.replace('{class}', self.progressErrorClass);
- self.isDisabled = $el.attr('disabled') || $el.attr('readonly');
- if (self.isDisabled) {
- $el.attr('disabled', true);
- }
- self.isClickable = self.browseOnZoneClick && self.showPreview &&
- (self.dropZoneEnabled || !$h.isEmpty(self.defaultPreviewContent));
- self.isAjaxUpload = $h.hasFileUploadSupport() && !$h.isEmpty(self.uploadUrl);
- self.dropZoneEnabled = $h.hasDragDropSupport() && self.dropZoneEnabled;
- if (!self.isAjaxUpload) {
- self.dropZoneEnabled = self.dropZoneEnabled && $h.canAssignFilesToInput();
- }
- self.slug = typeof options.slugCallback === 'function' ? options.slugCallback : self._slugDefault;
- self.mainTemplate = self.showCaption ? self._getLayoutTemplate('main1') : self._getLayoutTemplate('main2');
- self.captionTemplate = self._getLayoutTemplate('caption');
- self.previewGenericTemplate = self._getPreviewTemplate('generic');
- if (!self.imageCanvas && self.resizeImage && (self.maxImageWidth || self.maxImageHeight)) {
- self.imageCanvas = document.createElement('canvas');
- self.imageCanvasContext = self.imageCanvas.getContext('2d');
- }
- if ($h.isEmpty($el.attr('id'))) {
- $el.attr('id', $h.uniqId());
- }
- self.namespace = '.fileinput_' + $el.attr('id').replace(/-/g, '_');
- if (self.$container === undefined) {
- self.$container = self._createContainer();
- } else {
- self._refreshContainer();
- }
- $cont = self.$container;
- self.$dropZone = $cont.find('.file-drop-zone');
- self.$progress = $cont.find('.kv-upload-progress');
- self.$btnUpload = $cont.find('.fileinput-upload');
- self.$captionContainer = $h.getElement(options, 'elCaptionContainer', $cont.find('.file-caption'));
- self.$caption = $h.getElement(options, 'elCaptionText', $cont.find('.file-caption-name'));
- if (!$h.isEmpty(self.msgPlaceholder)) {
- f = $el.attr('multiple') ? self.filePlural : self.fileSingle;
- self.$caption.attr('placeholder', self.msgPlaceholder.replace('{files}', f));
- }
- self.$captionIcon = self.$captionContainer.find('.file-caption-icon');
- self.$previewContainer = $h.getElement(options, 'elPreviewContainer', $cont.find('.file-preview'));
- self.$preview = $h.getElement(options, 'elPreviewImage', $cont.find('.file-preview-thumbnails'));
- self.$previewStatus = $h.getElement(options, 'elPreviewStatus', $cont.find('.file-preview-status'));
- self.$errorContainer = $h.getElement(options, 'elErrorContainer',
- self.$previewContainer.find('.kv-fileinput-error'));
- self._validateDisabled();
- if (!$h.isEmpty(self.msgErrorClass)) {
- $h.addCss(self.$errorContainer, self.msgErrorClass);
- }
- if (!refreshMode) {
- self.$errorContainer.hide();
- self.previewInitId = 'preview-' + $h.uniqId();
- self._initPreviewCache();
- self._initPreview(true);
- self._initPreviewActions();
- if (self.$parent.hasClass('file-loading')) {
- self.$container.insertBefore(self.$parent);
- self.$parent.remove();
- }
- } else {
- if (!self._errorsExist()) {
- self.$errorContainer.hide();
- }
- }
- self._setFileDropZoneTitle();
- if ($el.attr('disabled')) {
- self.disable();
- }
- self._initZoom();
- if (self.hideThumbnailContent) {
- $h.addCss(self.$preview, 'hide-content');
- }
- },
- _initFileManager: function () {
- var self = this;
- self.fileManager = {
- stack: {},
- processed: [],
- errors: [],
- loadedImages: {},
- totalImages: 0,
- totalFiles: null,
- totalSize: null,
- uploadedSize: 0,
- stats: {},
- initStats: function (id) {
- var data = {started: $h.now().getTime()};
- if (id) {
- self.fileManager.stats[id] = data;
- } else {
- self.fileManager.stats = data;
- }
- },
- getUploadStats: function (id, loaded, total) {
- var fm = self.fileManager, started = id ? fm.stats[id] && fm.stats[id].started || null : null;
- if (!started) {
- started = $h.now().getTime();
- }
- var elapsed = ($h.now().getTime() - started) / 1000,
- speeds = ['B/s', 'KB/s', 'MB/s', 'GB/s', 'TB/s', 'PB/s', 'EB/s', 'ZB/s', 'YB/s'],
- bps = elapsed ? loaded / elapsed : 0, bitrate = self._getSize(bps, speeds),
- pendingBytes = total - loaded,
- out = {
- fileId: id,
- started: started,
- elapsed: elapsed,
- loaded: loaded,
- total: total,
- bps: bps,
- bitrate: bitrate,
- pendingBytes: pendingBytes
- };
- if (id) {
- fm.stats[id] = out;
- } else {
- fm.stats = out;
- }
- return out;
- },
- exists: function (id) {
- return $.inArray(id, self.fileManager.getIdList()) !== -1;
- },
- count: function () {
- return self.fileManager.getIdList().length;
- },
- total: function () {
- var fm = self.fileManager;
- if (!fm.totalFiles) {
- fm.totalFiles = fm.count();
- }
- return fm.totalFiles;
- },
- getTotalSize: function () {
- var fm = self.fileManager;
- if (fm.totalSize) {
- return fm.totalSize;
- }
- fm.totalSize = 0;
- $.each(self.fileManager.stack, function (id, f) {
- var size = parseFloat(f.size);
- fm.totalSize += isNaN(size) ? 0 : size;
- });
- return fm.totalSize;
- },
- add: function (file, id) {
- if (!id) {
- id = self.fileManager.getId(file);
- }
- if (!id) {
- return;
- }
- self.fileManager.stack[id] = {
- file: file,
- name: $h.getFileName(file),
- relativePath: $h.getFileRelativePath(file),
- size: file.size,
- nameFmt: self._getFileName(file, ''),
- sizeFmt: self._getSize(file.size)
- };
- },
- remove: function ($thumb) {
- var id = $thumb.attr('data-fileid');
- if (id) {
- self.fileManager.removeFile(id);
- }
- },
- removeFile: function (id) {
- delete self.fileManager.stack[id];
- delete self.fileManager.loadedImages[id];
- },
- move: function (idFrom, idTo) {
- var result = {}, stack = self.fileManager.stack;
- if (!idFrom && !idTo || idFrom === idTo) {
- return;
- }
- $.each(stack, function (k, v) {
- if (k !== idFrom) {
- result[k] = v;
- }
- if (k === idTo) {
- result[idFrom] = stack[idFrom];
- }
- });
- self.fileManager.stack = result;
- },
- list: function () {
- var files = [];
- $.each(self.fileManager.stack, function (k, v) {
- if (v && v.file) {
- files.push(v.file);
- }
- });
- return files;
- },
- isPending: function (id) {
- return $.inArray(id, self.fileManager.processed) === -1 && self.fileManager.exists(id);
- },
- isProcessed: function () {
- var processed = true, fm = self.fileManager;
- $.each(fm.stack, function (id) {
- if (fm.isPending(id)) {
- processed = false;
- }
- });
- return processed;
- },
- clear: function () {
- var fm = self.fileManager;
- fm.totalFiles = null;
- fm.totalSize = null;
- fm.uploadedSize = 0;
- fm.stack = {};
- fm.errors = [];
- fm.processed = [];
- fm.stats = {};
- fm.clearImages();
- },
- clearImages: function () {
- self.fileManager.loadedImages = {};
- self.fileManager.totalImages = 0;
- },
- addImage: function (id, config) {
- self.fileManager.loadedImages[id] = config;
- },
- removeImage: function (id) {
- delete self.fileManager.loadedImages[id];
- },
- getImageIdList: function () {
- return Object.keys(self.fileManager.loadedImages);
- },
- getImageCount: function () {
- return self.fileManager.getImageIdList().length;
- },
- getId: function (file) {
- return self._getFileId(file);
- },
- getIndex: function (id) {
- return self.fileManager.getIdList().indexOf(id);
- },
- getThumb: function (id) {
- var $thumb = null;
- self._getThumbs().each(function () {
- if ($(this).attr('data-fileid') === id) {
- $thumb = $(this);
- }
- });
- return $thumb;
- },
- getThumbIndex: function ($thumb) {
- var id = $thumb.attr('data-fileid');
- return self.fileManager.getIndex(id);
- },
- getIdList: function () {
- return Object.keys(self.fileManager.stack);
- },
- getFile: function (id) {
- return self.fileManager.stack[id] || null;
- },
- getFileName: function (id, fmt) {
- var file = self.fileManager.getFile(id);
- if (!file) {
- return '';
- }
- return fmt ? (file.nameFmt || '') : file.name || '';
- },
- getFirstFile: function () {
- var ids = self.fileManager.getIdList(), id = ids && ids.length ? ids[0] : null;
- return self.fileManager.getFile(id);
- },
- setFile: function (id, file) {
- if (self.fileManager.getFile(id)) {
- self.fileManager.stack[id].file = file;
- } else {
- self.fileManager.add(file, id);
- }
- },
- setProcessed: function (id) {
- self.fileManager.processed.push(id);
- },
- getProgress: function () {
- var total = self.fileManager.total(), processed = self.fileManager.processed.length;
- if (!total) {
- return 0;
- }
- return Math.ceil(processed / total * 100);
- },
- setProgress: function (id, pct) {
- var f = self.fileManager.getFile(id);
- if (!isNaN(pct) && f) {
- f.progress = pct;
- }
- }
- };
- },
- _setUploadData: function (fd, config) {
- var self = this;
- $.each(config, function (key, value) {
- var param = self.uploadParamNames[key] || key;
- if ($h.isArray(value)) {
- fd.append(param, value[0], value[1]);
- } else {
- fd.append(param, value);
- }
- });
- },
- _initResumableUpload: function () {
- var self = this, opts = self.resumableUploadOptions, logs = $h.logMessages;
- if (!self.enableResumableUpload) {
- return;
- }
- if (opts.fallback !== false && typeof opts.fallback !== 'function') {
- opts.fallback = function (s) {
- s._log(logs.noResumableSupport);
- s.enableResumableUpload = false;
- };
- }
- if (!$h.hasResumableUploadSupport() && opts.fallback !== false) {
- opts.fallback(self);
- return;
- }
- if (!self.uploadUrl && self.enableResumableUpload) {
- self._log(logs.noUploadUrl);
- self.enableResumableUpload = false;
- return;
- }
- opts.chunkSize = parseFloat(opts.chunkSize);
- if (opts.chunkSize <= 0 || isNaN(opts.chunkSize)) {
- self._log(logs.invalidChunkSize, {chunkSize: opts.chunkSize});
- self.enableResumableUpload = false;
- return;
- }
- self.resumableManager = {
- init: function (id, f, index) {
- var rm = self.resumableManager, fm = self.fileManager;
- rm.currThreads = 0;
- rm.logs = [];
- rm.stack = [];
- rm.error = '';
- rm.chunkIntervalId = null;
- rm.id = id;
- rm.file = f.file;
- rm.fileName = f.name;
- rm.fileIndex = index;
- rm.completed = false;
- rm.testing = false;
- rm.lastProgress = 0;
- if (self.showPreview) {
- rm.$thumb = fm.getThumb(id) || null;
- rm.$progress = rm.$btnDelete = null;
- if (rm.$thumb && rm.$thumb.length) {
- rm.$progress = rm.$thumb.find('.file-thumb-progress');
- rm.$btnDelete = rm.$thumb.find('.kv-file-remove');
- }
- }
- rm.chunkSize = self.resumableUploadOptions.chunkSize * 1024;
- rm.chunkCount = rm.getTotalChunks();
- },
- logAjaxError: function (jqXHR, textStatus, errorThrown) {
- if (self.resumableUploadOptions.showErrorLog) {
- self._log(logs.ajaxError, {
- status: jqXHR.status,
- error: errorThrown,
- text: jqXHR.responseText || ''
- });
- }
- },
- reset: function () {
- var rm = self.resumableManager;
- rm.processed = {};
- },
- setProcessed: function (status) {
- var rm = self.resumableManager, fm = self.fileManager, id = rm.id, msg,
- $thumb = rm.$thumb, $prog = rm.$progress, hasThumb = $thumb && $thumb.length,
- params = {id: hasThumb ? $thumb.attr('id') : '', index: fm.getIndex(id), fileId: id};
- rm.completed = true;
- rm.lastProgress = 0;
- fm.uploadedSize += rm.file.size;
- if (hasThumb) {
- $thumb.removeClass('file-uploading');
- }
- if (status === 'success') {
- if (self.showPreview) {
- self._setProgress(101, $prog);
- self._setThumbStatus($thumb, 'Success');
- self._initUploadSuccess(rm.processed[id].data, $thumb);
- }
- self.fileManager.removeFile(id);
- delete rm.processed[id];
- self._raise('fileuploaded', [params.id, params.index, params.fileId]);
- if (fm.isProcessed()) {
- self._setProgress(101);
- }
- } else {
- if (self.showPreview) {
- self._setThumbStatus($thumb, 'Error');
- self._setPreviewError($thumb, true);
- self._setProgress(101, $prog, self.msgProgressError);
- self._setProgress(101, self.$progress, self.msgProgressError);
- self.cancelling = true;
- }
- if (!self.$errorContainer.find('li[data-file-id="' + params.fileId + '"]').length) {
- msg = self.msgResumableUploadRetriesExceeded.setTokens({
- file: rm.fileName,
- max: self.resumableUploadOptions.maxRetries,
- error: rm.error
- });
- self._showFileError(msg, params);
- }
- }
- if (fm.isProcessed()) {
- rm.reset();
- }
- },
- check: function () {
- var rm = self.resumableManager, status = true;
- $.each(rm.logs, function (index, value) {
- if (!value) {
- status = false;
- return false;
- }
- });
- if (status) {
- clearInterval(rm.chunkIntervalId);
- rm.setProcessed('success');
- }
- },
- processedResumables: function () {
- var logs = self.resumableManager.logs, i, count = 0;
- if (!logs || !logs.length) {
- return 0;
- }
- for (i = 0; i < logs.length; i++) {
- if (logs[i] === true) {
- count++;
- }
- }
- return count;
- },
- getUploadedSize: function () {
- var rm = self.resumableManager, size = rm.processedResumables() * rm.chunkSize;
- return size > rm.file.size ? rm.file.size : size;
- },
- getTotalChunks: function () {
- var rm = self.resumableManager, chunkSize = parseFloat(rm.chunkSize);
- if (!isNaN(chunkSize) && chunkSize > 0) {
- return Math.ceil(rm.file.size / chunkSize);
- }
- return 0;
- },
- getProgress: function () {
- var rm = self.resumableManager, processed = rm.processedResumables(), total = rm.chunkCount;
- if (total === 0) {
- return 0;
- }
- return Math.ceil(processed / total * 100);
- },
- checkAborted: function (intervalId) {
- if (self.paused || self.cancelling) {
- clearInterval(intervalId);
- self.unlock();
- }
- },
- upload: function () {
- var rm = self.resumableManager, fm = self.fileManager, ids = fm.getIdList(), flag = 'new',
- intervalId;
- intervalId = setInterval(function () {
- var id;
- rm.checkAborted(intervalId);
- if (flag === 'new') {
- self.lock();
- flag = 'processing';
- id = ids.shift();
- fm.initStats(id);
- if (fm.stack[id]) {
- rm.init(id, fm.stack[id], fm.getIndex(id));
- rm.testUpload();
- rm.uploadResumable();
- }
- }
- if (!fm.isPending(id) && rm.completed) {
- flag = 'new';
- }
- if (fm.isProcessed()) {
- var $initThumbs = self.$preview.find('.file-preview-initial');
- if ($initThumbs.length) {
- $h.addCss($initThumbs, $h.SORT_CSS);
- self._initSortable();
- }
- clearInterval(intervalId);
- self._clearFileInput();
- self.unlock();
- setTimeout(function () {
- var data = self.previewCache.data;
- if (data) {
- self.initialPreview = data.content;
- self.initialPreviewConfig = data.config;
- self.initialPreviewThumbTags = data.tags;
- }
- self._raise('filebatchuploadcomplete', [
- self.initialPreview,
- self.initialPreviewConfig,
- self.initialPreviewThumbTags,
- self._getExtraData()
- ]);
- }, self.processDelay);
- }
- }, self.processDelay);
- },
- uploadResumable: function () {
- var i, rm = self.resumableManager, total = rm.chunkCount;
- for (i = 0; i < total; i++) {
- rm.logs[i] = !!(rm.processed[rm.id] && rm.processed[rm.id][i]);
- }
- for (i = 0; i < total; i++) {
- rm.pushAjax(i, 0);
- }
- rm.chunkIntervalId = setInterval(rm.loopAjax, self.queueDelay);
- },
- testUpload: function () {
- var rm = self.resumableManager, opts = self.resumableUploadOptions, fd, f,
- fm = self.fileManager, id = rm.id, fnBefore, fnSuccess, fnError, fnComplete, outData;
- if (!opts.testUrl) {
- rm.testing = false;
- return;
- }
- rm.testing = true;
- fd = new FormData();
- f = fm.stack[id];
- self._setUploadData(fd, {
- fileId: id,
- fileName: f.fileName,
- fileSize: f.size,
- fileRelativePath: f.relativePath,
- chunkSize: rm.chunkSize,
- chunkCount: rm.chunkCount
- });
- fnBefore = function (jqXHR) {
- outData = self._getOutData(fd, jqXHR);
- self._raise('filetestbeforesend', [id, fm, rm, outData]);
- };
- fnSuccess = function (data, textStatus, jqXHR) {
- outData = self._getOutData(fd, jqXHR, data);
- var pNames = self.uploadParamNames, chunksUploaded = pNames.chunksUploaded || 'chunksUploaded',
- params = [id, fm, rm, outData];
- if (!data[chunksUploaded] || !$h.isArray(data[chunksUploaded])) {
- self._raise('filetesterror', params);
- } else {
- if (!rm.processed[id]) {
- rm.processed[id] = {};
- }
- $.each(data[chunksUploaded], function (key, index) {
- rm.logs[index] = true;
- rm.processed[id][index] = true;
- });
- rm.processed[id].data = data;
- self._raise('filetestsuccess', params);
- }
- rm.testing = false;
- };
- fnError = function (jqXHR, textStatus, errorThrown) {
- outData = self._getOutData(fd, jqXHR);
- self._raise('filetestajaxerror', [id, fm, rm, outData]);
- rm.logAjaxError(jqXHR, textStatus, errorThrown);
- rm.testing = false;
- };
- fnComplete = function () {
- self._raise('filetestcomplete', [id, fm, rm, self._getOutData(fd)]);
- rm.testing = false;
- };
- self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, fd, id, rm.fileIndex, opts.testUrl);
- },
- pushAjax: function (index, retry) {
- self.resumableManager.stack.push([index, retry]);
- },
- sendAjax: function (index, retry) {
- var fm = self.fileManager, rm = self.resumableManager, opts = self.resumableUploadOptions, f,
- chunkSize = rm.chunkSize, id = rm.id, file = rm.file, $thumb = rm.$thumb,
- $btnDelete = rm.$btnDelete;
- if (rm.processed[id] && rm.processed[id][index]) {
- return;
- }
- rm.currThreads++;
- if (retry > opts.maxRetries) {
- rm.setProcessed('error');
- return;
- }
- var fd, outData, fnBefore, fnSuccess, fnError, fnComplete, slice = file.slice ? 'slice' :
- (file.mozSlice ? 'mozSlice' : (file.webkitSlice ? 'webkitSlice' : 'slice')),
- blob = file[slice](chunkSize * index, chunkSize * (index + 1));
- fd = new FormData();
- f = fm.stack[id];
- self._setUploadData(fd, {
- chunkCount: rm.chunkCount,
- chunkIndex: index,
- chunkSize: chunkSize,
- chunkSizeStart: chunkSize * index,
- fileBlob: [blob, rm.fileName],
- fileId: id,
- fileName: rm.fileName,
- fileRelativePath: f.relativePath,
- fileSize: file.size,
- retryCount: retry
- });
- if (rm.$progress && rm.$progress.length) {
- rm.$progress.show();
- }
- fnBefore = function (jqXHR) {
- outData = self._getOutData(fd, jqXHR);
- if (self.showPreview) {
- if (!$thumb.hasClass('file-preview-success')) {
- self._setThumbStatus($thumb, 'Loading');
- $h.addCss($thumb, 'file-uploading');
- }
- $btnDelete.attr('disabled', true);
- }
- self._raise('filechunkbeforesend', [id, index, retry, fm, rm, outData]);
- };
- fnSuccess = function (data, textStatus, jqXHR) {
- outData = self._getOutData(fd, jqXHR, data);
- var paramNames = self.uploadParamNames, chunkIndex = paramNames.chunkIndex || 'chunkIndex',
- opts = self.resumableUploadOptions, params = [id, index, retry, fm, rm, outData];
- rm.currThreads--;
- if (data.error) {
- if (opts.showErrorLog) {
- self._log(logs.retryStatus, {
- retry: retry + 1,
- filename: rm.fileName,
- chunk: index
- });
- }
- rm.pushAjax(index, retry + 1);
- rm.error = data.error;
- self._raise('filechunkerror', params);
- } else {
- rm.logs[data[chunkIndex]] = true;
- if (!rm.processed[id]) {
- rm.processed[id] = {};
- }
- rm.processed[id][data[chunkIndex]] = true;
- rm.processed[id].data = data;
- self._raise('filechunksuccess', params);
- rm.check();
- }
- };
- fnError = function (jqXHR, textStatus, errorThrown) {
- outData = self._getOutData(fd, jqXHR);
- rm.currThreads--;
- rm.error = errorThrown;
- rm.logAjaxError(jqXHR, textStatus, errorThrown);
- self._raise('filechunkajaxerror', [id, index, retry, fm, rm, outData]);
- rm.pushAjax(index, retry + 1);
- };
- fnComplete = function () {
- self._raise('filechunkcomplete', [id, index, retry, fm, rm, self._getOutData(fd)]);
- };
- self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, fd, id, rm.fileIndex);
- },
- loopAjax: function () {
- var rm = self.resumableManager;
- if (rm.currThreads < self.resumableUploadOptions.maxThreads && !rm.testing) {
- var arr = rm.stack.shift(), index;
- if (typeof arr !== 'undefined') {
- index = arr[0];
- if (!rm.processed[rm.id] || !rm.processed[rm.id][index]) {
- rm.sendAjax(index, arr[1]);
- } else {
- if (rm.processedResumables() >= rm.getTotalChunks()) {
- rm.setProcessed('success');
- clearInterval(rm.chunkIntervalId);
- }
- }
- }
- }
- }
- };
- self.resumableManager.reset();
- },
- _initTemplateDefaults: function () {
- var self = this, tMain1, tMain2, tPreview, tFileIcon, tClose, tCaption, tBtnDefault, tBtnLink, tBtnBrowse,
- tModalMain, tModal, tProgress, tSize, tFooter, tActions, tActionDelete, tActionUpload, tActionDownload,
- tActionZoom, tActionDrag, tIndicator, tTagBef, tTagBef1, tTagBef2, tTagAft, tGeneric, tHtml, tImage,
- tText, tOffice, tGdocs, tVideo, tAudio, tFlash, tObject, tPdf, tOther, tStyle, tZoomCache, vDefaultDim,
- tStats;
- tMain1 = '{preview}\n' +
- '<div class="kv-upload-progress kv-hidden"></div><div class="clearfix"></div>\n' +
- '<div class="input-group {class}">\n' +
- ' {caption}\n' +
- '<div class="input-group-btn input-group-append">\n' +
- ' {remove}\n' +
- ' {cancel}\n' +
- ' {pause}\n' +
- ' {upload}\n' +
- ' {browse}\n' +
- ' </div>\n' +
- '</div>';
- 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';
- tPreview = '<div class="file-preview {class}">\n' +
- ' {close}' +
- ' <div class="{dropClass}">\n' +
- ' <div class="file-preview-thumbnails">\n' +
- ' </div>\n' +
- ' <div class="clearfix"></div>' +
- ' <div class="file-preview-status text-center text-success"></div>\n' +
- ' <div class="kv-fileinput-error"></div>\n' +
- ' </div>\n' +
- '</div>';
- tClose = $h.closeButton('fileinput-remove');
- tFileIcon = '<i class="glyphicon glyphicon-file"></i>';
- // noinspection HtmlUnknownAttribute
- tCaption = '<div class="file-caption form-control {class}" tabindex="500">\n' +
- ' <span class="file-caption-icon"></span>\n' +
- ' <input class="file-caption-name" onkeydown="return false;" onpaste="return false;">\n' +
- '</div>';
- //noinspection HtmlUnknownAttribute
- tBtnDefault = '<button type="{type}" tabindex="500" title="{title}" class="{css}" ' +
- '{status}>{icon} {label}</button>';
- //noinspection HtmlUnknownAttribute
- tBtnLink = '<a href="{href}" tabindex="500" title="{title}" class="{css}" {status}>{icon} {label}</a>';
- //noinspection HtmlUnknownAttribute
- tBtnBrowse = '<div tabindex="500" class="{css}" {status}>{icon} {label}</div>';
- tModalMain = '<div id="' + $h.MODAL_ID + '" class="file-zoom-dialog modal fade" ' +
- 'tabindex="-1" aria-labelledby="' + $h.MODAL_ID + 'Label"></div>';
- tModal = '<div class="modal-dialog modal-lg{rtl}" role="document">\n' +
- ' <div class="modal-content">\n' +
- ' <div class="modal-header">\n' +
- ' <h5 class="modal-title">{heading}</h5>\n' +
- ' <span class="kv-zoom-title"></span>\n' +
- ' <div class="kv-zoom-actions">{toggleheader}{fullscreen}{borderless}{close}</div>\n' +
- ' </div>\n' +
- ' <div class="modal-body">\n' +
- ' <div class="floating-buttons"></div>\n' +
- ' <div class="kv-zoom-body file-zoom-content {zoomFrameClass}"></div>\n' + '{prev} {next}\n' +
- ' </div>\n' +
- ' </div>\n' +
- '</div>\n';
- tProgress = '<div class="progress">\n' +
- ' <div class="{class}" role="progressbar"' +
- ' aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' +
- ' {status}\n' +
- ' </div>\n' +
- '</div>{stats}';
- tStats = '<div class="text-info file-upload-stats">' +
- '<span class="pending-time">{pendingTime}</span> ' +
- '<span class="upload-speed">{uploadSpeed}</span>' +
- '</div>';
- tSize = ' <samp>({sizeText})</samp>';
- tFooter = '<div class="file-thumbnail-footer">\n' +
- ' <div class="file-footer-caption" title="{caption}">\n' +
- ' <div class="file-caption-info">{caption}</div>\n' +
- ' <div class="file-size-info">{size}</div>\n' +
- ' </div>\n' +
- ' {progress}\n{indicator}\n{actions}\n' +
- '</div>';
- tActions = '<div class="file-actions">\n' +
- ' <div class="file-footer-buttons">\n' +
- ' {download} {upload} {delete} {zoom} {other}' +
- ' </div>\n' +
- '</div>\n' +
- '{drag}\n' +
- '<div class="clearfix"></div>';
- //noinspection HtmlUnknownAttribute
- tActionDelete = '<button type="button" class="kv-file-remove {removeClass}" ' +
- 'title="{removeTitle}" {dataUrl}{dataKey}>{removeIcon}</button>\n';
- tActionUpload = '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">' +
- '{uploadIcon}</button>';
- tActionDownload = '<a class="kv-file-download {downloadClass}" title="{downloadTitle}" ' +
- 'href="{downloadUrl}" download="{caption}" target="_blank">{downloadIcon}</a>';
- tActionZoom = '<button type="button" class="kv-file-zoom {zoomClass}" ' +
- 'title="{zoomTitle}">{zoomIcon}</button>';
- tActionDrag = '<span class="file-drag-handle {dragClass}" title="{dragTitle}">{dragIcon}</span>';
- tIndicator = '<div class="file-upload-indicator" title="{indicatorTitle}">{indicator}</div>';
- tTagBef = '<div class="file-preview-frame {frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
- ' data-fileid="{fileid}" data-template="{template}"';
- tTagBef1 = tTagBef + '><div class="kv-file-content">\n';
- tTagBef2 = tTagBef + ' title="{caption}"><div class="kv-file-content">\n';
- tTagAft = '</div>{footer}\n</div>\n';
- tGeneric = '{content}\n';
- tStyle = ' {style}';
- tHtml = '<div class="kv-preview-data file-preview-html" title="{caption}"' + tStyle + '>{data}</div>\n';
- tImage = '<img src="{data}" class="file-preview-image kv-preview-data" title="{title}" ' +
- 'alt="{alt}"' + tStyle + '>\n';
- tText = '<textarea class="kv-preview-data file-preview-text" title="{caption}" readonly' + tStyle + '>' +
- '{data}</textarea>\n';
- tOffice = '<iframe class="kv-preview-data file-preview-office" ' +
- 'src="https://view.officeapps.live.com/op/embed.aspx?src={data}"' + tStyle + '></iframe>';
- tGdocs = '<iframe class="kv-preview-data file-preview-gdocs" ' +
- 'src="https://docs.google.com/gview?url={data}&embedded=true"' + tStyle + '></iframe>';
- tVideo = '<video class="kv-preview-data file-preview-video" controls' + tStyle + '>\n' +
- '<source src="{data}" type="{type}">\n' + $h.DEFAULT_PREVIEW + '\n</video>\n';
- tAudio = '<!--suppress ALL --><audio class="kv-preview-data file-preview-audio" controls' + tStyle + '>\n<source src="{data}" ' +
- 'type="{type}">\n' + $h.DEFAULT_PREVIEW + '\n</audio>\n';
- tFlash = '<embed class="kv-preview-data file-preview-flash" src="{data}" type="application/x-shockwave-flash"' + tStyle + '>\n';
- tPdf = '<embed class="kv-preview-data file-preview-pdf" src="{data}" type="application/pdf"' + tStyle + '>\n';
- tObject = '<object class="kv-preview-data file-preview-object file-object {typeCss}" ' +
- 'data="{data}" type="{type}"' + tStyle + '>\n' + '<param name="movie" value="{caption}" />\n' +
- $h.OBJECT_PARAMS + ' ' + $h.DEFAULT_PREVIEW + '\n</object>\n';
- tOther = '<div class="kv-preview-data file-preview-other-frame"' + tStyle + '>\n' + $h.DEFAULT_PREVIEW + '\n</div>\n';
- tZoomCache = '<div class="kv-zoom-cache" style="display:none">{zoomContent}</div>';
- vDefaultDim = {width: '100%', height: '100%', 'min-height': '480px'};
- if (self._isPdfRendered()) {
- tPdf = self.pdfRendererTemplate.replace('{renderer}', self._encodeURI(self.pdfRendererUrl));
- }
- self.defaults = {
- layoutTemplates: {
- main1: tMain1,
- main2: tMain2,
- preview: tPreview,
- close: tClose,
- fileIcon: tFileIcon,
- caption: tCaption,
- modalMain: tModalMain,
- modal: tModal,
- progress: tProgress,
- stats: tStats,
- size: tSize,
- footer: tFooter,
- indicator: tIndicator,
- actions: tActions,
- actionDelete: tActionDelete,
- actionUpload: tActionUpload,
- actionDownload: tActionDownload,
- actionZoom: tActionZoom,
- actionDrag: tActionDrag,
- btnDefault: tBtnDefault,
- btnLink: tBtnLink,
- btnBrowse: tBtnBrowse,
- zoomCache: tZoomCache
- },
- previewMarkupTags: {
- tagBefore1: tTagBef1,
- tagBefore2: tTagBef2,
- tagAfter: tTagAft
- },
- previewContentTemplates: {
- generic: tGeneric,
- html: tHtml,
- image: tImage,
- text: tText,
- office: tOffice,
- gdocs: tGdocs,
- video: tVideo,
- audio: tAudio,
- flash: tFlash,
- object: tObject,
- pdf: tPdf,
- other: tOther
- },
- allowedPreviewTypes: ['image', 'html', 'text', 'video', 'audio', 'flash', 'pdf', 'object'],
- previewTemplates: {},
- previewSettings: {
- image: {width: 'auto', height: 'auto', 'max-width': '100%', 'max-height': '100%'},
- html: {width: '213px', height: '160px'},
- text: {width: '213px', height: '160px'},
- office: {width: '213px', height: '160px'},
- gdocs: {width: '213px', height: '160px'},
- video: {width: '213px', height: '160px'},
- audio: {width: '100%', height: '30px'},
- flash: {width: '213px', height: '160px'},
- object: {width: '213px', height: '160px'},
- pdf: {width: '100%', height: '160px'},
- other: {width: '213px', height: '160px'}
- },
- previewSettingsSmall: {
- image: {width: 'auto', height: 'auto', 'max-width': '100%', 'max-height': '100%'},
- html: {width: '100%', height: '160px'},
- text: {width: '100%', height: '160px'},
- office: {width: '100%', height: '160px'},
- gdocs: {width: '100%', height: '160px'},
- video: {width: '100%', height: 'auto'},
- audio: {width: '100%', height: '30px'},
- flash: {width: '100%', height: 'auto'},
- object: {width: '100%', height: 'auto'},
- pdf: {width: '100%', height: '160px'},
- other: {width: '100%', height: '160px'}
- },
- previewZoomSettings: {
- image: {width: 'auto', height: 'auto', 'max-width': '100%', 'max-height': '100%'},
- html: vDefaultDim,
- text: vDefaultDim,
- office: {width: '100%', height: '100%', 'max-width': '100%', 'min-height': '480px'},
- gdocs: {width: '100%', height: '100%', 'max-width': '100%', 'min-height': '480px'},
- video: {width: 'auto', height: '100%', 'max-width': '100%'},
- audio: {width: '100%', height: '30px'},
- flash: {width: 'auto', height: '480px'},
- object: {width: 'auto', height: '100%', 'max-width': '100%', 'min-height': '480px'},
- pdf: vDefaultDim,
- other: {width: 'auto', height: '100%', 'min-height': '480px'}
- },
- mimeTypeAliases: {
- 'video/quicktime': 'video/mp4'
- },
- fileTypeSettings: {
- image: function (vType, vName) {
- return ($h.compare(vType, 'image.*') && !$h.compare(vType, /(tiff?|wmf)$/i) ||
- $h.compare(vName, /\.(gif|png|jpe?g)$/i));
- },
- html: function (vType, vName) {
- return $h.compare(vType, 'text/html') || $h.compare(vName, /\.(htm|html)$/i);
- },
- office: function (vType, vName) {
- return $h.compare(vType, /(word|excel|powerpoint|office)$/i) ||
- $h.compare(vName, /\.(docx?|xlsx?|pptx?|pps|potx?)$/i);
- },
- gdocs: function (vType, vName) {
- return $h.compare(vType, /(word|excel|powerpoint|office|iwork-pages|tiff?)$/i) ||
- $h.compare(vName,
- /\.(docx?|xlsx?|pptx?|pps|potx?|rtf|ods|odt|pages|ai|dxf|ttf|tiff?|wmf|e?ps)$/i);
- },
- text: function (vType, vName) {
- return $h.compare(vType, 'text.*') || $h.compare(vName, /\.(xml|javascript)$/i) ||
- $h.compare(vName, /\.(txt|md|csv|nfo|ini|json|php|js|css)$/i);
- },
- video: function (vType, vName) {
- return $h.compare(vType, 'video.*') && ($h.compare(vType, /(ogg|mp4|mp?g|mov|webm|3gp)$/i) ||
- $h.compare(vName, /\.(og?|mp4|webm|mp?g|mov|3gp)$/i));
- },
- audio: function (vType, vName) {
- return $h.compare(vType, 'audio.*') && ($h.compare(vName, /(ogg|mp3|mp?g|wav)$/i) ||
- $h.compare(vName, /\.(og?|mp3|mp?g|wav)$/i));
- },
- flash: function (vType, vName) {
- return $h.compare(vType, 'application/x-shockwave-flash', true) || $h.compare(vName,
- /\.(swf)$/i);
- },
- pdf: function (vType, vName) {
- return $h.compare(vType, 'application/pdf', true) || $h.compare(vName, /\.(pdf)$/i);
- },
- object: function () {
- return true;
- },
- other: function () {
- return true;
- }
- },
- fileActionSettings: {
- showRemove: true,
- showUpload: true,
- showDownload: true,
- showZoom: true,
- showDrag: true,
- removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
- removeClass: 'btn btn-sm btn-kv btn-default btn-outline-secondary',
- removeErrorClass: 'btn btn-sm btn-kv btn-danger',
- removeTitle: 'Remove file',
- uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
- uploadClass: 'btn btn-sm btn-kv btn-default btn-outline-secondary',
- uploadTitle: 'Upload file',
- uploadRetryIcon: '<i class="glyphicon glyphicon-repeat"></i>',
- uploadRetryTitle: 'Retry upload',
- downloadIcon: '<i class="glyphicon glyphicon-download"></i>',
- downloadClass: 'btn btn-sm btn-kv btn-default btn-outline-secondary',
- downloadTitle: 'Download file',
- zoomIcon: '<i class="glyphicon glyphicon-zoom-in"></i>',
- zoomClass: 'btn btn-sm btn-kv btn-default btn-outline-secondary',
- zoomTitle: 'View Details',
- dragIcon: '<i class="glyphicon glyphicon-move"></i>',
- dragClass: 'text-info',
- dragTitle: 'Move / Rearrange',
- dragSettings: {},
- indicatorNew: '<i class="glyphicon glyphicon-plus-sign text-warning"></i>',
- indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign text-success"></i>',
- indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>',
- indicatorLoading: '<i class="glyphicon glyphicon-hourglass text-muted"></i>',
- indicatorPaused: '<i class="glyphicon glyphicon-pause text-primary"></i>',
- indicatorNewTitle: 'Not uploaded yet',
- indicatorSuccessTitle: 'Uploaded',
- indicatorErrorTitle: 'Upload Error',
- indicatorLoadingTitle: 'Uploading ...',
- indicatorPausedTitle: 'Upload Paused'
- }
- };
- $.each(self.defaults, function (key, setting) {
- if (key === 'allowedPreviewTypes') {
- if (self.allowedPreviewTypes === undefined) {
- self.allowedPreviewTypes = setting;
- }
- return;
- }
- self[key] = $.extend(true, {}, setting, self[key]);
- });
- self._initPreviewTemplates();
- },
- _initPreviewTemplates: function () {
- var self = this, tags = self.previewMarkupTags, tagBef, tagAft = tags.tagAfter;
- $.each(self.previewContentTemplates, function (key, value) {
- if ($h.isEmpty(self.previewTemplates[key])) {
- tagBef = tags.tagBefore2;
- if (key === 'generic' || key === 'image' || key === 'html' || key === 'text') {
- tagBef = tags.tagBefore1;
- }
- if (self._isPdfRendered() && key === 'pdf') {
- tagBef = tagBef.replace('kv-file-content', 'kv-file-content kv-pdf-rendered');
- }
- self.previewTemplates[key] = tagBef + value + tagAft;
- }
- });
- },
- _initPreviewCache: function () {
- var self = this;
- self.previewCache = {
- data: {},
- init: function () {
- var content = self.initialPreview;
- if (content.length > 0 && !$h.isArray(content)) {
- content = content.split(self.initialPreviewDelimiter);
- }
- self.previewCache.data = {
- content: content,
- config: self.initialPreviewConfig,
- tags: self.initialPreviewThumbTags
- };
- },
- count: function (skipNull) {
- if (!self.previewCache.data || !self.previewCache.data.content) {
- return 0;
- }
- if (skipNull) {
- var chk = self.previewCache.data.content.filter(function (n) {
- return n !== null;
- });
- return chk.length;
- }
- return self.previewCache.data.content.length;
- },
- get: function (i, isDisabled) {
- var ind = 'init_' + i, data = self.previewCache.data, config = data.config[i], fileId,
- content = data.content[i], previewId = self.previewInitId + '-' + ind, out, $tmp, cat, ftr,
- fname, ftype, frameClass, asData = $h.ifSet('previewAsData', config, self.initialPreviewAsData),
- a = config ? {title: config.title || null, alt: config.alt || null} : {title: null, alt: null},
- parseTemplate = function (cat, dat, fn, ft, id, ftr, ind, fc, t) {
- fc = ' file-preview-initial ' + $h.SORT_CSS + (fc ? ' ' + fc : '');
- /** @namespace config.zoomData */
- fileId = config && config.fileId || 'file_' + id;
- return self._generatePreviewTemplate(cat, dat, fn, ft, id, fileId, false, null, fc,
- ftr, ind, t, a, config && config.zoomData || dat);
- };
- if (!content || !content.length) {
- return '';
- }
- isDisabled = isDisabled === undefined ? true : isDisabled;
- cat = $h.ifSet('type', config, self.initialPreviewFileType || 'generic');
- fname = $h.ifSet('filename', config, $h.ifSet('caption', config));
- ftype = $h.ifSet('filetype', config, cat);
- ftr = self.previewCache.footer(i, isDisabled, (config && config.size || null));
- frameClass = $h.ifSet('frameClass', config);
- if (asData) {
- out = parseTemplate(cat, content, fname, ftype, previewId, ftr, ind, frameClass);
- } else {
- out = parseTemplate('generic', content, fname, ftype, previewId, ftr, ind, frameClass, cat)
- .setTokens({'content': data.content[i]});
- }
- if (data.tags.length && data.tags[i]) {
- out = $h.replaceTags(out, data.tags[i]);
- }
- /** @namespace config.frameAttr */
- if (!$h.isEmpty(config) && !$h.isEmpty(config.frameAttr)) {
- $tmp = $(document.createElement('div')).html(out);
- $tmp.find('.file-preview-initial').attr(config.frameAttr);
- out = $tmp.html();
- $tmp.remove();
- }
- return out;
- },
- clean: function (data) {
- data.content = $h.cleanArray(data.content);
- data.config = $h.cleanArray(data.config);
- data.tags = $h.cleanArray(data.tags);
- self.previewCache.data = data;
- },
- add: function (content, config, tags, append) {
- var data = self.previewCache.data, index = content.length - 1;
- if (!content || !content.length) {
- return index;
- }
- if (!$h.isArray(content)) {
- content = content.split(self.initialPreviewDelimiter);
- }
- if (append) {
- index = data.content.push(content[0]) - 1;
- data.config[index] = config;
- data.tags[index] = tags;
- } else {
- data.content = content;
- data.config = config;
- data.tags = tags;
- }
- self.previewCache.clean(data);
- return index;
- },
- set: function (content, config, tags, append) {
- var data = self.previewCache.data, i, chk;
- if (!content || !content.length) {
- return;
- }
- if (!$h.isArray(content)) {
- content = content.split(self.initialPreviewDelimiter);
- }
- chk = content.filter(function (n) {
- return n !== null;
- });
- if (!chk.length) {
- return;
- }
- if (data.content === undefined) {
- data.content = [];
- }
- if (data.config === undefined) {
- data.config = [];
- }
- if (data.tags === undefined) {
- data.tags = [];
- }
- if (append) {
- for (i = 0; i < content.length; i++) {
- if (content[i]) {
- data.content.push(content[i]);
- }
- }
- for (i = 0; i < config.length; i++) {
- if (config[i]) {
- data.config.push(config[i]);
- }
- }
- for (i = 0; i < tags.length; i++) {
- if (tags[i]) {
- data.tags.push(tags[i]);
- }
- }
- } else {
- data.content = content;
- data.config = config;
- data.tags = tags;
- }
- self.previewCache.clean(data);
- },
- unset: function (index) {
- var chk = self.previewCache.count(), rev = self.reversePreviewOrder;
- if (!chk) {
- return;
- }
- if (chk === 1) {
- self.previewCache.data.content = [];
- self.previewCache.data.config = [];
- self.previewCache.data.tags = [];
- self.initialPreview = [];
- self.initialPreviewConfig = [];
- self.initialPreviewThumbTags = [];
- return;
- }
- self.previewCache.data.content = $h.spliceArray(self.previewCache.data.content, index, rev);
- self.previewCache.data.config = $h.spliceArray(self.previewCache.data.config, index, rev);
- self.previewCache.data.tags = $h.spliceArray(self.previewCache.data.tags, index, rev);
- var data = $.extend(true, {}, self.previewCache.data);
- self.previewCache.clean(data);
- },
- out: function () {
- var html = '', caption, len = self.previewCache.count(), i, content;
- if (len === 0) {
- return {content: '', caption: ''};
- }
- for (i = 0; i < len; i++) {
- content = self.previewCache.get(i);
- html = self.reversePreviewOrder ? (content + html) : (html + content);
- }
- caption = self._getMsgSelected(len);
- return {content: html, caption: caption};
- },
- footer: function (i, isDisabled, size) {
- var data = self.previewCache.data || {};
- if ($h.isEmpty(data.content)) {
- return '';
- }
- if ($h.isEmpty(data.config) || $h.isEmpty(data.config[i])) {
- data.config[i] = {};
- }
- isDisabled = isDisabled === undefined ? true : isDisabled;
- var config = data.config[i], caption = $h.ifSet('caption', config), a,
- width = $h.ifSet('width', config, 'auto'), url = $h.ifSet('url', config, false),
- key = $h.ifSet('key', config, null), fileId = $h.ifSet('fileId', config, null),
- fs = self.fileActionSettings, initPreviewShowDel = self.initialPreviewShowDelete || false,
- downloadInitialUrl = !self.initialPreviewDownloadUrl ? '' :
- self.initialPreviewDownloadUrl + '?key=' + key + (fileId ? '&fileId=' + fileId : ''),
- dUrl = config.downloadUrl || downloadInitialUrl,
- dFil = config.filename || config.caption || '',
- initPreviewShowDwl = !!(dUrl),
- sDel = $h.ifSet('showRemove', config, $h.ifSet('showRemove', fs, initPreviewShowDel)),
- sDwl = $h.ifSet('showDownload', config, $h.ifSet('showDownload', fs, initPreviewShowDwl)),
- sZm = $h.ifSet('showZoom', config, $h.ifSet('showZoom', fs, true)),
- sDrg = $h.ifSet('showDrag', config, $h.ifSet('showDrag', fs, true)),
- dis = (url === false) && isDisabled;
- sDwl = sDwl && config.downloadUrl !== false && !!dUrl;
- a = self._renderFileActions(config, false, sDwl, sDel, sZm, sDrg, dis, url, key, true, dUrl, dFil);
- return self._getLayoutTemplate('footer').setTokens({
- 'progress': self._renderThumbProgress(),
- 'actions': a,
- 'caption': caption,
- 'size': self._getSize(size),
- 'width': width,
- 'indicator': ''
- });
- }
- };
- self.previewCache.init();
- },
- _isPdfRendered: function () {
- var self = this, useLib = self.usePdfRenderer,
- flag = typeof useLib === 'function' ? useLib() : !!useLib;
- return flag && self.pdfRendererUrl;
- },
- _handler: function ($el, event, callback) {
- var self = this, ns = self.namespace, ev = event.split(' ').join(ns + ' ') + ns;
- if (!$el || !$el.length) {
- return;
- }
- $el.off(ev).on(ev, callback);
- },
- _encodeURI: function (vUrl) {
- var self = this;
- return self.encodeUrl ? encodeURI(vUrl) : vUrl;
- },
- _log: function (msg, tokens) {
- var self = this, id = self.$element.attr('id');
- if (id) {
- msg = '"' + id + '": ' + msg;
- }
- msg = 'bootstrap-fileinput: ' + msg;
- if (typeof tokens === 'object') {
- msg.setTokens(tokens);
- }
- if (typeof window.console.log !== 'undefined') {
- window.console.log(msg);
- } else {
- window.alert(msg);
- }
- },
- _validate: function () {
- var self = this, status = self.$element.attr('type') === 'file';
- if (!status) {
- self._log($h.logMessages.badInputType);
- }
- return status;
- },
- _errorsExist: function () {
- var self = this, $err, $errList = self.$errorContainer.find('li');
- if ($errList.length) {
- return true;
- }
- $err = $(document.createElement('div')).html(self.$errorContainer.html());
- $err.find('.kv-error-close').remove();
- $err.find('ul').remove();
- return !!$.trim($err.text()).length;
- },
- _errorHandler: function (evt, caption) {
- var self = this, err = evt.target.error, showError = function (msg) {
- self._showError(msg.replace('{name}', caption));
- };
- /** @namespace err.NOT_FOUND_ERR */
- /** @namespace err.SECURITY_ERR */
- /** @namespace err.NOT_READABLE_ERR */
- if (err.code === err.NOT_FOUND_ERR) {
- showError(self.msgFileNotFound);
- } else {
- if (err.code === err.SECURITY_ERR) {
- showError(self.msgFileSecured);
- } else {
- if (err.code === err.NOT_READABLE_ERR) {
- showError(self.msgFileNotReadable);
- } else {
- if (err.code === err.ABORT_ERR) {
- showError(self.msgFilePreviewAborted);
- } else {
- showError(self.msgFilePreviewError);
- }
- }
- }
- }
- },
- _addError: function (msg) {
- var self = this, $error = self.$errorContainer;
- if (msg && $error.length) {
- $error.html(self.errorCloseButton + msg);
- self._handler($error.find('.kv-error-close'), 'click', function () {
- setTimeout(function () {
- if (self.showPreview && !self.getFrames().length) {
- self.clear();
- }
- $error.fadeOut('slow');
- }, self.processDelay);
- });
- }
- },
- _setValidationError: function (css) {
- var self = this;
- css = (css ? css + ' ' : '') + 'has-error';
- self.$container.removeClass(css).addClass('has-error');
- $h.addCss(self.$captionContainer, 'is-invalid');
- },
- _resetErrors: function (fade) {
- var self = this, $error = self.$errorContainer;
- self.isError = false;
- self.$container.removeClass('has-error');
- self.$captionContainer.removeClass('is-invalid');
- $error.html('');
- if (fade) {
- $error.fadeOut('slow');
- } else {
- $error.hide();
- }
- },
- _showFolderError: function (folders) {
- var self = this, $error = self.$errorContainer, msg;
- if (!folders) {
- return;
- }
- if (!self.isAjaxUpload) {
- self._clearFileInput();
- }
- msg = self.msgFoldersNotAllowed.replace('{n}', folders);
- self._addError(msg);
- self._setValidationError();
- $error.fadeIn(800);
- self._raise('filefoldererror', [folders, msg]);
- },
- _showFileError: function (msg, params, event) {
- var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror',
- fId = params && params.fileId || '', e = params && params.id ?
- '<li data-thumb-id="' + params.id + '" data-file-id="' + fId + '">' + msg + '</li>' : '<li>' + msg + '</li>';
- if ($error.find('ul').length === 0) {
- self._addError('<ul>' + e + '</ul>');
- } else {
- $error.find('ul').append(e);
- }
- $error.fadeIn(800);
- self._raise(ev, [params, msg]);
- self._setValidationError('file-input-new');
- return true;
- },
- _showError: function (msg, params, event) {
- var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
- params = params || {};
- params.reader = self.reader;
- self._addError(msg);
- $error.fadeIn(800);
- self._raise(ev, [params, msg]);
- if (!self.isAjaxUpload) {
- self._clearFileInput();
- }
- self._setValidationError('file-input-new');
- self.$btnUpload.attr('disabled', true);
- return true;
- },
- _noFilesError: function (params) {
- var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle,
- msg = self.msgFilesTooLess.replace('{n}', self.minFileCount).replace('{files}', label),
- $error = self.$errorContainer;
- self._addError(msg);
- self.isError = true;
- self._updateFileDetails(0);
- $error.fadeIn(800);
- self._raise('fileerror', [params, msg]);
- self._clearFileInput();
- self._setValidationError();
- },
- _parseError: function (operation, jqXHR, errorThrown, fileName) {
- /** @namespace jqXHR.responseJSON */
- var self = this, errMsg = $.trim(errorThrown + ''), textPre,
- text = jqXHR.responseJSON !== undefined && jqXHR.responseJSON.error !== undefined ?
- jqXHR.responseJSON.error : jqXHR.responseText;
- if (self.cancelling && self.msgUploadAborted) {
- errMsg = self.msgUploadAborted;
- }
- if (self.showAjaxErrorDetails && text) {
- text = $.trim(text.replace(/\n\s*\n/g, '\n'));
- textPre = text.length ? '<pre>' + text + '</pre>' : '';
- errMsg += errMsg ? textPre : text;
- }
- if (!errMsg) {
- errMsg = self.msgAjaxError.replace('{operation}', operation);
- }
- self.cancelling = false;
- return fileName ? '<b>' + fileName + ': </b>' + errMsg : errMsg;
- },
- _parseFileType: function (type, name) {
- var self = this, isValid, vType, cat, i, types = self.allowedPreviewTypes || [];
- if (type === 'application/text-plain') {
- return 'text';
- }
- for (i = 0; i < types.length; i++) {
- cat = types[i];
- isValid = self.fileTypeSettings[cat];
- vType = isValid(type, name) ? cat : '';
- if (!$h.isEmpty(vType)) {
- return vType;
- }
- }
- return 'other';
- },
- _getPreviewIcon: function (fname) {
- var self = this, ext, out = null;
- if (fname && fname.indexOf('.') > -1) {
- ext = fname.split('.').pop();
- if (self.previewFileIconSettings) {
- out = self.previewFileIconSettings[ext] || self.previewFileIconSettings[ext.toLowerCase()] || null;
- }
- if (self.previewFileExtSettings) {
- $.each(self.previewFileExtSettings, function (key, func) {
- if (self.previewFileIconSettings[key] && func(ext)) {
- out = self.previewFileIconSettings[key];
- //noinspection UnnecessaryReturnStatementJS
- return;
- }
- });
- }
- }
- return out;
- },
- _parseFilePreviewIcon: function (content, fname) {
- var self = this, icn = self._getPreviewIcon(fname) || self.previewFileIcon, out = content;
- if (out.indexOf('{previewFileIcon}') > -1) {
- out = out.setTokens({'previewFileIconClass': self.previewFileIconClass, 'previewFileIcon': icn});
- }
- return out;
- },
- _raise: function (event, params) {
- var self = this, e = $.Event(event);
- if (params !== undefined) {
- self.$element.trigger(e, params);
- } else {
- self.$element.trigger(e);
- }
- if (e.isDefaultPrevented() || e.result === false) {
- return false;
- }
- switch (event) {
- // ignore these events
- case 'filebatchuploadcomplete':
- case 'filebatchuploadsuccess':
- case 'fileuploaded':
- case 'fileclear':
- case 'filecleared':
- case 'filereset':
- case 'fileerror':
- case 'filefoldererror':
- case 'fileuploaderror':
- case 'filebatchuploaderror':
- case 'filedeleteerror':
- case 'filecustomerror':
- case 'filesuccessremove':
- break;
- // receive data response via `filecustomerror` event`
- default:
- if (!self.ajaxAborted) {
- self.ajaxAborted = e.result;
- }
- break;
- }
- return true;
- },
- _listenFullScreen: function (isFullScreen) {
- var self = this, $modal = self.$modal, $btnFull, $btnBord;
- if (!$modal || !$modal.length) {
- return;
- }
- $btnFull = $modal && $modal.find('.btn-fullscreen');
- $btnBord = $modal && $modal.find('.btn-borderless');
- if (!$btnFull.length || !$btnBord.length) {
- return;
- }
- $btnFull.removeClass('active').attr('aria-pressed', 'false');
- $btnBord.removeClass('active').attr('aria-pressed', 'false');
- if (isFullScreen) {
- $btnFull.addClass('active').attr('aria-pressed', 'true');
- } else {
- $btnBord.addClass('active').attr('aria-pressed', 'true');
- }
- if ($modal.hasClass('file-zoom-fullscreen')) {
- self._maximizeZoomDialog();
- } else {
- if (isFullScreen) {
- self._maximizeZoomDialog();
- } else {
- $btnBord.removeClass('active').attr('aria-pressed', 'false');
- }
- }
- },
- _listen: function () {
- var self = this, $el = self.$element, $form = self.$form, $cont = self.$container, fullScreenEvents;
- self._handler($el, 'click', function (e) {
- if ($el.hasClass('file-no-browse')) {
- if ($el.data('zoneClicked')) {
- $el.data('zoneClicked', false);
- } else {
- e.preventDefault();
- }
- }
- });
- self._handler($el, 'change', $.proxy(self._change, self));
- if (self.showBrowse) {
- self._handler(self.$btnFile, 'click', $.proxy(self._browse, self));
- }
- self._handler($cont.find('.fileinput-remove:not([disabled])'), 'click', $.proxy(self.clear, self));
- self._handler($cont.find('.fileinput-cancel'), 'click', $.proxy(self.cancel, self));
- self._handler($cont.find('.fileinput-pause'), 'click', $.proxy(self.pause, self));
- self._initDragDrop();
- self._handler($form, 'reset', $.proxy(self.clear, self));
- if (!self.isAjaxUpload) {
- self._handler($form, 'submit', $.proxy(self._submitForm, self));
- }
- self._handler(self.$container.find('.fileinput-upload'), 'click', $.proxy(self._uploadClick, self));
- self._handler($(window), 'resize', function () {
- self._listenFullScreen(screen.width === window.innerWidth && screen.height === window.innerHeight);
- });
- fullScreenEvents = 'webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange';
- self._handler($(document), fullScreenEvents, function () {
- self._listenFullScreen($h.checkFullScreen());
- });
- self._autoFitContent();
- self._initClickable();
- self._refreshPreview();
- },
- _autoFitContent: function () {
- var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
- self = this, config = width < 400 ? (self.previewSettingsSmall || self.defaults.previewSettingsSmall) :
- (self.previewSettings || self.defaults.previewSettings), sel;
- $.each(config, function (cat, settings) {
- sel = '.file-preview-frame .file-preview-' + cat;
- self.$preview.find(sel + '.kv-preview-data,' + sel + ' .kv-preview-data').css(settings);
- });
- },
- _scanDroppedItems: function (item, files, path) {
- path = path || '';
- var self = this, i, dirReader, readDir, errorHandler = function (e) {
- self._log($h.logMessages.badDroppedFiles);
- self._log(e);
- };
- if (item.isFile) {
- item.file(function (file) {
- files.push(file);
- }, errorHandler);
- } else {
- if (item.isDirectory) {
- dirReader = item.createReader();
- readDir = function () {
- dirReader.readEntries(function (entries) {
- if (entries && entries.length > 0) {
- for (i = 0; i < entries.length; i++) {
- self._scanDroppedItems(entries[i], files, path + item.name + '/');
- }
- // recursively call readDir() again, since browser can only handle first 100 entries.
- readDir();
- }
- return null;
- }, errorHandler);
- };
- readDir();
- }
- }
- },
- _initDragDrop: function () {
- var self = this, $zone = self.$dropZone;
- if (self.dropZoneEnabled && self.showPreview) {
- self._handler($zone, 'dragenter dragover', $.proxy(self._zoneDragEnter, self));
- self._handler($zone, 'dragleave', $.proxy(self._zoneDragLeave, self));
- self._handler($zone, 'drop', $.proxy(self._zoneDrop, self));
- self._handler($(document), 'dragenter dragover drop', self._zoneDragDropInit);
- }
- },
- _zoneDragDropInit: function (e) {
- e.stopPropagation();
- e.preventDefault();
- },
- _zoneDragEnter: function (e) {
- var self = this, dataTransfer = e.originalEvent.dataTransfer,
- hasFiles = $.inArray('Files', dataTransfer.types) > -1;
- self._zoneDragDropInit(e);
- if (self.isDisabled || !hasFiles) {
- e.originalEvent.dataTransfer.effectAllowed = 'none';
- e.originalEvent.dataTransfer.dropEffect = 'none';
- return;
- }
- if (self._raise('fileDragEnter', {'sourceEvent': e, 'files': dataTransfer.types.Files})) {
- $h.addCss(self.$dropZone, 'file-highlighted');
- }
- },
- _zoneDragLeave: function (e) {
- var self = this;
- self._zoneDragDropInit(e);
- if (self.isDisabled) {
- return;
- }
- if (self._raise('fileDragLeave', {'sourceEvent': e})) {
- self.$dropZone.removeClass('file-highlighted');
- }
- },
- _zoneDrop: function (e) {
- /** @namespace e.originalEvent.dataTransfer */
- var self = this, i, $el = self.$element, dataTransfer = e.originalEvent.dataTransfer,
- files = dataTransfer.files, items = dataTransfer.items, folders = $h.getDragDropFolders(items),
- processFiles = function () {
- if (!self.isAjaxUpload) {
- self.changeTriggered = true;
- $el.get(0).files = files;
- setTimeout(function () {
- self.changeTriggered = false;
- $el.trigger('change' + self.namespace);
- }, self.processDelay);
- } else {
- self._change(e, files);
- }
- self.$dropZone.removeClass('file-highlighted');
- };
- e.preventDefault();
- if (self.isDisabled || $h.isEmpty(files)) {
- return;
- }
- if (!self._raise('fileDragDrop', {'sourceEvent': e, 'files': files})) {
- return;
- }
- if (folders > 0) {
- if (!self.isAjaxUpload) {
- self._showFolderError(folders);
- return;
- }
- files = [];
- for (i = 0; i < items.length; i++) {
- var item = items[i].webkitGetAsEntry();
- if (item) {
- self._scanDroppedItems(item, files);
- }
- }
- setTimeout(function () {
- processFiles();
- }, 500);
- } else {
- processFiles();
- }
- },
- _uploadClick: function (e) {
- var self = this, $btn = self.$container.find('.fileinput-upload'), $form,
- isEnabled = !$btn.hasClass('disabled') && $h.isEmpty($btn.attr('disabled'));
- if (e && e.isDefaultPrevented()) {
- return;
- }
- if (!self.isAjaxUpload) {
- if (isEnabled && $btn.attr('type') !== 'submit') {
- $form = $btn.closest('form');
- // downgrade to normal form submit if possible
- if ($form.length) {
- $form.trigger('submit');
- }
- e.preventDefault();
- }
- return;
- }
- e.preventDefault();
- if (isEnabled) {
- self.upload();
- }
- },
- _submitForm: function () {
- var self = this;
- return self._isFileSelectionValid() && !self._abort({});
- },
- _clearPreview: function () {
- var self = this, $p = self.$preview,
- $thumbs = self.showUploadedThumbs ? self.getFrames(':not(.file-preview-success)') : self.getFrames();
- $thumbs.each(function () {
- var $thumb = $(this);
- $thumb.remove();
- $h.cleanZoomCache($p.find('#zoom-' + $thumb.attr('id')));
- });
- if (!self.getFrames().length || !self.showPreview) {
- self._resetUpload();
- }
- self._validateDefaultPreview();
- },
- _initSortable: function () {
- var self = this, $el = self.$preview, settings, selector = '.' + $h.SORT_CSS,
- rev = self.reversePreviewOrder;
- if (!window.KvSortable || $el.find(selector).length === 0) {
- return;
- }
- //noinspection JSUnusedGlobalSymbols
- settings = {
- handle: '.drag-handle-init',
- dataIdAttr: 'data-preview-id',
- scroll: false,
- draggable: selector,
- onSort: function (e) {
- var oldIndex = e.oldIndex, newIndex = e.newIndex, i = 0;
- self.initialPreview = $h.moveArray(self.initialPreview, oldIndex, newIndex, rev);
- self.initialPreviewConfig = $h.moveArray(self.initialPreviewConfig, oldIndex, newIndex, rev);
- self.previewCache.init();
- self.getFrames('.file-preview-initial').each(function () {
- $(this).attr('data-fileindex', 'init_' + i);
- i++;
- });
- self._raise('filesorted', {
- previewId: $(e.item).attr('id'),
- 'oldIndex': oldIndex,
- 'newIndex': newIndex,
- stack: self.initialPreviewConfig
- });
- }
- };
- if ($el.data('kvsortable')) {
- $el.kvsortable('destroy');
- }
- $.extend(true, settings, self.fileActionSettings.dragSettings);
- $el.kvsortable(settings);
- },
- _setPreviewContent: function (content) {
- var self = this;
- self.$preview.html(content);
- self._autoFitContent();
- },
- _initPreviewImageOrientations: function () {
- var self = this, i = 0;
- if (!self.autoOrientImageInitial) {
- return;
- }
- self.getFrames('.file-preview-initial').each(function () {
- var $thumb = $(this), $img, $zoomImg, id, config = self.initialPreviewConfig[i];
- /** @namespace config.exif */
- if (config && config.exif && config.exif.Orientation) {
- id = $thumb.attr('id');
- $img = $thumb.find('>.kv-file-content img');
- $zoomImg = self.$preview.find('#zoom-' + id + ' >.kv-file-content img');
- self.setImageOrientation($img, $zoomImg, config.exif.Orientation, $thumb);
- }
- i++;
- });
- },
- _initPreview: function (isInit) {
- var self = this, cap = self.initialCaption || '', out;
- if (!self.previewCache.count(true)) {
- self._clearPreview();
- if (isInit) {
- self._setCaption(cap);
- } else {
- self._initCaption();
- }
- return;
- }
- out = self.previewCache.out();
- cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
- self._setPreviewContent(out.content);
- self._setInitThumbAttr();
- self._setCaption(cap);
- self._initSortable();
- if (!$h.isEmpty(out.content)) {
- self.$container.removeClass('file-input-new');
- }
- self._initPreviewImageOrientations();
- },
- _getZoomButton: function (type) {
- var self = this, label = self.previewZoomButtonIcons[type], css = self.previewZoomButtonClasses[type],
- title = ' title="' + (self.previewZoomButtonTitles[type] || '') + '" ',
- params = title + (type === 'close' ? ' data-dismiss="modal" aria-hidden="true"' : '');
- if (type === 'fullscreen' || type === 'borderless' || type === 'toggleheader') {
- params += ' data-toggle="button" aria-pressed="false" autocomplete="off"';
- }
- return '<button type="button" class="' + css + ' btn-' + type + '"' + params + '>' + label + '</button>';
- },
- _getModalContent: function () {
- var self = this;
- return self._getLayoutTemplate('modal').setTokens({
- 'rtl': self.rtl ? ' kv-rtl' : '',
- 'zoomFrameClass': self.frameClass,
- 'heading': self.msgZoomModalHeading,
- 'prev': self._getZoomButton('prev'),
- 'next': self._getZoomButton('next'),
- 'toggleheader': self._getZoomButton('toggleheader'),
- 'fullscreen': self._getZoomButton('fullscreen'),
- 'borderless': self._getZoomButton('borderless'),
- 'close': self._getZoomButton('close')
- });
- },
- _listenModalEvent: function (event) {
- var self = this, $modal = self.$modal, getParams = function (e) {
- return {
- sourceEvent: e,
- previewId: $modal.data('previewId'),
- modal: $modal
- };
- };
- $modal.on(event + '.bs.modal', function (e) {
- var $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless');
- self._raise('filezoom' + event, getParams(e));
- if (event === 'shown') {
- $btnBord.removeClass('active').attr('aria-pressed', 'false');
- $btnFull.removeClass('active').attr('aria-pressed', 'false');
- if ($modal.hasClass('file-zoom-fullscreen')) {
- self._maximizeZoomDialog();
- if ($h.checkFullScreen()) {
- $btnFull.addClass('active').attr('aria-pressed', 'true');
- } else {
- $btnBord.addClass('active').attr('aria-pressed', 'true');
- }
- }
- }
- });
- },
- _initZoom: function () {
- var self = this, $dialog, modalMain = self._getLayoutTemplate('modalMain'), modalId = '#' + $h.MODAL_ID;
- if (!self.showPreview) {
- return;
- }
- self.$modal = $(modalId);
- if (!self.$modal || !self.$modal.length) {
- $dialog = $(document.createElement('div')).html(modalMain).insertAfter(self.$container);
- self.$modal = $(modalId).insertBefore($dialog);
- $dialog.remove();
- }
- $h.initModal(self.$modal);
- self.$modal.html(self._getModalContent());
- $.each($h.MODAL_EVENTS, function (key, event) {
- self._listenModalEvent(event);
- });
- },
- _initZoomButtons: function () {
- var self = this, previewId = self.$modal.data('previewId') || '', $first, $last,
- thumbs = self.getFrames().toArray(), len = thumbs.length, $prev = self.$modal.find('.btn-prev'),
- $next = self.$modal.find('.btn-next');
- if (thumbs.length < 2) {
- $prev.hide();
- $next.hide();
- return;
- } else {
- $prev.show();
- $next.show();
- }
- if (!len) {
- return;
- }
- $first = $(thumbs[0]);
- $last = $(thumbs[len - 1]);
- $prev.removeAttr('disabled');
- $next.removeAttr('disabled');
- if ($first.length && $first.attr('id') === previewId) {
- $prev.attr('disabled', true);
- }
- if ($last.length && $last.attr('id') === previewId) {
- $next.attr('disabled', true);
- }
- },
- _maximizeZoomDialog: function () {
- var self = this, $modal = self.$modal, $head = $modal.find('.modal-header:visible'),
- $foot = $modal.find('.modal-footer:visible'), $body = $modal.find('.modal-body'),
- h = $(window).height(), diff = 0;
- $modal.addClass('file-zoom-fullscreen');
- if ($head && $head.length) {
- h -= $head.outerHeight(true);
- }
- if ($foot && $foot.length) {
- h -= $foot.outerHeight(true);
- }
- if ($body && $body.length) {
- diff = $body.outerHeight(true) - $body.height();
- h -= diff;
- }
- $modal.find('.kv-zoom-body').height(h);
- },
- _resizeZoomDialog: function (fullScreen) {
- var self = this, $modal = self.$modal, $btnFull = $modal.find('.btn-fullscreen'),
- $btnBord = $modal.find('.btn-borderless');
- if ($modal.hasClass('file-zoom-fullscreen')) {
- $h.toggleFullScreen(false);
- if (!fullScreen) {
- if (!$btnFull.hasClass('active')) {
- $modal.removeClass('file-zoom-fullscreen');
- self.$modal.find('.kv-zoom-body').css('height', self.zoomModalHeight);
- } else {
- $btnFull.removeClass('active').attr('aria-pressed', 'false');
- }
- } else {
- if (!$btnFull.hasClass('active')) {
- $modal.removeClass('file-zoom-fullscreen');
- self._resizeZoomDialog(true);
- if ($btnBord.hasClass('active')) {
- $btnBord.removeClass('active').attr('aria-pressed', 'false');
- }
- }
- }
- } else {
- if (!fullScreen) {
- self._maximizeZoomDialog();
- return;
- }
- $h.toggleFullScreen(true);
- }
- $modal.focus();
- },
- _setZoomContent: function ($frame, animate) {
- var self = this, $content, tmplt, body, title, $body, $dataEl, config, previewId = $frame.attr('id'),
- $zoomPreview = self.$preview.find('#zoom-' + previewId), $modal = self.$modal, $tmp,
- $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless'), cap, size,
- $btnTogh = $modal.find('.btn-toggleheader');
- tmplt = $zoomPreview.attr('data-template') || 'generic';
- $content = $zoomPreview.find('.kv-file-content');
- body = $content.length ? $content.html() : '';
- cap = $frame.data('caption') || '';
- size = $frame.data('size') || '';
- title = cap + ' ' + size;
- $modal.find('.kv-zoom-title').attr('title', $('<div/>').html(title).text()).html(title);
- $body = $modal.find('.kv-zoom-body');
- $modal.removeClass('kv-single-content');
- if (animate) {
- $tmp = $body.addClass('file-thumb-loading').clone().insertAfter($body);
- $body.html(body).hide();
- $tmp.fadeOut('fast', function () {
- $body.fadeIn('fast', function () {
- $body.removeClass('file-thumb-loading');
- });
- $tmp.remove();
- });
- } else {
- $body.html(body);
- }
- config = self.previewZoomSettings[tmplt];
- if (config) {
- $dataEl = $body.find('.kv-preview-data');
- $h.addCss($dataEl, 'file-zoom-detail');
- $.each(config, function (key, value) {
- $dataEl.css(key, value);
- if (($dataEl.attr('width') && key === 'width') || ($dataEl.attr('height') && key === 'height')) {
- $dataEl.removeAttr(key);
- }
- });
- }
- $modal.data('previewId', previewId);
- self._handler($modal.find('.btn-prev'), 'click', function () {
- self._zoomSlideShow('prev', previewId);
- });
- self._handler($modal.find('.btn-next'), 'click', function () {
- self._zoomSlideShow('next', previewId);
- });
- self._handler($btnFull, 'click', function () {
- self._resizeZoomDialog(true);
- });
- self._handler($btnBord, 'click', function () {
- self._resizeZoomDialog(false);
- });
- self._handler($btnTogh, 'click', function () {
- var $header = $modal.find('.modal-header'), $floatBar = $modal.find('.modal-body .floating-buttons'),
- ht, $actions = $header.find('.kv-zoom-actions'), resize = function (height) {
- var $body = self.$modal.find('.kv-zoom-body'), h = self.zoomModalHeight;
- if ($modal.hasClass('file-zoom-fullscreen')) {
- h = $body.outerHeight(true);
- if (!height) {
- h = h - $header.outerHeight(true);
- }
- }
- $body.css('height', height ? h + height : h);
- };
- if ($header.is(':visible')) {
- ht = $header.outerHeight(true);
- $header.slideUp('slow', function () {
- $actions.find('.btn').appendTo($floatBar);
- resize(ht);
- });
- } else {
- $floatBar.find('.btn').appendTo($actions);
- $header.slideDown('slow', function () {
- resize();
- });
- }
- $modal.focus();
- });
- self._handler($modal, 'keydown', function (e) {
- var key = e.which || e.keyCode, $prev = $(this).find('.btn-prev'), $next = $(this).find('.btn-next'),
- vId = $(this).data('previewId'), vPrevKey = self.rtl ? 39 : 37, vNextKey = self.rtl ? 37 : 39;
- if (key === vPrevKey && $prev.length && !$prev.attr('disabled')) {
- self._zoomSlideShow('prev', vId);
- }
- if (key === vNextKey && $next.length && !$next.attr('disabled')) {
- self._zoomSlideShow('next', vId);
- }
- });
- },
- _zoomPreview: function ($btn) {
- var self = this, $frame, $modal = self.$modal;
- if (!$btn.length) {
- throw 'Cannot zoom to detailed preview!';
- }
- $h.initModal($modal);
- $modal.html(self._getModalContent());
- $frame = $btn.closest($h.FRAMES);
- self._setZoomContent($frame);
- $modal.modal('show');
- self._initZoomButtons();
- },
- _zoomSlideShow: function (dir, previewId) {
- var self = this, $btn = self.$modal.find('.kv-zoom-actions .btn-' + dir), $targFrame, i,
- thumbs = self.getFrames().toArray(), len = thumbs.length, out;
- if ($btn.attr('disabled')) {
- return;
- }
- for (i = 0; i < len; i++) {
- if ($(thumbs[i]).attr('id') === previewId) {
- out = dir === 'prev' ? i - 1 : i + 1;
- break;
- }
- }
- if (out < 0 || out >= len || !thumbs[out]) {
- return;
- }
- $targFrame = $(thumbs[out]);
- if ($targFrame.length) {
- self._setZoomContent($targFrame, true);
- }
- self._initZoomButtons();
- self._raise('filezoom' + dir, {'previewId': previewId, modal: self.$modal});
- },
- _initZoomButton: function () {
- var self = this;
- self.$preview.find('.kv-file-zoom').each(function () {
- var $el = $(this);
- self._handler($el, 'click', function () {
- self._zoomPreview($el);
- });
- });
- },
- _inputFileCount: function () {
- return this.$element.get(0).files.length;
- },
- _refreshPreview: function () {
- var self = this, files;
- if ((!self._inputFileCount() && !self.isAjaxUpload) || !self.showPreview || !self.isPreviewable) {
- return;
- }
- if (self.isAjaxUpload) {
- if (self.fileManager.count() > 0) {
- files = $.extend(true, {}, self.fileManager.stack);
- self.fileManager.clear();
- self._clearFileInput();
- } else {
- files = self.$element.get(0).files;
- }
- } else {
- files = self.$element.get(0).files;
- }
- if (files && files.length) {
- self.readFiles(files);
- self._setFileDropZoneTitle();
- }
- },
- _clearObjects: function ($el) {
- $el.find('video audio').each(function () {
- this.pause();
- $(this).remove();
- });
- $el.find('img object div').each(function () {
- $(this).remove();
- });
- },
- _clearFileInput: function () {
- var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
- if (!self._inputFileCount()) {
- return;
- }
- $srcFrm = $el.closest('form');
- $tmpFrm = $(document.createElement('form'));
- $tmpEl = $(document.createElement('div'));
- $el.before($tmpEl);
- if ($srcFrm.length) {
- $srcFrm.after($tmpFrm);
- } else {
- $tmpEl.after($tmpFrm);
- }
- $tmpFrm.append($el).trigger('reset');
- $tmpEl.before($el).remove();
- $tmpFrm.remove();
- },
- _resetUpload: function () {
- var self = this;
- self.uploadCache = {content: [], config: [], tags: [], append: true};
- self.$btnUpload.removeAttr('disabled');
- self._setProgress(0);
- self.$progress.hide();
- self._resetErrors(false);
- self._initAjax();
- self.fileManager.clearImages();
- self._resetCanvas();
- self.cacheInitialPreview = {};
- if (self.overwriteInitial) {
- self.initialPreview = [];
- self.initialPreviewConfig = [];
- self.initialPreviewThumbTags = [];
- self.previewCache.data = {
- content: [],
- config: [],
- tags: []
- };
- }
- },
- _resetCanvas: function () {
- var self = this;
- if (self.canvas && self.imageCanvasContext) {
- self.imageCanvasContext.clearRect(0, 0, self.canvas.width, self.canvas.height);
- }
- },
- _hasInitialPreview: function () {
- var self = this;
- return !self.overwriteInitial && self.previewCache.count(true);
- },
- _resetPreview: function () {
- var self = this, out, cap;
- if (self.previewCache.count(true)) {
- out = self.previewCache.out();
- self._setPreviewContent(out.content);
- self._setInitThumbAttr();
- cap = self.initialCaption ? self.initialCaption : out.caption;
- self._setCaption(cap);
- } else {
- self._clearPreview();
- self._initCaption();
- }
- if (self.showPreview) {
- self._initZoom();
- self._initSortable();
- }
- },
- _clearDefaultPreview: function () {
- var self = this;
- self.$preview.find('.file-default-preview').remove();
- },
- _validateDefaultPreview: function () {
- var self = this;
- if (!self.showPreview || $h.isEmpty(self.defaultPreviewContent)) {
- return;
- }
- self._setPreviewContent('<div class="file-default-preview">' + self.defaultPreviewContent + '</div>');
- self.$container.removeClass('file-input-new');
- self._initClickable();
- },
- _resetPreviewThumbs: function (isAjax) {
- var self = this, out;
- if (isAjax) {
- self._clearPreview();
- self.clearFileStack();
- return;
- }
- if (self._hasInitialPreview()) {
- out = self.previewCache.out();
- self._setPreviewContent(out.content);
- self._setInitThumbAttr();
- self._setCaption(out.caption);
- self._initPreviewActions();
- } else {
- self._clearPreview();
- }
- },
- _getLayoutTemplate: function (t) {
- var self = this, template = self.layoutTemplates[t];
- if ($h.isEmpty(self.customLayoutTags)) {
- return template;
- }
- return $h.replaceTags(template, self.customLayoutTags);
- },
- _getPreviewTemplate: function (t) {
- var self = this, template = self.previewTemplates[t];
- if ($h.isEmpty(self.customPreviewTags)) {
- return template;
- }
- return $h.replaceTags(template, self.customPreviewTags);
- },
- _getOutData: function (formdata, jqXHR, responseData, filesData) {
- var self = this;
- jqXHR = jqXHR || {};
- responseData = responseData || {};
- filesData = filesData || self.fileManager.list();
- return {
- formdata: formdata,
- files: filesData,
- filenames: self.filenames,
- filescount: self.getFilesCount(),
- extra: self._getExtraData(),
- response: responseData,
- reader: self.reader,
- jqXHR: jqXHR
- };
- },
- _getMsgSelected: function (n) {
- var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural;
- return n > 0 ? self.msgSelected.replace('{n}', n).replace('{files}', strFiles) : self.msgNoFilesSelected;
- },
- _getFrame: function (id) {
- var self = this, $frame = $('#' + id);
- if (!$frame.length) {
- self._log($h.logMessages.invalidThumb, {id: id});
- return null;
- }
- return $frame;
- },
- _getThumbs: function (css) {
- css = css || '';
- return this.getFrames(':not(.file-preview-initial)' + css);
- },
- _getExtraData: function (fileId, index) {
- var self = this, data = self.uploadExtraData;
- if (typeof self.uploadExtraData === 'function') {
- data = self.uploadExtraData(fileId, index);
- }
- return data;
- },
- _initXhr: function (xhrobj, fileId, fileCount) {
- var self = this, fm = self.fileManager, func = function (event) {
- var pct = 0, total = event.total, loaded = event.loaded || event.position,
- stats = fm.getUploadStats(fileId, loaded, total);
- /** @namespace event.lengthComputable */
- if (event.lengthComputable && !self.enableResumableUpload) {
- pct = $h.round(loaded / total * 100);
- }
- if (fileId) {
- self._setFileUploadStats(fileId, pct, fileCount, stats);
- } else {
- self._setProgress(pct, null, null, self._getStats(stats));
- }
- self._raise('fileajaxprogress', [stats]);
- };
- if (xhrobj.upload) {
- if (self.progressDelay) {
- func = $h.debounce(func, self.progressDelay);
- }
- xhrobj.upload.addEventListener('progress', func, false);
- }
- return xhrobj;
- },
- _initAjaxSettings: function () {
- var self = this;
- self._ajaxSettings = $.extend(true, {}, self.ajaxSettings);
- self._ajaxDeleteSettings = $.extend(true, {}, self.ajaxDeleteSettings);
- },
- _mergeAjaxCallback: function (funcName, srcFunc, type) {
- var self = this, settings = self._ajaxSettings, flag = self.mergeAjaxCallbacks, targFunc;
- if (type === 'delete') {
- settings = self._ajaxDeleteSettings;
- flag = self.mergeAjaxDeleteCallbacks;
- }
- targFunc = settings[funcName];
- if (flag && typeof targFunc === 'function') {
- if (flag === 'before') {
- settings[funcName] = function () {
- targFunc.apply(this, arguments);
- srcFunc.apply(this, arguments);
- };
- } else {
- settings[funcName] = function () {
- srcFunc.apply(this, arguments);
- targFunc.apply(this, arguments);
- };
- }
- } else {
- settings[funcName] = srcFunc;
- }
- },
- _ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, formdata, fileId, index, vUrl) {
- var self = this, settings, defaults, data, processQueue;
- if (!self._raise('filepreajax', [formdata, fileId, index])) {
- return;
- }
- formdata.append('initialPreview', JSON.stringify(self.initialPreview));
- formdata.append('initialPreviewConfig', JSON.stringify(self.initialPreviewConfig));
- formdata.append('initialPreviewThumbTags', JSON.stringify(self.initialPreviewThumbTags));
- self._initAjaxSettings();
- self._mergeAjaxCallback('beforeSend', fnBefore);
- self._mergeAjaxCallback('success', fnSuccess);
- self._mergeAjaxCallback('complete', fnComplete);
- self._mergeAjaxCallback('error', fnError);
- vUrl = vUrl || self.uploadUrlThumb || self.uploadUrl;
- if (typeof vUrl === 'function') {
- vUrl = vUrl();
- }
- data = self._getExtraData(fileId, index) || {};
- if (typeof data === 'object') {
- $.each(data, function (key, value) {
- formdata.append(key, value);
- });
- }
- defaults = {
- xhr: function () {
- var xhrobj = $.ajaxSettings.xhr();
- return self._initXhr(xhrobj, fileId, self.fileManager.count());
- },
- url: self._encodeURI(vUrl),
- type: 'POST',
- dataType: 'json',
- data: formdata,
- cache: false,
- processData: false,
- contentType: false
- };
- settings = $.extend(true, {}, defaults, self._ajaxSettings);
- self.ajaxQueue.push(settings);
- processQueue = function () {
- var config, xhr;
- if (self.ajaxCurrentThreads < self.maxAjaxThreads) {
- config = self.ajaxQueue.shift();
- if (typeof config !== 'undefined') {
- self.ajaxCurrentThreads++;
- xhr = $.ajax(config).done(function () {
- clearInterval(self.ajaxQueueIntervalId);
- self.ajaxCurrentThreads--;
- });
- self.ajaxRequests.push(xhr);
- }
- }
- };
- self.ajaxQueueIntervalId = setInterval(processQueue, self.queueDelay);
- },
- _mergeArray: function (prop, content) {
- var self = this, arr1 = $h.cleanArray(self[prop]), arr2 = $h.cleanArray(content);
- self[prop] = arr1.concat(arr2);
- },
- _initUploadSuccess: function (out, $thumb, allFiles) {
- var self = this, append, data, index, $div, $newCache, content, config, tags, i;
- if (!self.showPreview || typeof out !== 'object' || $.isEmptyObject(out)) {
- return;
- }
- if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
- self.hasInitData = true;
- content = out.initialPreview || [];
- config = out.initialPreviewConfig || [];
- tags = out.initialPreviewThumbTags || [];
- append = out.append === undefined || out.append;
- if (content.length > 0 && !$h.isArray(content)) {
- content = content.split(self.initialPreviewDelimiter);
- }
- if (content.length) {
- self._mergeArray('initialPreview', content);
- self._mergeArray('initialPreviewConfig', config);
- self._mergeArray('initialPreviewThumbTags', tags);
- }
- if ($thumb !== undefined) {
- if (!allFiles) {
- index = self.previewCache.add(content[0], config[0], tags[0], append);
- data = self.previewCache.get(index, false);
- $div = $(document.createElement('div')).html(data).hide().insertAfter($thumb);
- $newCache = $div.find('.kv-zoom-cache');
- if ($newCache && $newCache.length) {
- $newCache.insertAfter($thumb);
- }
- $thumb.fadeOut('slow', function () {
- var $newThumb = $div.find('.file-preview-frame');
- if ($newThumb && $newThumb.length) {
- $newThumb.insertBefore($thumb).fadeIn('slow').css('display:inline-block');
- }
- self._initPreviewActions();
- self._clearFileInput();
- $h.cleanZoomCache(self.$preview.find('#zoom-' + $thumb.attr('id')));
- $thumb.remove();
- $div.remove();
- self._initSortable();
- });
- } else {
- i = $thumb.attr('data-fileindex');
- self.uploadCache.content[i] = content[0];
- self.uploadCache.config[i] = config[0] || [];
- self.uploadCache.tags[i] = tags[0] || [];
- self.uploadCache.append = append;
- }
- } else {
- self.previewCache.set(content, config, tags, append);
- self._initPreview();
- self._initPreviewActions();
- }
- }
- },
- _initSuccessThumbs: function () {
- var self = this;
- if (!self.showPreview) {
- return;
- }
- self._getThumbs($h.FRAMES + '.file-preview-success').each(function () {
- var $thumb = $(this), $preview = self.$preview, $remove = $thumb.find('.kv-file-remove');
- $remove.removeAttr('disabled');
- self._handler($remove, 'click', function () {
- var id = $thumb.attr('id'),
- out = self._raise('filesuccessremove', [id, $thumb.attr('data-fileindex')]);
- $h.cleanMemory($thumb);
- if (out === false) {
- return;
- }
- $thumb.fadeOut('slow', function () {
- $h.cleanZoomCache($preview.find('#zoom-' + id));
- $thumb.remove();
- if (!self.getFrames().length) {
- self.reset();
- }
- });
- });
- });
- },
- _updateInitialPreview: function () {
- var self = this, u = self.uploadCache, i, j, len = 0, data = self.cacheInitialPreview;
- if (data && data.content) {
- len = data.content.length;
- }
- if (self.showPreview) {
- self.previewCache.set(u.content, u.config, u.tags, u.append);
- if (len) {
- for (i = 0; i < u.content.length; i++) {
- j = i + len;
- data.content[j] = u.content[i];
- //noinspection JSUnresolvedVariable
- if (data.config.length) {
- data.config[j] = u.config[i];
- }
- if (data.tags.length) {
- data.tags[j] = u.tags[i];
- }
- }
- self.initialPreview = $h.cleanArray(data.content);
- self.initialPreviewConfig = $h.cleanArray(data.config);
- self.initialPreviewThumbTags = $h.cleanArray(data.tags);
- } else {
- self.initialPreview = u.content;
- self.initialPreviewConfig = u.config;
- self.initialPreviewThumbTags = u.tags;
- }
- self.cacheInitialPreview = {};
- if (self.hasInitData) {
- self._initPreview();
- self._initPreviewActions();
- }
- }
- },
- _uploadSingle: function (i, id, isBatch) {
- var self = this, fm = self.fileManager, count = fm.count(), formdata = new FormData(), outData,
- previewId = self.previewInitId + '-' + i, $thumb, chkComplete, $btnUpload, $btnDelete,
- hasPostData = count > 0 || !$.isEmptyObject(self.uploadExtraData), uploadFailed, $prog, fnBefore,
- errMsg, fnSuccess, fnComplete, fnError, updateUploadLog, op = self.ajaxOperations.uploadThumb,
- fileObj = fm.getFile(id), params = {id: previewId, index: i, fileId: id},
- fileName = self.fileManager.getFileName(id, true);
- if (self.enableResumableUpload) { // not enabled for resumable uploads
- return;
- }
- if (self.showPreview) {
- $thumb = self.fileManager.getThumb(id);
- $prog = $thumb.find('.file-thumb-progress');
- $btnUpload = $thumb.find('.kv-file-upload');
- $btnDelete = $thumb.find('.kv-file-remove');
- $prog.show();
- }
- if (count === 0 || !hasPostData || (self.showPreview && $btnUpload && $btnUpload.hasClass('disabled')) ||
- self._abort(params)) {
- return;
- }
- updateUploadLog = function () {
- if (!uploadFailed) {
- fm.removeFile(id);
- } else {
- fm.errors.push(id);
- }
- fm.setProcessed(id);
- if (fm.isProcessed()) {
- self.fileBatchCompleted = true;
- }
- };
- chkComplete = function () {
- var $initThumbs;
- if (!self.fileBatchCompleted) {
- return;
- }
- setTimeout(function () {
- var triggerReset = fm.count() === 0, errCount = fm.errors.length;
- self._updateInitialPreview();
- self.unlock(triggerReset);
- if (triggerReset) {
- self._clearFileInput();
- }
- $initThumbs = self.$preview.find('.file-preview-initial');
- if (self.uploadAsync && $initThumbs.length) {
- $h.addCss($initThumbs, $h.SORT_CSS);
- self._initSortable();
- }
- self._raise('filebatchuploadcomplete', [fm.stack, self._getExtraData()]);
- if (!self.retryErrorUploads || errCount === 0) {
- fm.clear();
- }
- self._setProgress(101);
- self.ajaxAborted = false;
- }, self.processDelay);
- };
- fnBefore = function (jqXHR) {
- outData = self._getOutData(formdata, jqXHR);
- fm.initStats(id);
- self.fileBatchCompleted = false;
- if (!isBatch) {
- self.ajaxAborted = false;
- }
- if (self.showPreview) {
- if (!$thumb.hasClass('file-preview-success')) {
- self._setThumbStatus($thumb, 'Loading');
- $h.addCss($thumb, 'file-uploading');
- }
- $btnUpload.attr('disabled', true);
- $btnDelete.attr('disabled', true);
- }
- if (!isBatch) {
- self.lock();
- }
- if (fm.errors.indexOf(id) !== -1) {
- delete fm.errors[id];
- }
- self._raise('filepreupload', [outData, previewId, i]);
- $.extend(true, params, outData);
- if (self._abort(params)) {
- jqXHR.abort();
- if (!isBatch) {
- self._setThumbStatus($thumb, 'New');
- $thumb.removeClass('file-uploading');
- $btnUpload.removeAttr('disabled');
- $btnDelete.removeAttr('disabled');
- self.unlock();
- }
- self._setProgressCancelled();
- }
- };
- fnSuccess = function (data, textStatus, jqXHR) {
- var pid = self.showPreview && $thumb.attr('id') ? $thumb.attr('id') : previewId;
- outData = self._getOutData(formdata, jqXHR, data);
- $.extend(true, params, outData);
- setTimeout(function () {
- if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
- if (self.showPreview) {
- self._setThumbStatus($thumb, 'Success');
- $btnUpload.hide();
- self._initUploadSuccess(data, $thumb, isBatch);
- self._setProgress(101, $prog);
- }
- self._raise('fileuploaded', [outData, pid, i]);
- if (!isBatch) {
- self.fileManager.remove($thumb);
- } else {
- updateUploadLog();
- }
- } else {
- uploadFailed = true;
- errMsg = self._parseError(op, jqXHR, self.msgUploadError, self.fileManager.getFileName(id));
- self._showFileError(errMsg, params);
- self._setPreviewError($thumb, true);
- if (!self.retryErrorUploads) {
- $btnUpload.hide();
- }
- if (isBatch) {
- updateUploadLog();
- }
- self._setProgress(101, $('#' + pid).find('.file-thumb-progress'), self.msgUploadError);
- }
- }, self.processDelay);
- };
- fnComplete = function () {
- setTimeout(function () {
- if (self.showPreview) {
- $btnUpload.removeAttr('disabled');
- $btnDelete.removeAttr('disabled');
- $thumb.removeClass('file-uploading');
- }
- if (!isBatch) {
- self.unlock(false);
- self._clearFileInput();
- } else {
- chkComplete();
- }
- self._initSuccessThumbs();
- }, self.processDelay);
- };
- fnError = function (jqXHR, textStatus, errorThrown) {
- errMsg = self._parseError(op, jqXHR, errorThrown, self.fileManager.getFileName(id));
- uploadFailed = true;
- setTimeout(function () {
- if (isBatch) {
- updateUploadLog();
- }
- self.fileManager.setProgress(id, 100);
- self._setPreviewError($thumb, true);
- if (!self.retryErrorUploads) {
- $btnUpload.hide();
- }
- $.extend(true, params, self._getOutData(formdata, jqXHR));
- self._setProgress(101, $prog, self.msgAjaxProgressError.replace('{operation}', op));
- self._setProgress(101, $thumb.find('.file-thumb-progress'), self.msgUploadError);
- self._showFileError(errMsg, params);
- }, self.processDelay);
- };
- formdata.append(self.uploadFileAttr, fileObj.file, fileName);
- self._setUploadData(formdata, {fileId: id});
- self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, formdata, id, i);
- },
- _uploadBatch: function () {
- var self = this, fm = self.fileManager, total = fm.total(), params = {}, fnBefore, fnSuccess, fnError,
- fnComplete, hasPostData = total > 0 || !$.isEmptyObject(self.uploadExtraData), errMsg,
- setAllUploaded, formdata = new FormData(), op = self.ajaxOperations.uploadBatch;
- if (total === 0 || !hasPostData || self._abort(params)) {
- return;
- }
- setAllUploaded = function () {
- self.fileManager.clear();
- self._clearFileInput();
- };
- fnBefore = function (jqXHR) {
- self.lock();
- fm.initStats();
- var outData = self._getOutData(formdata, jqXHR);
- self.ajaxAborted = false;
- if (self.showPreview) {
- self._getThumbs().each(function () {
- var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
- $btnDelete = $thumb.find('.kv-file-remove');
- if (!$thumb.hasClass('file-preview-success')) {
- self._setThumbStatus($thumb, 'Loading');
- $h.addCss($thumb, 'file-uploading');
- }
- $btnUpload.attr('disabled', true);
- $btnDelete.attr('disabled', true);
- });
- }
- self._raise('filebatchpreupload', [outData]);
- if (self._abort(outData)) {
- jqXHR.abort();
- self._getThumbs().each(function () {
- var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
- $btnDelete = $thumb.find('.kv-file-remove');
- if ($thumb.hasClass('file-preview-loading')) {
- self._setThumbStatus($thumb, 'New');
- $thumb.removeClass('file-uploading');
- }
- $btnUpload.removeAttr('disabled');
- $btnDelete.removeAttr('disabled');
- });
- self._setProgressCancelled();
- }
- };
- fnSuccess = function (data, textStatus, jqXHR) {
- /** @namespace data.errorkeys */
- var outData = self._getOutData(formdata, jqXHR, data), key = 0,
- $thumbs = self._getThumbs(':not(.file-preview-success)'),
- keys = $h.isEmpty(data) || $h.isEmpty(data.errorkeys) ? [] : data.errorkeys;
- if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
- self._raise('filebatchuploadsuccess', [outData]);
- setAllUploaded();
- if (self.showPreview) {
- $thumbs.each(function () {
- var $thumb = $(this);
- self._setThumbStatus($thumb, 'Success');
- $thumb.removeClass('file-uploading');
- $thumb.find('.kv-file-upload').hide().removeAttr('disabled');
- });
- self._initUploadSuccess(data);
- } else {
- self.reset();
- }
- self._setProgress(101);
- } else {
- if (self.showPreview) {
- $thumbs.each(function () {
- var $thumb = $(this);
- $thumb.removeClass('file-uploading');
- $thumb.find('.kv-file-upload').removeAttr('disabled');
- $thumb.find('.kv-file-remove').removeAttr('disabled');
- if (keys.length === 0 || $.inArray(key, keys) !== -1) {
- self._setPreviewError($thumb, true);
- if (!self.retryErrorUploads) {
- $thumb.find('.kv-file-upload').hide();
- self.fileManager.remove($thumb);
- }
- } else {
- $thumb.find('.kv-file-upload').hide();
- self._setThumbStatus($thumb, 'Success');
- self.fileManager.remove($thumb);
- }
- if (!$thumb.hasClass('file-preview-error') || self.retryErrorUploads) {
- key++;
- }
- });
- self._initUploadSuccess(data);
- }
- errMsg = self._parseError(op, jqXHR, self.msgUploadError);
- self._showFileError(errMsg, outData, 'filebatchuploaderror');
- self._setProgress(101, self.$progress, self.msgUploadError);
- }
- };
- fnComplete = function () {
- self.unlock();
- self._initSuccessThumbs();
- self._clearFileInput();
- self._raise('filebatchuploadcomplete', [self.fileManager.stack, self._getExtraData()]);
- };
- fnError = function (jqXHR, textStatus, errorThrown) {
- var outData = self._getOutData(formdata, jqXHR);
- errMsg = self._parseError(op, jqXHR, errorThrown);
- self._showFileError(errMsg, outData, 'filebatchuploaderror');
- self.uploadFileCount = total - 1;
- if (!self.showPreview) {
- return;
- }
- self._getThumbs().each(function () {
- var $thumb = $(this);
- $thumb.removeClass('file-uploading');
- if (self.fileManager.getFile($thumb.attr('data-fileid'))) {
- self._setPreviewError($thumb);
- }
- });
- self._getThumbs().removeClass('file-uploading');
- self._getThumbs(' .kv-file-upload').removeAttr('disabled');
- self._getThumbs(' .kv-file-delete').removeAttr('disabled');
- self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
- };
- var ctr = 0;
- $.each(self.fileManager.stack, function (key, data) {
- if (!$h.isEmpty(data.file)) {
- formdata.append(self.uploadFileAttr, data.file, (data.nameFmt || ('untitled_' + ctr)));
- }
- ctr++;
- });
- self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, formdata);
- },
- _uploadExtraOnly: function () {
- var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError, formdata = new FormData(), errMsg,
- op = self.ajaxOperations.uploadExtra;
- if (self._abort(params)) {
- return;
- }
- fnBefore = function (jqXHR) {
- self.lock();
- var outData = self._getOutData(formdata, jqXHR);
- self._raise('filebatchpreupload', [outData]);
- self._setProgress(50);
- params.data = outData;
- params.xhr = jqXHR;
- if (self._abort(params)) {
- jqXHR.abort();
- self._setProgressCancelled();
- }
- };
- fnSuccess = function (data, textStatus, jqXHR) {
- var outData = self._getOutData(formdata, jqXHR, data);
- if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
- self._raise('filebatchuploadsuccess', [outData]);
- self._clearFileInput();
- self._initUploadSuccess(data);
- self._setProgress(101);
- } else {
- errMsg = self._parseError(op, jqXHR, self.msgUploadError);
- self._showFileError(errMsg, outData, 'filebatchuploaderror');
- }
- };
- fnComplete = function () {
- self.unlock();
- self._clearFileInput();
- self._raise('filebatchuploadcomplete', [self.fileManager.stack, self._getExtraData()]);
- };
- fnError = function (jqXHR, textStatus, errorThrown) {
- var outData = self._getOutData(formdata, jqXHR);
- errMsg = self._parseError(op, jqXHR, errorThrown);
- params.data = outData;
- self._showFileError(errMsg, outData, 'filebatchuploaderror');
- self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
- };
- self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, formdata);
- },
- _deleteFileIndex: function ($frame) {
- var self = this, ind = $frame.attr('data-fileindex'), rev = self.reversePreviewOrder;
- if (ind.substring(0, 5) === 'init_') {
- ind = parseInt(ind.replace('init_', ''));
- self.initialPreview = $h.spliceArray(self.initialPreview, ind, rev);
- self.initialPreviewConfig = $h.spliceArray(self.initialPreviewConfig, ind, rev);
- self.initialPreviewThumbTags = $h.spliceArray(self.initialPreviewThumbTags, ind, rev);
- self.getFrames().each(function () {
- var $nFrame = $(this), nInd = $nFrame.attr('data-fileindex');
- if (nInd.substring(0, 5) === 'init_') {
- nInd = parseInt(nInd.replace('init_', ''));
- if (nInd > ind) {
- nInd--;
- $nFrame.attr('data-fileindex', 'init_' + nInd);
- }
- }
- });
- if (self.uploadAsync || self.enableResumableUpload) {
- self.cacheInitialPreview = self.getPreview();
- }
- }
- },
- _initFileActions: function () {
- var self = this, $preview = self.$preview;
- if (!self.showPreview) {
- return;
- }
- self._initZoomButton();
- self.getFrames(' .kv-file-remove').each(function () {
- var $el = $(this), $frame = $el.closest($h.FRAMES), hasError, id = $frame.attr('id'),
- ind = $frame.attr('data-fileindex'), n, cap, status;
- self._handler($el, 'click', function () {
- status = self._raise('filepreremove', [id, ind]);
- if (status === false || !self._validateMinCount()) {
- return false;
- }
- hasError = $frame.hasClass('file-preview-error');
- $h.cleanMemory($frame);
- $frame.fadeOut('slow', function () {
- $h.cleanZoomCache($preview.find('#zoom-' + id));
- self.fileManager.remove($frame);
- self._clearObjects($frame);
- $frame.remove();
- if (id && hasError) {
- self.$errorContainer.find('li[data-thumb-id="' + id + '"]').fadeOut('fast', function () {
- $(this).remove();
- if (!self._errorsExist()) {
- self._resetErrors();
- }
- });
- }
- self._clearFileInput();
- var chk = self.previewCache.count(true), len = self.fileManager.count(),
- file, hasThumb = self.showPreview && self.getFrames().length;
- if (len === 0 && chk === 0 && !hasThumb) {
- self.reset();
- } else {
- n = chk + len;
- if (n > 1) {
- cap = self._getMsgSelected(n);
- } else {
- file = self.fileManager.getFirstFile();
- cap = file ? file.nameFmt : '_';
- }
- self._setCaption(cap);
- }
- self._raise('fileremoved', [id, ind]);
- });
- });
- });
- self.getFrames(' .kv-file-upload').each(function () {
- var $el = $(this);
- self._handler($el, 'click', function () {
- var $frame = $el.closest($h.FRAMES), id = $frame.attr('data-fileid');
- self.$progress.hide();
- if ($frame.hasClass('file-preview-error') && !self.retryErrorUploads) {
- return;
- }
- self._uploadSingle(self.fileManager.getIndex(id), id, false);
- });
- });
- },
- _initPreviewActions: function () {
- var self = this, $preview = self.$preview, deleteExtraData = self.deleteExtraData || {},
- btnRemove = $h.FRAMES + ' .kv-file-remove', settings = self.fileActionSettings,
- origClass = settings.removeClass, errClass = settings.removeErrorClass,
- resetProgress = function () {
- var hasFiles = self.isAjaxUpload ? self.previewCache.count(true) : self._inputFileCount();
- if (!self.getFrames().length && !hasFiles) {
- self._setCaption('');
- self.reset();
- self.initialCaption = '';
- }
- };
- self._initZoomButton();
- $preview.find(btnRemove).each(function () {
- var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key'), errMsg, fnBefore,
- fnSuccess, fnError, op = self.ajaxOperations.deleteThumb;
- if ($h.isEmpty(vUrl) || vKey === undefined) {
- return;
- }
- if (typeof vUrl === 'function') {
- vUrl = vUrl();
- }
- var $frame = $el.closest($h.FRAMES), cache = self.previewCache.data, settings, params, config,
- fileName, extraData, index = $frame.attr('data-fileindex');
- index = parseInt(index.replace('init_', ''));
- config = $h.isEmpty(cache.config) && $h.isEmpty(cache.config[index]) ? null : cache.config[index];
- extraData = $h.isEmpty(config) || $h.isEmpty(config.extra) ? deleteExtraData : config.extra;
- fileName = config.filename || config.caption || '';
- if (typeof extraData === 'function') {
- extraData = extraData();
- }
- params = {id: $el.attr('id'), key: vKey, extra: extraData};
- fnBefore = function (jqXHR) {
- self.ajaxAborted = false;
- self._raise('filepredelete', [vKey, jqXHR, extraData]);
- if (self._abort()) {
- jqXHR.abort();
- } else {
- $el.removeClass(errClass);
- $h.addCss($frame, 'file-uploading');
- $h.addCss($el, 'disabled ' + origClass);
- }
- };
- fnSuccess = function (data, textStatus, jqXHR) {
- var n, cap;
- if (!$h.isEmpty(data) && !$h.isEmpty(data.error)) {
- params.jqXHR = jqXHR;
- params.response = data;
- errMsg = self._parseError(op, jqXHR, self.msgDeleteError, fileName);
- self._showFileError(errMsg, params, 'filedeleteerror');
- $frame.removeClass('file-uploading');
- $el.removeClass('disabled ' + origClass).addClass(errClass);
- resetProgress();
- return;
- }
- $frame.removeClass('file-uploading').addClass('file-deleted');
- $frame.fadeOut('slow', function () {
- index = parseInt(($frame.attr('data-fileindex')).replace('init_', ''));
- self.previewCache.unset(index);
- self._deleteFileIndex($frame);
- n = self.previewCache.count(true);
- cap = n > 0 ? self._getMsgSelected(n) : '';
- self._setCaption(cap);
- self._raise('filedeleted', [vKey, jqXHR, extraData]);
- $h.cleanZoomCache($preview.find('#zoom-' + $frame.attr('id')));
- self._clearObjects($frame);
- $frame.remove();
- resetProgress();
- });
- };
- fnError = function (jqXHR, textStatus, errorThrown) {
- var errMsg = self._parseError(op, jqXHR, errorThrown, fileName);
- params.jqXHR = jqXHR;
- params.response = {};
- self._showFileError(errMsg, params, 'filedeleteerror');
- $frame.removeClass('file-uploading');
- $el.removeClass('disabled ' + origClass).addClass(errClass);
- resetProgress();
- };
- self._initAjaxSettings();
- self._mergeAjaxCallback('beforeSend', fnBefore, 'delete');
- self._mergeAjaxCallback('success', fnSuccess, 'delete');
- self._mergeAjaxCallback('error', fnError, 'delete');
- settings = $.extend(true, {}, {
- url: self._encodeURI(vUrl),
- type: 'POST',
- dataType: 'json',
- data: $.extend(true, {}, {key: vKey}, extraData)
- }, self._ajaxDeleteSettings);
- self._handler($el, 'click', function () {
- if (!self._validateMinCount()) {
- return false;
- }
- self.ajaxAborted = false;
- self._raise('filebeforedelete', [vKey, extraData]);
- //noinspection JSUnresolvedVariable,JSHint
- if (self.ajaxAborted instanceof Promise) {
- self.ajaxAborted.then(function (result) {
- if (!result) {
- $.ajax(settings);
- }
- });
- } else {
- if (!self.ajaxAborted) {
- $.ajax(settings);
- }
- }
- });
- });
- },
- _hideFileIcon: function () {
- var self = this;
- if (self.overwriteInitial) {
- self.$captionContainer.removeClass('icon-visible');
- }
- },
- _showFileIcon: function () {
- var self = this;
- $h.addCss(self.$captionContainer, 'icon-visible');
- },
- _getSize: function (bytes, sizes) {
- var self = this, size = parseFloat(bytes), i, func = self.fileSizeGetter, out;
- if (!$.isNumeric(bytes) || !$.isNumeric(size)) {
- return '';
- }
- if (typeof func === 'function') {
- out = func(size);
- } else {
- if (size === 0) {
- out = '0.00 B';
- } else {
- i = Math.floor(Math.log(size) / Math.log(1024));
- if (!sizes) {
- sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
- }
- out = (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + sizes[i];
- }
- }
- return self._getLayoutTemplate('size').replace('{sizeText}', out);
- },
- _getFileType: function (ftype) {
- var self = this;
- return self.mimeTypeAliases[ftype] || ftype;
- },
- _generatePreviewTemplate: function (
- cat,
- data,
- fname,
- ftype,
- previewId,
- fileId,
- isError,
- size,
- frameClass,
- foot,
- ind,
- templ,
- attrs,
- zoomData
- ) {
- var self = this, caption = self.slug(fname), prevContent, zoomContent = '', styleAttribs = '',
- screenW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
- config, newCat = self.preferIconicPreview ? 'other' : cat, title = caption, alt = caption,
- footer = foot || self._renderFileFooter(cat, caption, size, 'auto', isError),
- hasIconSetting = self._getPreviewIcon(fname), typeCss = 'type-default',
- forcePrevIcon = hasIconSetting && self.preferIconicPreview,
- forceZoomIcon = hasIconSetting && self.preferIconicZoomPreview, getContent;
- config = screenW < 400 ? (self.previewSettingsSmall[newCat] || self.defaults.previewSettingsSmall[newCat]) :
- (self.previewSettings[newCat] || self.defaults.previewSettings[newCat]);
- if (config) {
- $.each(config, function (key, val) {
- styleAttribs += key + ':' + val + ';';
- });
- }
- getContent = function (c, d, zoom, frameCss) {
- var id = zoom ? 'zoom-' + previewId : previewId, tmplt = self._getPreviewTemplate(c),
- css = (frameClass || '') + ' ' + frameCss;
- if (self.frameClass) {
- css = self.frameClass + ' ' + css;
- }
- if (zoom) {
- css = css.replace(' ' + $h.SORT_CSS, '');
- }
- tmplt = self._parseFilePreviewIcon(tmplt, fname);
- if (c === 'text') {
- d = $h.htmlEncode(d);
- }
- if (cat === 'object' && !ftype) {
- $.each(self.defaults.fileTypeSettings, function (key, func) {
- if (key === 'object' || key === 'other') {
- return;
- }
- if (func(fname, ftype)) {
- typeCss = 'type-' + key;
- }
- });
- }
- if (!$h.isEmpty(attrs)) {
- if (attrs.title !== undefined && attrs.title !== null) {
- title = attrs.title;
- }
- if (attrs.alt !== undefined && attrs.alt !== null) {
- title = attrs.alt;
- }
- }
- return tmplt.setTokens({
- 'previewId': id,
- 'caption': caption,
- 'title': title,
- 'alt': alt,
- 'frameClass': css,
- 'type': self._getFileType(ftype),
- 'fileindex': ind,
- 'fileid': fileId || '',
- 'typeCss': typeCss,
- 'footer': footer,
- 'data': d,
- 'template': templ || cat,
- 'style': styleAttribs ? 'style="' + styleAttribs + '"' : ''
- });
- };
- ind = ind || previewId.slice(previewId.lastIndexOf('-') + 1);
- if (self.fileActionSettings.showZoom) {
- zoomContent = getContent((forceZoomIcon ? 'other' : cat), zoomData ? zoomData : data, true,
- 'kv-zoom-thumb');
- }
- zoomContent = '\n' + self._getLayoutTemplate('zoomCache').replace('{zoomContent}', zoomContent);
- if (typeof self.sanitizeZoomCache === 'function') {
- zoomContent = self.sanitizeZoomCache(zoomContent);
- }
- prevContent = getContent((forcePrevIcon ? 'other' : cat), data, false, 'kv-preview-thumb');
- return prevContent + zoomContent;
- },
- _addToPreview: function ($preview, content) {
- var self = this;
- return self.reversePreviewOrder ? $preview.prepend(content) : $preview.append(content);
- },
- _previewDefault: function (file, previewId, isDisabled) {
- var self = this, $preview = self.$preview;
- if (!self.showPreview) {
- return;
- }
- var fname = $h.getFileName(file), ftype = file ? file.type : '', content, size = file.size || 0,
- caption = self._getFileName(file, ''), isError = isDisabled === true && !self.isAjaxUpload,
- data = $h.createObjectURL(file), fileId = self.fileManager.getId(file);
- self._clearDefaultPreview();
- content = self._generatePreviewTemplate('other', data, fname, ftype, previewId, fileId, isError, size);
- self._addToPreview($preview, content);
- self._setThumbAttr(previewId, caption, size);
- if (isDisabled === true && self.isAjaxUpload) {
- self._setThumbStatus($('#' + previewId), 'Error');
- }
- },
- canPreview: function (file) {
- var self = this;
- if (!file || !self.showPreview || !self.$preview || !self.$preview.length) {
- return false;
- }
- var name = file.name || '', type = file.type || '', size = (file.size || 0) / 1000,
- cat = self._parseFileType(type, name), allowedTypes, allowedMimes, allowedExts, skipPreview,
- types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes,
- exts = self.allowedPreviewExtensions || [], dTypes = self.disabledPreviewTypes,
- dMimes = self.disabledPreviewMimeTypes, dExts = self.disabledPreviewExtensions || [],
- maxSize = self.maxFilePreviewSize && parseFloat(self.maxFilePreviewSize) || 0,
- expAllExt = new RegExp('\\.(' + exts.join('|') + ')$', 'i'),
- expDisExt = new RegExp('\\.(' + dExts.join('|') + ')$', 'i');
- allowedTypes = !types || types.indexOf(cat) !== -1;
- allowedMimes = !mimes || mimes.indexOf(type) !== -1;
- allowedExts = !exts.length || $h.compare(name, expAllExt);
- skipPreview = (dTypes && dTypes.indexOf(cat) !== -1) || (dMimes && dMimes.indexOf(type) !== -1) ||
- (dExts.length && $h.compare(name, expDisExt)) || (maxSize && !isNaN(maxSize) && size > maxSize);
- return !skipPreview && (allowedTypes || allowedMimes || allowedExts);
- },
- _previewFile: function (i, file, theFile, previewId, data, fileInfo) {
- if (!this.showPreview) {
- return;
- }
- var self = this, fname = $h.getFileName(file), ftype = fileInfo.type, caption = fileInfo.name,
- cat = self._parseFileType(ftype, fname), content, $preview = self.$preview, fsize = file.size || 0,
- iData = (cat === 'text' || cat === 'html' || cat === 'image') ? theFile.target.result : data,
- fileId = self.fileManager.getId(file);
- /** @namespace window.DOMPurify */
- if (cat === 'html' && self.purifyHtml && window.DOMPurify) {
- iData = window.DOMPurify.sanitize(iData);
- }
- content = self._generatePreviewTemplate(cat, iData, fname, ftype, previewId, fileId, false, fsize);
- self._clearDefaultPreview();
- self._addToPreview($preview, content);
- var $thumb = $preview.find('#' + previewId), $img = $thumb.find('img'), id = $thumb.attr('data-fileid');
- self._validateImageOrientation($img, file, previewId, id, caption, ftype, fsize, iData);
- self._setThumbAttr(previewId, caption, fsize);
- self._initSortable();
- },
- _setThumbAttr: function (id, caption, size) {
- var self = this, $frame = $('#' + id);
- if ($frame.length) {
- size = size && size > 0 ? self._getSize(size) : '';
- $frame.data({'caption': caption, 'size': size});
- }
- },
- _setInitThumbAttr: function () {
- var self = this, data = self.previewCache.data, len = self.previewCache.count(true), config,
- caption, size, previewId;
- if (len === 0) {
- return;
- }
- for (var i = 0; i < len; i++) {
- config = data.config[i];
- previewId = self.previewInitId + '-' + 'init_' + i;
- caption = $h.ifSet('caption', config, $h.ifSet('filename', config));
- size = $h.ifSet('size', config);
- self._setThumbAttr(previewId, caption, size);
- }
- },
- _slugDefault: function (text) {
- // noinspection RegExpRedundantEscape
- return $h.isEmpty(text) ? '' : String(text).replace(/[\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_');
- },
- _updateFileDetails: function (numFiles) {
- var self = this, $el = self.$element, label, n, log, nFiles, file,
- name = ($h.isIE(9) && $h.findFileName($el.val())) || ($el[0].files[0] && $el[0].files[0].name);
- if (!name && self.fileManager.count() > 0) {
- file = self.fileManager.getFirstFile();
- label = file.nameFmt;
- } else {
- label = name ? self.slug(name) : '_';
- }
- n = self.isAjaxUpload ? self.fileManager.count() : numFiles;
- nFiles = self.previewCache.count(true) + n;
- log = n === 1 ? label : self._getMsgSelected(nFiles);
- if (self.isError) {
- self.$previewContainer.removeClass('file-thumb-loading');
- self.$previewStatus.html('');
- self.$captionContainer.removeClass('icon-visible');
- } else {
- self._showFileIcon();
- }
- self._setCaption(log, self.isError);
- self.$container.removeClass('file-input-new file-input-ajax-new');
- if (arguments.length === 1) {
- self._raise('fileselect', [numFiles, label]);
- }
- if (self.previewCache.count(true)) {
- self._initPreviewActions();
- }
- },
- _setThumbStatus: function ($thumb, status) {
- var self = this;
- if (!self.showPreview) {
- return;
- }
- var icon = 'indicator' + status, msg = icon + 'Title',
- css = 'file-preview-' + status.toLowerCase(),
- $indicator = $thumb.find('.file-upload-indicator'),
- config = self.fileActionSettings;
- $thumb.removeClass('file-preview-success file-preview-error file-preview-paused file-preview-loading');
- if (status === 'Success') {
- $thumb.find('.file-drag-handle').remove();
- }
- $indicator.html(config[icon]);
- $indicator.attr('title', config[msg]);
- $thumb.addClass(css);
- if (status === 'Error' && !self.retryErrorUploads) {
- $thumb.find('.kv-file-upload').attr('disabled', true);
- }
- },
- _setProgressCancelled: function () {
- var self = this;
- self._setProgress(101, self.$progress, self.msgCancelled);
- },
- _setProgress: function (p, $el, error, stats) {
- var self = this;
- $el = $el || self.$progress;
- if (!$el.length) {
- return;
- }
- var pct = Math.min(p, 100), out, pctLimit = self.progressUploadThreshold,
- t = p <= 100 ? self.progressTemplate : self.progressCompleteTemplate,
- template = pct < 100 ? self.progressTemplate :
- (error ? (self.paused ? self.progressPauseTemplate : self.progressErrorTemplate) : t);
- if (p >= 100) {
- stats = '';
- }
- if (!$h.isEmpty(template)) {
- if (pctLimit && pct > pctLimit && p <= 100) {
- out = template.setTokens({'percent': pctLimit, 'status': self.msgUploadThreshold});
- } else {
- out = template.setTokens({'percent': pct, 'status': (p > 100 ? self.msgUploadEnd : pct + '%')});
- }
- stats = stats || '';
- out = out.setTokens({stats: stats});
- $el.html(out);
- if (error) {
- $el.find('[role="progressbar"]').html(error);
- }
- }
- },
- _setFileDropZoneTitle: function () {
- var self = this, $zone = self.$container.find('.file-drop-zone'), title = self.dropZoneTitle, strFiles;
- if (self.isClickable) {
- strFiles = $h.isEmpty(self.$element.attr('multiple')) ? self.fileSingle : self.filePlural;
- title += self.dropZoneClickTitle.replace('{files}', strFiles);
- }
- $zone.find('.' + self.dropZoneTitleClass).remove();
- if (!self.showPreview || $zone.length === 0 || self.fileManager.count() > 0 || !self.dropZoneEnabled ||
- (!self.isAjaxUpload && self.$element.files)) {
- return;
- }
- if ($zone.find($h.FRAMES).length === 0 && $h.isEmpty(self.defaultPreviewContent)) {
- $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + title + '</div>');
- }
- self.$container.removeClass('file-input-new');
- $h.addCss(self.$container, 'file-input-ajax-new');
- },
- _getStats: function (stats) {
- var self = this, pendingTime, t;
- if (!self.showUploadStats || !stats || !stats.bitrate) {
- return '';
- }
- t = self._getLayoutTemplate('stats');
- pendingTime = (!stats.elapsed || !stats.bps) ? self.msgCalculatingTime :
- self.msgPendingTime.setTokens({time: $h.getElapsed(Math.ceil(stats.pendingBytes / stats.bps))});
- return t.setTokens({
- uploadSpeed: stats.bitrate,
- pendingTime: pendingTime
- });
- },
- _setResumableProgress: function (pct, stats, $thumb) {
- var self = this, rm = self.resumableManager, obj = $thumb ? rm : self,
- $prog = $thumb ? $thumb.find('.file-thumb-progress') : null;
- if (obj.lastProgress === 0) {
- obj.lastProgress = pct;
- }
- if (pct < obj.lastProgress) {
- pct = obj.lastProgress;
- }
- self._setProgress(pct, $prog, null, self._getStats(stats));
- obj.lastProgress = pct;
- },
- _setFileUploadStats: function (id, pct, total, stats) {
- var self = this, $prog = self.$progress;
- if (!self.showPreview && (!$prog || !$prog.length)) {
- return;
- }
- var fm = self.fileManager, $thumb = fm.getThumb(id), pctTot, rm = self.resumableManager,
- totUpSize = 0, totSize = fm.getTotalSize(), totStats = $.extend(true, {}, stats);
- if (self.enableResumableUpload) {
- var loaded = stats.loaded, currUplSize = rm.getUploadedSize(), currTotSize = rm.file.size, totLoaded;
- loaded += currUplSize;
- totLoaded = fm.uploadedSize + loaded;
- pct = $h.round(100 * loaded / currTotSize);
- stats.pendingBytes = currTotSize - currUplSize;
- self._setResumableProgress(pct, stats, $thumb);
- pctTot = Math.floor(100 * totLoaded / totSize);
- totStats.pendingBytes = totSize - totLoaded;
- self._setResumableProgress(pctTot, totStats);
- } else {
- fm.setProgress(id, pct);
- $prog = $thumb && $thumb.length ? $thumb.find('.file-thumb-progress') : null;
- self._setProgress(pct, $prog, null, self._getStats(stats));
- $.each(fm.stats, function (id, cfg) {
- totUpSize += cfg.loaded;
- });
- totStats.pendingBytes = totSize - totUpSize;
- pctTot = $h.round(totUpSize / totSize * 100);
- self._setProgress(pctTot, null, null, self._getStats(totStats));
- }
- },
- _validateMinCount: function () {
- var self = this, len = self.isAjaxUpload ? self.fileManager.count() : self._inputFileCount();
- if (self.validateInitialCount && self.minFileCount > 0 && self._getFileCount(len - 1) < self.minFileCount) {
- self._noFilesError({});
- return false;
- }
- return true;
- },
- _getFileCount: function (fileCount) {
- var self = this, addCount = 0;
- if (self.validateInitialCount && !self.overwriteInitial) {
- addCount = self.previewCache.count(true);
- fileCount += addCount;
- }
- return fileCount;
- },
- _getFileId: function (file) {
- return $h.getFileId(file, this.generateFileId);
- },
- _getFileName: function (file, defaultValue) {
- var self = this, fileName = $h.getFileName(file);
- return fileName ? self.slug(fileName) : defaultValue;
- },
- _getFileNames: function (skipNull) {
- var self = this;
- return self.filenames.filter(function (n) {
- return (skipNull ? n !== undefined : n !== undefined && n !== null);
- });
- },
- _setPreviewError: function ($thumb, keepFile) {
- var self = this, removeFrame = self.removeFromPreviewOnError && !self.retryErrorUploads;
- if (!keepFile || removeFrame) {
- self.fileManager.remove($thumb);
- }
- if (!self.showPreview) {
- return;
- }
- if (removeFrame) {
- $thumb.remove();
- return;
- } else {
- self._setThumbStatus($thumb, 'Error');
- }
- self._refreshUploadButton($thumb);
- },
- _refreshUploadButton: function ($thumb) {
- var self = this, $btn = $thumb.find('.kv-file-upload'), cfg = self.fileActionSettings,
- icon = cfg.uploadIcon, title = cfg.uploadTitle;
- if (!$btn.length) {
- return;
- }
- if (self.retryErrorUploads) {
- icon = cfg.uploadRetryIcon;
- title = cfg.uploadRetryTitle;
- }
- $btn.attr('title', title).html(icon);
- },
- _checkDimensions: function (i, chk, $img, $thumb, fname, type, params) {
- var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max', limit = self[tag + 'Image' + type],
- $imgEl, isValid;
- if ($h.isEmpty(limit) || !$img.length) {
- return;
- }
- $imgEl = $img[0];
- dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height;
- isValid = chk === 'Small' ? dim >= limit : dim <= limit;
- if (isValid) {
- return;
- }
- msg = self['msgImage' + type + chk].setTokens({'name': fname, 'size': limit});
- self._showFileError(msg, params);
- self._setPreviewError($thumb);
- },
- _getExifObj: function (data) {
- var self = this, exifObj = null, error = $h.logMessages.exifWarning;
- if (data.slice(0, 23) !== 'data:image/jpeg;base64,' && data.slice(0, 22) !== 'data:image/jpg;base64,') {
- exifObj = null;
- return;
- }
- try {
- exifObj = window.piexif ? window.piexif.load(data) : null;
- } catch (err) {
- exifObj = null;
- error = err && err.message || '';
- }
- if (!exifObj) {
- self._log($h.logMessages.badExifParser, {details: error});
- }
- return exifObj;
- },
- setImageOrientation: function ($img, $zoomImg, value, $thumb) {
- var self = this, invalidImg = !$img || !$img.length, invalidZoomImg = !$zoomImg || !$zoomImg.length, $mark,
- isHidden = false, $div, zoomOnly = invalidImg && $thumb && $thumb.attr('data-template') === 'image', ev;
- if (invalidImg && invalidZoomImg) {
- return;
- }
- ev = 'load.fileinputimageorient';
- if (zoomOnly) {
- $img = $zoomImg;
- $zoomImg = null;
- $img.css(self.previewSettings.image);
- $div = $(document.createElement('div')).appendTo($thumb.find('.kv-file-content'));
- $mark = $(document.createElement('span')).insertBefore($img);
- $img.css('visibility', 'hidden').removeClass('file-zoom-detail').appendTo($div);
- } else {
- isHidden = !$img.is(':visible');
- }
- $img.off(ev).on(ev, function () {
- if (isHidden) {
- self.$preview.removeClass('hide-content');
- $thumb.find('.kv-file-content').css('visibility', 'hidden');
- }
- var img = $img.get(0), zoomImg = $zoomImg && $zoomImg.length ? $zoomImg.get(0) : null,
- h = img.offsetHeight, w = img.offsetWidth, r = $h.getRotation(value);
- if (isHidden) {
- $thumb.find('.kv-file-content').css('visibility', 'visible');
- self.$preview.addClass('hide-content');
- }
- $img.data('orientation', value);
- if (zoomImg) {
- $zoomImg.data('orientation', value);
- }
- if (value < 5) {
- $h.setTransform(img, r);
- $h.setTransform(zoomImg, r);
- return;
- }
- var offsetAngle = Math.atan(w / h), origFactor = Math.sqrt(Math.pow(h, 2) + Math.pow(w, 2)),
- scale = !origFactor ? 1 : (h / Math.cos(Math.PI / 2 + offsetAngle)) / origFactor,
- s = ' scale(' + Math.abs(scale) + ')';
- $h.setTransform(img, r + s);
- $h.setTransform(zoomImg, r + s);
- if (zoomOnly) {
- $img.css('visibility', 'visible').insertAfter($mark).addClass('file-zoom-detail');
- $mark.remove();
- $div.remove();
- }
- });
- },
- _validateImageOrientation: function ($img, file, previewId, fileId, caption, ftype, fsize, iData) {
- var self = this, exifObj, value, autoOrientImage = self.autoOrientImage;
- exifObj = autoOrientImage ? self._getExifObj(iData) : null;
- value = exifObj ? exifObj['0th'][piexif.ImageIFD.Orientation] : null; // jshint ignore:line
- if (!value) {
- self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj);
- return;
- }
- self.setImageOrientation($img, $('#zoom-' + previewId + ' img'), value, $('#' + previewId));
- self._raise('fileimageoriented', {'$img': $img, 'file': file});
- self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj);
- },
- _validateImage: function (previewId, fileId, fname, ftype, fsize, iData, exifObj) {
- var self = this, $preview = self.$preview, params, w1, w2, $thumb = $preview.find('#' + previewId),
- i = $thumb.attr('data-fileindex'), $img = $thumb.find('img');
- fname = fname || 'Untitled';
- $img.one('load', function () {
- w1 = $thumb.width();
- w2 = $preview.width();
- if (w1 > w2) {
- $img.css('width', '100%');
- }
- params = {ind: i, id: previewId, fileId: fileId};
- self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
- self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
- if (!self.resizeImage) {
- self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
- self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
- }
- self._raise('fileimageloaded', [previewId]);
- self.fileManager.addImage(fileId, {
- ind: i,
- img: $img,
- thumb: $thumb,
- pid: previewId,
- typ: ftype,
- siz: fsize,
- validated: false,
- imgData: iData,
- exifObj: exifObj
- });
- $thumb.data('exif', exifObj);
- self._validateAllImages();
- }).one('error', function () {
- self._raise('fileimageloaderror', [previewId]);
- }).each(function () {
- if (this.complete) {
- $(this).trigger('load');
- } else {
- if (this.error) {
- $(this).trigger('error');
- }
- }
- });
- },
- _validateAllImages: function () {
- var self = this, counter = {val: 0}, numImgs = self.fileManager.getImageCount(), fsize,
- minSize = self.resizeIfSizeMoreThan;
- if (numImgs !== self.fileManager.totalImages) {
- return;
- }
- self._raise('fileimagesloaded');
- if (!self.resizeImage) {
- return;
- }
- $.each(self.fileManager.loadedImages, function (id, config) {
- if (!config.validated) {
- fsize = config.siz;
- if (fsize && fsize > minSize * 1000) {
- self._getResizedImage(id, config, counter, numImgs);
- }
- config.validated = true;
- }
- });
- },
- _getResizedImage: function (id, config, counter, numImgs) {
- var self = this, img = $(config.img)[0], width = img.naturalWidth, height = img.naturalHeight, blob,
- ratio = 1, maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height,
- isValidImage = !!(width && height), chkWidth, chkHeight, canvas = self.imageCanvas, dataURI,
- context = self.imageCanvasContext, type = config.typ, pid = config.pid, ind = config.ind,
- $thumb = config.thumb, throwError, msg, exifObj = config.exifObj, exifStr, file, params, evParams;
- throwError = function (msg, params, ev) {
- if (self.isAjaxUpload) {
- self._showFileError(msg, params, ev);
- } else {
- self._showError(msg, params, ev);
- }
- self._setPreviewError($thumb);
- };
- file = self.fileManager.getFile(id);
- params = {id: pid, 'index': ind, fileId: id};
- evParams = [id, pid, ind];
- if (!file || !isValidImage || (width <= maxWidth && height <= maxHeight)) {
- if (isValidImage && file) {
- self._raise('fileimageresized', evParams);
- }
- counter.val++;
- if (counter.val === numImgs) {
- self._raise('fileimagesresized');
- }
- if (!isValidImage) {
- throwError(self.msgImageResizeError, params, 'fileimageresizeerror');
- return;
- }
- }
- type = type || self.resizeDefaultImageType;
- chkWidth = width > maxWidth;
- chkHeight = height > maxHeight;
- if (self.resizePreference === 'width') {
- ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1);
- } else {
- ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1);
- }
- self._resetCanvas();
- width *= ratio;
- height *= ratio;
- canvas.width = width;
- canvas.height = height;
- try {
- context.drawImage(img, 0, 0, width, height);
- dataURI = canvas.toDataURL(type, self.resizeQuality);
- if (exifObj) {
- exifStr = window.piexif.dump(exifObj);
- dataURI = window.piexif.insert(exifStr, dataURI);
- }
- blob = $h.dataURI2Blob(dataURI);
- self.fileManager.setFile(id, blob);
- self._raise('fileimageresized', evParams);
- counter.val++;
- if (counter.val === numImgs) {
- self._raise('fileimagesresized', [undefined, undefined]);
- }
- if (!(blob instanceof Blob)) {
- throwError(self.msgImageResizeError, params, 'fileimageresizeerror');
- }
- }
- catch (err) {
- counter.val++;
- if (counter.val === numImgs) {
- self._raise('fileimagesresized', [undefined, undefined]);
- }
- msg = self.msgImageResizeException.replace('{errors}', err.message);
- throwError(msg, params, 'fileimageresizeexception');
- }
- },
- _initBrowse: function ($container) {
- var self = this, $el = self.$element;
- if (self.showBrowse) {
- self.$btnFile = $container.find('.btn-file').append($el);
- } else {
- $el.appendTo($container).attr('tabindex', -1);
- $h.addCss($el, 'file-no-browse');
- }
- },
- _initClickable: function () {
- var self = this, $zone, $tmpZone;
- if (!self.isClickable) {
- return;
- }
- $zone = self.$dropZone;
- if (!self.isAjaxUpload) {
- $tmpZone = self.$preview.find('.file-default-preview');
- if ($tmpZone.length) {
- $zone = $tmpZone;
- }
- }
- $h.addCss($zone, 'clickable');
- $zone.attr('tabindex', -1);
- self._handler($zone, 'click', function (e) {
- var $tar = $(e.target);
- if (!$(self.elErrorContainer + ':visible').length &&
- (!$tar.parents('.file-preview-thumbnails').length || $tar.parents(
- '.file-default-preview').length)) {
- self.$element.data('zoneClicked', true).trigger('click');
- $zone.blur();
- }
- });
- },
- _initCaption: function () {
- var self = this, cap = self.initialCaption || '';
- if (self.overwriteInitial || $h.isEmpty(cap)) {
- self.$caption.val('');
- return false;
- }
- self._setCaption(cap);
- return true;
- },
- _setCaption: function (content, isError) {
- var self = this, title, out, icon, n, cap, file;
- if (!self.$caption.length) {
- return;
- }
- self.$captionContainer.removeClass('icon-visible');
- if (isError) {
- title = $('<div>' + self.msgValidationError + '</div>').text();
- n = self.fileManager.count();
- if (n) {
- file = self.fileManager.getFirstFile();
- cap = n === 1 && file ? file.nameFmt : self._getMsgSelected(n);
- } else {
- cap = self._getMsgSelected(self.msgNo);
- }
- out = $h.isEmpty(content) ? cap : content;
- icon = '<span class="' + self.msgValidationErrorClass + '">' + self.msgValidationErrorIcon + '</span>';
- } else {
- if ($h.isEmpty(content)) {
- return;
- }
- title = $('<div>' + content + '</div>').text();
- out = title;
- icon = self._getLayoutTemplate('fileIcon');
- }
- self.$captionContainer.addClass('icon-visible');
- self.$caption.attr('title', title).val(out);
- self.$captionIcon.html(icon);
- },
- _createContainer: function () {
- var self = this, attribs = {'class': 'file-input file-input-new' + (self.rtl ? ' kv-rtl' : '')},
- $container = $(document.createElement('div')).attr(attribs).html(self._renderMain());
- $container.insertBefore(self.$element);
- self._initBrowse($container);
- if (self.theme) {
- $container.addClass('theme-' + self.theme);
- }
- return $container;
- },
- _refreshContainer: function () {
- var self = this, $container = self.$container, $el = self.$element;
- $el.insertAfter($container);
- $container.html(self._renderMain());
- self._initBrowse($container);
- self._validateDisabled();
- },
- _validateDisabled: function () {
- var self = this;
- self.$caption.attr({readonly: self.isDisabled});
- },
- _renderMain: function () {
- var self = this,
- dropCss = self.dropZoneEnabled ? ' file-drop-zone' : 'file-drop-disabled',
- close = !self.showClose ? '' : self._getLayoutTemplate('close'),
- preview = !self.showPreview ? '' : self._getLayoutTemplate('preview')
- .setTokens({'class': self.previewClass, 'dropClass': dropCss}),
- css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
- caption = self.captionTemplate.setTokens({'class': css + ' kv-fileinput-caption'});
- return self.mainTemplate.setTokens({
- 'class': self.mainClass + (!self.showBrowse && self.showCaption ? ' no-browse' : ''),
- 'preview': preview,
- 'close': close,
- 'caption': caption,
- 'upload': self._renderButton('upload'),
- 'remove': self._renderButton('remove'),
- 'cancel': self._renderButton('cancel'),
- 'pause': self._renderButton('pause'),
- 'browse': self._renderButton('browse')
- });
- },
- _renderButton: function (type) {
- var self = this, tmplt = self._getLayoutTemplate('btnDefault'), css = self[type + 'Class'],
- title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'],
- status = self.isDisabled ? ' disabled' : '', btnType = 'button';
- switch (type) {
- case 'remove':
- if (!self.showRemove) {
- return '';
- }
- break;
- case 'cancel':
- if (!self.showCancel) {
- return '';
- }
- css += ' kv-hidden';
- break;
- case 'pause':
- if (!self.showPause) {
- return '';
- }
- css += ' kv-hidden';
- break;
- case 'upload':
- if (!self.showUpload) {
- return '';
- }
- if (self.isAjaxUpload && !self.isDisabled) {
- tmplt = self._getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl);
- } else {
- btnType = 'submit';
- }
- break;
- case 'browse':
- if (!self.showBrowse) {
- return '';
- }
- tmplt = self._getLayoutTemplate('btnBrowse');
- break;
- default:
- return '';
- }
- css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button';
- if (!$h.isEmpty(label)) {
- label = ' <span class="' + self.buttonLabelClass + '">' + label + '</span>';
- }
- return tmplt.setTokens({
- 'type': btnType, 'css': css, 'title': title, 'status': status, 'icon': icon, 'label': label
- });
- },
- _renderThumbProgress: function () {
- var self = this;
- return '<div class="file-thumb-progress kv-hidden">' +
- self.progressInfoTemplate.setTokens({percent: 101, status: self.msgUploadBegin, stats: ''}) +
- '</div>';
- },
- _renderFileFooter: function (cat, caption, size, width, isError) {
- var self = this, config = self.fileActionSettings, rem = config.showRemove, drg = config.showDrag,
- upl = config.showUpload, zoom = config.showZoom, out, params,
- template = self._getLayoutTemplate('footer'), tInd = self._getLayoutTemplate('indicator'),
- ind = isError ? config.indicatorError : config.indicatorNew,
- title = isError ? config.indicatorErrorTitle : config.indicatorNewTitle,
- indicator = tInd.setTokens({'indicator': ind, 'indicatorTitle': title});
- size = self._getSize(size);
- params = {type: cat, caption: caption, size: size, width: width, progress: '', indicator: indicator};
- if (self.isAjaxUpload) {
- params.progress = self._renderThumbProgress();
- params.actions = self._renderFileActions(params, upl, false, rem, zoom, drg, false, false, false);
- } else {
- params.actions = self._renderFileActions(params, false, false, false, zoom, drg, false, false, false);
- }
- out = template.setTokens(params);
- out = $h.replaceTags(out, self.previewThumbTags);
- return out;
- },
- _renderFileActions: function (
- cfg,
- showUpl,
- showDwn,
- showDel,
- showZoom,
- showDrag,
- disabled,
- url,
- key,
- isInit,
- dUrl,
- dFile
- ) {
- var self = this;
- if (!cfg.type && isInit) {
- cfg.type = 'image';
- }
- if (self.enableResumableUpload) {
- showUpl = false;
- } else {
- if (typeof showUpl === 'function') {
- showUpl = showUpl(cfg);
- }
- }
- if (typeof showDwn === 'function') {
- showDwn = showDwn(cfg);
- }
- if (typeof showDel === 'function') {
- showDel = showDel(cfg);
- }
- if (typeof showZoom === 'function') {
- showZoom = showZoom(cfg);
- }
- if (typeof showDrag === 'function') {
- showDrag = showDrag(cfg);
- }
- if (!showUpl && !showDwn && !showDel && !showZoom && !showDrag) {
- return '';
- }
- var vUrl = url === false ? '' : ' data-url="' + url + '"', btnZoom = '', btnDrag = '', css,
- vKey = key === false ? '' : ' data-key="' + key + '"', btnDelete = '', btnUpload = '', btnDownload = '',
- template = self._getLayoutTemplate('actions'), config = self.fileActionSettings,
- otherButtons = self.otherActionButtons.setTokens({'dataKey': vKey, 'key': key}),
- removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
- if (showDel) {
- btnDelete = self._getLayoutTemplate('actionDelete').setTokens({
- 'removeClass': removeClass,
- 'removeIcon': config.removeIcon,
- 'removeTitle': config.removeTitle,
- 'dataUrl': vUrl,
- 'dataKey': vKey,
- 'key': key
- });
- }
- if (showUpl) {
- btnUpload = self._getLayoutTemplate('actionUpload').setTokens({
- 'uploadClass': config.uploadClass,
- 'uploadIcon': config.uploadIcon,
- 'uploadTitle': config.uploadTitle
- });
- }
- if (showDwn) {
- btnDownload = self._getLayoutTemplate('actionDownload').setTokens({
- 'downloadClass': config.downloadClass,
- 'downloadIcon': config.downloadIcon,
- 'downloadTitle': config.downloadTitle,
- 'downloadUrl': dUrl || self.initialPreviewDownloadUrl
- });
- btnDownload = btnDownload.setTokens({'filename': dFile, 'key': key});
- }
- if (showZoom) {
- btnZoom = self._getLayoutTemplate('actionZoom').setTokens({
- 'zoomClass': config.zoomClass,
- 'zoomIcon': config.zoomIcon,
- 'zoomTitle': config.zoomTitle
- });
- }
- if (showDrag && isInit) {
- css = 'drag-handle-init ' + config.dragClass;
- btnDrag = self._getLayoutTemplate('actionDrag').setTokens({
- 'dragClass': css,
- 'dragTitle': config.dragTitle,
- 'dragIcon': config.dragIcon
- });
- }
- return template.setTokens({
- 'delete': btnDelete,
- 'upload': btnUpload,
- 'download': btnDownload,
- 'zoom': btnZoom,
- 'drag': btnDrag,
- 'other': otherButtons
- });
- },
- _browse: function (e) {
- var self = this;
- if (e && e.isDefaultPrevented() || !self._raise('filebrowse')) {
- return;
- }
- if (self.isError && !self.isAjaxUpload) {
- self.clear();
- }
- self.$captionContainer.focus();
- },
- _change: function (e) {
- var self = this;
- if (self.changeTriggered) {
- return;
- }
- var $el = self.$element, isDragDrop = arguments.length > 1, isAjaxUpload = self.isAjaxUpload,
- tfiles, files = isDragDrop ? arguments[1] : $el.get(0).files, total,
- maxCount = !isAjaxUpload && $h.isEmpty($el.attr('multiple')) ? 1 : self.maxFileCount,
- len, ctr = self.fileManager.count(), isSingleUpload = $h.isEmpty($el.attr('multiple')),
- flagSingle = (isSingleUpload && ctr > 0),
- throwError = function (mesg, file, previewId, index) {
- var p1 = $.extend(true, {}, self._getOutData(null, {}, {}, files), {id: previewId, index: index}),
- p2 = {id: previewId, index: index, file: file, files: files};
- return isAjaxUpload ? self._showFileError(mesg, p1) : self._showError(mesg, p2);
- },
- maxCountCheck = function (n, m) {
- var msg = self.msgFilesTooMany.replace('{m}', m).replace('{n}', n);
- self.isError = throwError(msg, null, null, null);
- self.$captionContainer.removeClass('icon-visible');
- self._setCaption('', true);
- self.$container.removeClass('file-input-new file-input-ajax-new');
- };
- self.reader = null;
- self._resetUpload();
- self._hideFileIcon();
- if (self.dropZoneEnabled) {
- self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
- }
- if (!isAjaxUpload) {
- if (e.target && e.target.files === undefined) {
- files = e.target.value ? [{name: e.target.value.replace(/^.+\\/, '')}] : [];
- } else {
- files = e.target.files || {};
- }
- }
- tfiles = files;
- if ($h.isEmpty(tfiles) || tfiles.length === 0) {
- if (!isAjaxUpload) {
- self.clear();
- }
- self._raise('fileselectnone');
- return;
- }
- self._resetErrors();
- len = tfiles.length;
- total = self._getFileCount(isAjaxUpload ? (self.fileManager.count() + len) : len);
- if (maxCount > 0 && total > maxCount) {
- if (!self.autoReplace || len > maxCount) {
- maxCountCheck((self.autoReplace && len > maxCount ? len : total), maxCount);
- return;
- }
- if (total > maxCount) {
- self._resetPreviewThumbs(isAjaxUpload);
- }
- } else {
- if (!isAjaxUpload || flagSingle) {
- self._resetPreviewThumbs(false);
- if (flagSingle) {
- self.clearFileStack();
- }
- } else {
- if (isAjaxUpload && ctr === 0 && (!self.previewCache.count(true) || self.overwriteInitial)) {
- self._resetPreviewThumbs(true);
- }
- }
- }
- self.readFiles(tfiles);
- },
- _abort: function (params) {
- var self = this, data;
- if (self.ajaxAborted && typeof self.ajaxAborted === 'object' && self.ajaxAborted.message !== undefined) {
- data = $.extend(true, {}, self._getOutData(null), params);
- data.abortData = self.ajaxAborted.data || {};
- data.abortMessage = self.ajaxAborted.message;
- self._setProgress(101, self.$progress, self.msgCancelled);
- self._showFileError(self.ajaxAborted.message, data, 'filecustomerror');
- self.cancel();
- return true;
- }
- return !!self.ajaxAborted;
- },
- _resetFileStack: function () {
- var self = this, i = 0;
- self._getThumbs().each(function () {
- var $thumb = $(this), ind = $thumb.attr('data-fileindex'), pid = $thumb.attr('id');
- if (ind === '-1' || ind === -1) {
- return;
- }
- if (!self.fileManager.getFile($thumb.attr('data-fileid'))) {
- $thumb.attr({'id': self.previewInitId + '-' + i, 'data-fileindex': i});
- i++;
- } else {
- $thumb.attr({'id': 'uploaded-' + $h.uniqId(), 'data-fileindex': '-1'});
- }
- self.$preview.find('#zoom-' + pid).attr({
- 'id': 'zoom-' + $thumb.attr('id'),
- 'data-fileindex': $thumb.attr('data-fileindex')
- });
- });
- },
- _isFileSelectionValid: function (cnt) {
- var self = this;
- cnt = cnt || 0;
- if (self.required && !self.getFilesCount()) {
- self.$errorContainer.html('');
- self._showFileError(self.msgFileRequired);
- return false;
- }
- if (self.minFileCount > 0 && self._getFileCount(cnt) < self.minFileCount) {
- self._noFilesError({});
- return false;
- }
- return true;
- },
- clearFileStack: function () {
- var self = this;
- self.fileManager.clear();
- self._initResumableUpload();
- if (self.enableResumableUpload) {
- if (self.showPause === null) {
- self.showPause = true;
- }
- if (self.showCancel === null) {
- self.showCancel = false;
- }
- } else {
- self.showPause = false;
- if (self.showCancel === null) {
- self.showCancel = true;
- }
- }
- return self.$element;
- },
- getFileStack: function () {
- return this.fileManager.stack;
- },
- getFileList: function () {
- return this.fileManager.list();
- },
- getFilesCount: function () {
- var self = this, len = self.isAjaxUpload ? self.fileManager.count() : self._inputFileCount();
- return self._getFileCount(len);
- },
- readFiles: function (files) {
- this.reader = new FileReader();
- var self = this, $el = self.$element, reader = self.reader,
- $container = self.$previewContainer, $status = self.$previewStatus, msgLoading = self.msgLoading,
- msgProgress = self.msgProgress, previewInitId = self.previewInitId, numFiles = files.length,
- settings = self.fileTypeSettings, ctr = self.fileManager.count(), readFile,
- fileTypes = self.allowedFileTypes, typLen = fileTypes ? fileTypes.length : 0,
- fileExt = self.allowedFileExtensions, strExt = $h.isEmpty(fileExt) ? '' : fileExt.join(', '),
- throwError = function (msg, file, previewId, index, fileId) {
- var p1 = $.extend(true, {}, self._getOutData(null, {}, {}, files),
- {id: previewId, index: index, fileId: fileId}), $thumb = $('#' + previewId),
- p2 = {id: previewId, index: index, fileId: fileId, file: file, files: files};
- self._previewDefault(file, previewId, true);
- if (self.isAjaxUpload) {
- setTimeout(function () {
- readFile(index + 1);
- }, self.processDelay);
- } else {
- numFiles = 0;
- }
- self._initFileActions();
- $thumb.remove();
- self.isError = self.isAjaxUpload ? self._showFileError(msg, p1) : self._showError(msg, p2);
- self._updateFileDetails(numFiles);
- };
- self.fileManager.clearImages();
- $.each(files, function (key, file) {
- var func = self.fileTypeSettings.image;
- if (func && func(file.type)) {
- self.fileManager.totalImages++;
- }
- });
- readFile = function (i) {
- if ($h.isEmpty($el.attr('multiple'))) {
- numFiles = 1;
- }
- if (i >= numFiles) {
- if (self.isAjaxUpload && self.fileManager.count() > 0) {
- self._raise('filebatchselected', [self.fileManager.stack]);
- } else {
- self._raise('filebatchselected', [files]);
- }
- $container.removeClass('file-thumb-loading');
- $status.html('');
- return;
- }
- var node = ctr + i, previewId = previewInitId + '-' + node, file = files[i], fSizeKB, j, msg, $thumb,
- fnText = settings.text, fnImage = settings.image, fnHtml = settings.html, typ, chk, typ1, typ2,
- caption = self._getFileName(file, ''), fileSize = (file && file.size || 0) / 1000,
- fileExtExpr = '', previewData = $h.createObjectURL(file), fileCount = 0,
- strTypes = '', fileId,
- func, knownTypes = 0, isText, isHtml, isImage, txtFlag, processFileLoaded = function () {
- var msg = msgProgress.setTokens({
- 'index': i + 1,
- 'files': numFiles,
- 'percent': 50,
- 'name': caption
- });
- setTimeout(function () {
- $status.html(msg);
- self._updateFileDetails(numFiles);
- readFile(i + 1);
- }, self.processDelay);
- self._raise('fileloaded', [file, previewId, i, reader]);
- };
- if (!file) {
- return;
- }
- fileId = self.fileManager.getId(file);
- if (typLen > 0) {
- for (j = 0; j < typLen; j++) {
- typ1 = fileTypes[j];
- typ2 = self.msgFileTypes[typ1] || typ1;
- strTypes += j === 0 ? typ2 : ', ' + typ2;
- }
- }
- if (caption === false) {
- readFile(i + 1);
- return;
- }
- if (caption.length === 0) {
- msg = self.msgInvalidFileName.replace('{name}', $h.htmlEncode($h.getFileName(file), '[unknown]'));
- throwError(msg, file, previewId, i, fileId);
- return;
- }
- if (!$h.isEmpty(fileExt)) {
- fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
- }
- fSizeKB = fileSize.toFixed(2);
- if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
- msg = self.msgSizeTooLarge.setTokens({
- 'name': caption,
- 'size': fSizeKB,
- 'maxSize': self.maxFileSize
- });
- throwError(msg, file, previewId, i, fileId);
- return;
- }
- if (self.minFileSize !== null && fileSize <= $h.getNum(self.minFileSize)) {
- msg = self.msgSizeTooSmall.setTokens({
- 'name': caption,
- 'size': fSizeKB,
- 'minSize': self.minFileSize
- });
- throwError(msg, file, previewId, i, fileId);
- return;
- }
- if (!$h.isEmpty(fileTypes) && $h.isArray(fileTypes)) {
- for (j = 0; j < fileTypes.length; j += 1) {
- typ = fileTypes[j];
- func = settings[typ];
- fileCount += !func || (typeof func !== 'function') ? 0 : (func(file.type,
- $h.getFileName(file)) ? 1 : 0);
- }
- if (fileCount === 0) {
- msg = self.msgInvalidFileType.setTokens({name: caption, types: strTypes});
- throwError(msg, file, previewId, i, fileId);
- return;
- }
- }
- if (fileCount === 0 && !$h.isEmpty(fileExt) && $h.isArray(fileExt) && !$h.isEmpty(fileExtExpr)) {
- chk = $h.compare(caption, fileExtExpr);
- fileCount += $h.isEmpty(chk) ? 0 : chk.length;
- if (fileCount === 0) {
- msg = self.msgInvalidFileExtension.setTokens({name: caption, extensions: strExt});
- throwError(msg, file, previewId, i, fileId);
- return;
- }
- }
- if (self.isAjaxUpload && self.fileManager.exists(fileId)) {
- msg = self.msgDuplicateFile.setTokens({name: caption, size: fSizeKB});
- throwError(msg, file, previewId, i, fileId);
- $thumb = $('#' + previewId);
- if ($thumb && $thumb.length) {
- $thumb.remove();
- }
- return;
- }
- if (!self.canPreview(file)) {
- if (self.isAjaxUpload) {
- self.fileManager.add(file);
- }
- if (self.showPreview) {
- $container.addClass('file-thumb-loading');
- self._previewDefault(file, previewId);
- self._initFileActions();
- }
- setTimeout(function () {
- self._updateFileDetails(numFiles);
- readFile(i + 1);
- self._raise('fileloaded', [file, previewId, i]);
- }, 10);
- return;
- }
- isText = fnText(file.type, caption);
- isHtml = fnHtml(file.type, caption);
- isImage = fnImage(file.type, caption);
- $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
- $container.addClass('file-thumb-loading');
- reader.onerror = function (evt) {
- self._errorHandler(evt, caption);
- };
- reader.onload = function (theFile) {
- var hex, fileInfo, uint, byte, bytes = [], contents, mime, readTextImage = function (textFlag) {
- var newReader = new FileReader();
- newReader.onerror = function (theFileNew) {
- self._errorHandler(theFileNew, caption);
- };
- newReader.onload = function (theFileNew) {
- self._previewFile(i, file, theFileNew, previewId, previewData, fileInfo);
- self._initFileActions();
- processFileLoaded();
- };
- if (textFlag) {
- newReader.readAsText(file, self.textEncoding);
- } else {
- newReader.readAsDataURL(file);
- }
- };
- fileInfo = {'name': caption, 'type': file.type};
- $.each(settings, function (k, f) {
- if (k !== 'object' && k !== 'other' && typeof f === 'function' && f(file.type, caption)) {
- knownTypes++;
- }
- });
- if (knownTypes === 0) {// auto detect mime types from content if no known file types detected
- uint = new Uint8Array(theFile.target.result);
- for (j = 0; j < uint.length; j++) {
- byte = uint[j].toString(16);
- bytes.push(byte);
- }
- hex = bytes.join('').toLowerCase().substring(0, 8);
- mime = $h.getMimeType(hex, '', '');
- if ($h.isEmpty(mime)) { // look for ascii text content
- contents = $h.arrayBuffer2String(reader.result);
- mime = $h.isSvg(contents) ? 'image/svg+xml' : $h.getMimeType(hex, contents, file.type);
- }
- fileInfo = {'name': caption, 'type': mime};
- isText = fnText(mime, '');
- isHtml = fnHtml(mime, '');
- isImage = fnImage(mime, '');
- txtFlag = isText || isHtml;
- if (txtFlag || isImage) {
- readTextImage(txtFlag);
- return;
- }
- }
- self._previewFile(i, file, theFile, previewId, previewData, fileInfo);
- self._initFileActions();
- processFileLoaded();
- };
- reader.onprogress = function (data) {
- if (data.lengthComputable) {
- var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
- msg = msgProgress.setTokens({
- 'index': i + 1,
- 'files': numFiles,
- 'percent': progress,
- 'name': caption
- });
- setTimeout(function () {
- $status.html(msg);
- }, self.processDelay);
- }
- };
- if (isText || isHtml) {
- reader.readAsText(file, self.textEncoding);
- } else {
- if (isImage) {
- reader.readAsDataURL(file);
- } else {
- reader.readAsArrayBuffer(file);
- }
- }
- self.fileManager.add(file);
- };
- readFile(0);
- self._updateFileDetails(numFiles, false);
- },
- lock: function () {
- var self = this, $container = self.$container;
- self._resetErrors();
- self.disable();
- $container.addClass('is-locked');
- if (self.showCancel) {
- $container.find('.fileinput-cancel').show();
- }
- if (self.showPause) {
- $container.find('.fileinput-pause').show();
- }
- self._raise('filelock', [self.fileManager.stack, self._getExtraData()]);
- return self.$element;
- },
- unlock: function (reset) {
- var self = this, $container = self.$container;
- if (reset === undefined) {
- reset = true;
- }
- self.enable();
- $container.removeClass('is-locked');
- if (self.showCancel) {
- $container.find('.fileinput-cancel').hide();
- }
- if (self.showPause) {
- $container.find('.fileinput-pause').hide();
- }
- if (reset) {
- self._resetFileStack();
- }
- self._raise('fileunlock', [self.fileManager.stack, self._getExtraData()]);
- return self.$element;
- },
- resume: function () {
- var self = this, flag = false, $pr = self.$progress, rm = self.resumableManager;
- if (!self.enableResumableUpload) {
- return self.$element;
- }
- if (self.paused) {
- $pr.html(self.progressPauseTemplate.setTokens({
- percent: 101,
- status: self.msgUploadResume,
- stats: ''
- }));
- } else {
- flag = true;
- }
- self.paused = false;
- if (flag) {
- $pr.html(self.progressInfoTemplate.setTokens({
- percent: 101,
- status: self.msgUploadBegin,
- stats: ''
- }));
- }
- setTimeout(function () {
- rm.upload();
- }, self.processDelay);
- return self.$element;
- },
- pause: function () {
- var self = this, rm = self.resumableManager, xhr = self.ajaxRequests, len = xhr.length, i,
- pct = rm.getProgress(), actions = self.fileActionSettings;
- if (!self.enableResumableUpload) {
- return self.$element;
- }
- if (rm.chunkIntervalId) {
- clearInterval(rm.chunkIntervalId);
- }
- if (self.ajaxQueueIntervalId) {
- clearInterval(self.ajaxQueueIntervalId);
- }
- self._raise('fileuploadpaused', [self.fileManager, rm]);
- if (len > 0) {
- for (i = 0; i < len; i += 1) {
- self.paused = true;
- xhr[i].abort();
- }
- }
- if (self.showPreview) {
- self._getThumbs().each(function () {
- var $thumb = $(this), fileId = $thumb.attr('data-fileid'), t = self._getLayoutTemplate('stats'),
- stats, $indicator = $thumb.find('.file-upload-indicator');
- $thumb.removeClass('file-uploading');
- if ($indicator.attr('title') === actions.indicatorLoadingTitle) {
- self._setThumbStatus($thumb, 'Paused');
- stats = t.setTokens({pendingTime: self.msgPaused, uploadSpeed: ''});
- self.paused = true;
- self._setProgress(pct, $thumb.find('.file-thumb-progress'), pct + '%', stats);
- }
- if (!self.fileManager.getFile(fileId)) {
- $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
- }
- });
- }
- self._setProgress(101, self.$progress, self.msgPaused);
- return self.$element;
- },
- cancel: function () {
- var self = this, xhr = self.ajaxRequests, rm = self.resumableManager, len = xhr.length, i;
- if (self.enableResumableUpload && rm.chunkIntervalId) {
- clearInterval(rm.chunkIntervalId);
- rm.reset();
- self._raise('fileuploadcancelled', [self.fileManager, rm]);
- } else {
- self._raise('fileuploadcancelled', [self.fileManager]);
- }
- if (self.ajaxQueueIntervalId) {
- clearInterval(self.ajaxQueueIntervalId);
- }
- self._initAjax();
- if (len > 0) {
- for (i = 0; i < len; i += 1) {
- self.cancelling = true;
- xhr[i].abort();
- }
- }
- self._getThumbs().each(function () {
- var $thumb = $(this), fileId = $thumb.attr('data-fileid'), $prog = $thumb.find('.file-thumb-progress');
- $thumb.removeClass('file-uploading');
- self._setProgress(0, $prog);
- $prog.hide();
- if (!self.fileManager.getFile(fileId)) {
- $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
- $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
- }
- self.unlock();
- });
- setTimeout(function () {
- self._setProgressCancelled();
- }, self.processDelay);
- return self.$element;
- },
- clear: function () {
- var self = this, cap;
- if (!self._raise('fileclear')) {
- return;
- }
- self.$btnUpload.removeAttr('disabled');
- self._getThumbs().find('video,audio,img').each(function () {
- $h.cleanMemory($(this));
- });
- self._clearFileInput();
- self._resetUpload();
- self.clearFileStack();
- self._resetErrors(true);
- if (self._hasInitialPreview()) {
- self._showFileIcon();
- self._resetPreview();
- self._initPreviewActions();
- self.$container.removeClass('file-input-new');
- } else {
- self._getThumbs().each(function () {
- self._clearObjects($(this));
- });
- if (self.isAjaxUpload) {
- self.previewCache.data = {};
- }
- self.$preview.html('');
- cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
- self.$caption.attr('title', '').val(cap);
- $h.addCss(self.$container, 'file-input-new');
- self._validateDefaultPreview();
- }
- if (self.$container.find($h.FRAMES).length === 0) {
- if (!self._initCaption()) {
- self.$captionContainer.removeClass('icon-visible');
- }
- }
- self._hideFileIcon();
- self.$captionContainer.focus();
- self._setFileDropZoneTitle();
- self._raise('filecleared');
- return self.$element;
- },
- reset: function () {
- var self = this;
- if (!self._raise('filereset')) {
- return;
- }
- self.lastProgress = 0;
- self._resetPreview();
- self.$container.find('.fileinput-filename').text('');
- $h.addCss(self.$container, 'file-input-new');
- if (self.getFrames().length || self.dropZoneEnabled) {
- self.$container.removeClass('file-input-new');
- }
- self.clearFileStack();
- self._setFileDropZoneTitle();
- return self.$element;
- },
- disable: function () {
- var self = this;
- self.isDisabled = true;
- self._raise('filedisabled');
- self.$element.attr('disabled', 'disabled');
- self.$container.find('.kv-fileinput-caption').addClass('file-caption-disabled');
- self.$container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button')
- .attr('disabled', true);
- $h.addCss(self.$container.find('.btn-file'), 'disabled');
- self._initDragDrop();
- return self.$element;
- },
- enable: function () {
- var self = this;
- self.isDisabled = false;
- self._raise('fileenabled');
- self.$element.removeAttr('disabled');
- self.$container.find('.kv-fileinput-caption').removeClass('file-caption-disabled');
- self.$container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button')
- .removeAttr('disabled');
- self.$container.find('.btn-file').removeClass('disabled');
- self._initDragDrop();
- return self.$element;
- },
- upload: function () {
- var self = this, fm = self.fileManager, totLen = fm.count(), i, outData, len,
- hasExtraData = !$.isEmptyObject(self._getExtraData());
- if (!self.isAjaxUpload || self.isDisabled || !self._isFileSelectionValid(totLen)) {
- return;
- }
- self.lastProgress = 0;
- self._resetUpload();
- if (totLen === 0 && !hasExtraData) {
- self._showFileError(self.msgUploadEmpty);
- return;
- }
- self.cancelling = false;
- self.$progress.show();
- self.lock();
- len = fm.count();
- if (totLen === 0 && hasExtraData) {
- self._setProgress(2);
- self._uploadExtraOnly();
- return;
- }
- if (self.enableResumableUpload) {
- return self.resume();
- }
- if (self.uploadAsync || self.enableResumableUpload) {
- outData = self._getOutData(null);
- self._raise('filebatchpreupload', [outData]);
- self.fileBatchCompleted = false;
- self.uploadCache = {content: [], config: [], tags: [], append: true};
- for (i = 0; i < len; i++) {
- self.uploadCache.content[i] = null;
- self.uploadCache.config[i] = null;
- self.uploadCache.tags[i] = null;
- }
- self.$preview.find('.file-preview-initial').removeClass($h.SORT_CSS);
- self._initSortable();
- self.cacheInitialPreview = self.getPreview();
- }
- self._setProgress(2);
- self.hasInitData = false;
- if (self.uploadAsync) {
- i = 0;
- $.each(fm.stack, function (id) {
- self._uploadSingle(i, id, true);
- i++;
- });
- return;
- }
- self._uploadBatch();
- return self.$element;
- },
- destroy: function () {
- var self = this, $form = self.$form, $cont = self.$container, $el = self.$element, ns = self.namespace;
- $(document).off(ns);
- $(window).off(ns);
- if ($form && $form.length) {
- $form.off(ns);
- }
- if (self.isAjaxUpload) {
- self._clearFileInput();
- }
- self._cleanup();
- self._initPreviewCache();
- $el.insertBefore($cont).off(ns).removeData();
- $cont.off().remove();
- return $el;
- },
- refresh: function (options) {
- var self = this, $el = self.$element;
- if (typeof options !== 'object' || $h.isEmpty(options)) {
- options = self.options;
- } else {
- options = $.extend(true, {}, self.options, options);
- }
- self._init(options, true);
- self._listen();
- return $el;
- },
- zoom: function (frameId) {
- var self = this, $frame = self._getFrame(frameId), $modal = self.$modal;
- if (!$frame) {
- return;
- }
- $h.initModal($modal);
- $modal.html(self._getModalContent());
- self._setZoomContent($frame);
- $modal.modal('show');
- self._initZoomButtons();
- },
- getExif: function (frameId) {
- var self = this, $frame = self._getFrame(frameId);
- return $frame && $frame.data('exif') || null;
- },
- getFrames: function (cssFilter) {
- var self = this, $frames;
- cssFilter = cssFilter || '';
- $frames = self.$preview.find($h.FRAMES + cssFilter);
- if (self.reversePreviewOrder) {
- $frames = $($frames.get().reverse());
- }
- return $frames;
- },
- getPreview: function () {
- var self = this;
- return {
- content: self.initialPreview,
- config: self.initialPreviewConfig,
- tags: self.initialPreviewThumbTags
- };
- }
- };
- $.fn.fileinput = function (option) {
- if (!$h.hasFileAPISupport() && !$h.isIE(9)) {
- return;
- }
- var args = Array.apply(null, arguments), retvals = [];
- args.shift();
- this.each(function () {
- var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option,
- theme = options.theme || self.data('theme'), l = {}, t = {},
- lang = options.language || self.data('language') || $.fn.fileinput.defaults.language || 'en', opt;
- if (!data) {
- if (theme) {
- t = $.fn.fileinputThemes[theme] || {};
- }
- if (lang !== 'en' && !$h.isEmpty($.fn.fileinputLocales[lang])) {
- l = $.fn.fileinputLocales[lang] || {};
- }
- opt = $.extend(true, {}, $.fn.fileinput.defaults, t, $.fn.fileinputLocales.zh, l, options, self.data());
- data = new FileInput(this, opt);
- self.data('fileinput', data);
- }
- if (typeof option === 'string') {
- retvals.push(data[option].apply(data, args));
- }
- });
- switch (retvals.length) {
- case 0:
- return this;
- case 1:
- return retvals[0];
- default:
- return retvals;
- }
- };
- //noinspection HtmlUnknownAttribute
- $.fn.fileinput.defaults = {
- language: 'en',
- showCaption: true,
- showBrowse: true,
- showPreview: true,
- showRemove: true,
- showUpload: true,
- showUploadStats: true,
- showCancel: null,
- showPause: null,
- showClose: true,
- showUploadedThumbs: true,
- browseOnZoneClick: false,
- autoReplace: false,
- autoOrientImage: function () { // applicable for JPEG images only and non ios safari
- var ua = window.navigator.userAgent, webkit = !!ua.match(/WebKit/i),
- iOS = !!ua.match(/iP(od|ad|hone)/i), iOSSafari = iOS && webkit && !ua.match(/CriOS/i);
- return !iOSSafari;
- },
- autoOrientImageInitial: true,
- required: false,
- rtl: false,
- hideThumbnailContent: false,
- encodeUrl: true,
- generateFileId: null,
- previewClass: '',
- captionClass: '',
- frameClass: 'krajee-default',
- mainClass: 'file-caption-main',
- mainTemplate: null,
- purifyHtml: true,
- fileSizeGetter: null,
- initialCaption: '',
- initialPreview: [],
- initialPreviewDelimiter: '*$$*',
- initialPreviewAsData: false,
- initialPreviewFileType: 'image',
- initialPreviewConfig: [],
- initialPreviewThumbTags: [],
- previewThumbTags: {},
- initialPreviewShowDelete: true,
- initialPreviewDownloadUrl: '',
- removeFromPreviewOnError: false,
- deleteUrl: '',
- deleteExtraData: {},
- overwriteInitial: true,
- sanitizeZoomCache: function (content) {
- var $container = $(document.createElement('div')).append(content);
- $container.find('input,select,.file-thumbnail-footer').remove();
- return $container.html();
- },
- previewZoomButtonIcons: {
- prev: '<i class="glyphicon glyphicon-triangle-left"></i>',
- next: '<i class="glyphicon glyphicon-triangle-right"></i>',
- toggleheader: '<i class="glyphicon glyphicon-resize-vertical"></i>',
- fullscreen: '<i class="glyphicon glyphicon-fullscreen"></i>',
- borderless: '<i class="glyphicon glyphicon-resize-full"></i>',
- close: '<i class="glyphicon glyphicon-remove"></i>'
- },
- previewZoomButtonClasses: {
- prev: 'btn btn-navigate',
- next: 'btn btn-navigate',
- toggleheader: 'btn btn-sm btn-kv btn-default btn-outline-secondary',
- fullscreen: 'btn btn-sm btn-kv btn-default btn-outline-secondary',
- borderless: 'btn btn-sm btn-kv btn-default btn-outline-secondary',
- close: 'btn btn-sm btn-kv btn-default btn-outline-secondary'
- },
- previewTemplates: {},
- previewContentTemplates: {},
- preferIconicPreview: false,
- preferIconicZoomPreview: false,
- allowedFileTypes: null,
- allowedFileExtensions: null,
- allowedPreviewTypes: undefined,
- allowedPreviewMimeTypes: null,
- allowedPreviewExtensions: null,
- disabledPreviewTypes: undefined,
- disabledPreviewExtensions: ['msi', 'exe', 'com', 'zip', 'rar', 'app', 'vb', 'scr'],
- disabledPreviewMimeTypes: null,
- defaultPreviewContent: null,
- customLayoutTags: {},
- customPreviewTags: {},
- previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
- previewFileIconClass: 'file-other-icon',
- previewFileIconSettings: {},
- previewFileExtSettings: {},
- buttonLabelClass: 'hidden-xs',
- browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> ',
- browseClass: 'btn btn-primary',
- removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
- removeClass: 'btn btn-default btn-secondary',
- cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i>',
- cancelClass: 'btn btn-default btn-secondary',
- pauseIcon: '<i class="glyphicon glyphicon-pause"></i>',
- pauseClass: 'btn btn-default btn-secondary',
- uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
- uploadClass: 'btn btn-default btn-secondary',
- uploadUrl: null,
- uploadUrlThumb: null,
- uploadAsync: true,
- uploadParamNames: {
- chunkCount: 'chunkCount',
- chunkIndex: 'chunkIndex',
- chunkSize: 'chunkSize',
- chunkSizeStart: 'chunkSizeStart',
- chunksUploaded: 'chunksUploaded',
- fileBlob: 'fileBlob',
- fileId: 'fileId',
- fileName: 'fileName',
- fileRelativePath: 'fileRelativePath',
- fileSize: 'fileSize',
- retryCount: 'retryCount'
- },
- maxAjaxThreads: 5,
- processDelay: 100,
- queueDelay: 10, // must be lesser than process delay
- progressDelay: 0, // must be lesser than process delay
- enableResumableUpload: false,
- resumableUploadOptions: {
- fallback: null,
- testUrl: null, // used for checking status of chunks/ files previously / partially uploaded
- chunkSize: 2 * 1024, // in KB
- maxThreads: 4,
- maxRetries: 3,
- showErrorLog: true
- },
- uploadExtraData: {},
- zoomModalHeight: 480,
- minImageWidth: null,
- minImageHeight: null,
- maxImageWidth: null,
- maxImageHeight: null,
- resizeImage: false,
- resizePreference: 'width',
- resizeQuality: 0.92,
- resizeDefaultImageType: 'image/jpeg',
- resizeIfSizeMoreThan: 0, // in KB
- minFileSize: 0,
- maxFileSize: 0,
- maxFilePreviewSize: 25600, // 25 MB
- minFileCount: 0,
- maxFileCount: 0,
- validateInitialCount: false,
- msgValidationErrorClass: 'text-danger',
- msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
- msgErrorClass: 'file-error-message',
- progressThumbClass: 'progress-bar progress-bar-striped active',
- progressClass: 'progress-bar bg-success progress-bar-success progress-bar-striped active',
- progressInfoClass: 'progress-bar bg-info progress-bar-info progress-bar-striped active',
- progressCompleteClass: 'progress-bar bg-success progress-bar-success',
- progressPauseClass: 'progress-bar bg-primary progress-bar-primary progress-bar-striped active',
- progressErrorClass: 'progress-bar bg-danger progress-bar-danger',
- progressUploadThreshold: 99,
- previewFileType: 'image',
- elCaptionContainer: null,
- elCaptionText: null,
- elPreviewContainer: null,
- elPreviewImage: null,
- elPreviewStatus: null,
- elErrorContainer: null,
- errorCloseButton: $h.closeButton('kv-error-close'),
- slugCallback: null,
- dropZoneEnabled: true,
- dropZoneTitleClass: 'file-drop-zone-title',
- fileActionSettings: {},
- otherActionButtons: '',
- textEncoding: 'UTF-8',
- ajaxSettings: {},
- ajaxDeleteSettings: {},
- showAjaxErrorDetails: true,
- mergeAjaxCallbacks: false,
- mergeAjaxDeleteCallbacks: false,
- retryErrorUploads: true,
- reversePreviewOrder: false,
- usePdfRenderer: function () {
- //noinspection JSUnresolvedVariable
- var isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
- return !!navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/i) || isIE11;
- },
- pdfRendererUrl: '',
- pdfRendererTemplate: '<iframe class="kv-preview-data file-preview-pdf" src="{renderer}?file={data}" {style}></iframe>'
- };
- // noinspection HtmlUnknownAttribute
- $.fn.fileinputLocales.en = {
- fileSingle: 'file',
- filePlural: 'files',
- browseLabel: 'Browse …',
- removeLabel: 'Remove',
- removeTitle: 'Clear all unprocessed files',
- cancelLabel: 'Cancel',
- cancelTitle: 'Abort ongoing upload',
- pauseLabel: 'Pause',
- pauseTitle: 'Pause ongoing upload',
- uploadLabel: 'Upload',
- uploadTitle: 'Upload selected files',
- msgNo: 'No',
- msgNoFilesSelected: 'No files selected',
- msgCancelled: 'Cancelled',
- msgPaused: 'Paused',
- msgPlaceholder: 'Select {files}...',
- msgZoomModalHeading: 'Detailed Preview',
- msgFileRequired: 'You must select a file to upload.',
- msgSizeTooSmall: 'File "{name}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.',
- msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
- msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
- msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
- msgFileNotFound: 'File "{name}" not found!',
- msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
- msgFileNotReadable: 'File "{name}" is not readable.',
- msgFilePreviewAborted: 'File preview aborted for "{name}".',
- msgFilePreviewError: 'An error occurred while reading the file "{name}".',
- msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".',
- msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
- msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
- msgFileTypes: {
- 'image': 'image',
- 'html': 'HTML',
- 'text': 'text',
- 'video': 'video',
- 'audio': 'audio',
- 'flash': 'flash',
- 'pdf': 'PDF',
- 'object': 'object'
- },
- msgUploadAborted: 'The file upload was aborted',
- msgUploadThreshold: 'Processing...',
- msgUploadBegin: 'Initializing...',
- msgUploadEnd: 'Done',
- msgUploadResume: 'Resuming upload...',
- msgUploadEmpty: 'No valid data available for upload.',
- msgUploadError: 'Upload Error',
- msgDeleteError: 'Delete Error',
- msgProgressError: 'Error',
- msgValidationError: 'Validation Error',
- msgLoading: 'Loading file {index} of {files} …',
- msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
- msgSelected: '{n} {files} selected',
- msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
- msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
- msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
- msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
- msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
- msgImageResizeError: 'Could not get the image dimensions to resize.',
- msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>',
- msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!',
- msgAjaxProgressError: '{operation} failed',
- msgDuplicateFile: 'File "{name}" of same size "{size} KB" has already been selected earlier. Skipping duplicate selection.',
- msgResumableUploadRetriesExceeded: 'Upload aborted beyond <b>{max}</b> retries for file <b>{file}</b>! Error Details: <pre>{error}</pre>',
- msgPendingTime: '{time} remaining',
- msgCalculatingTime: 'calculating time remaining',
- ajaxOperations: {
- deleteThumb: 'file delete',
- uploadThumb: 'file upload',
- uploadBatch: 'batch file upload',
- uploadExtra: 'form data upload'
- },
- dropZoneTitle: 'Drag & drop files here …',
- dropZoneClickTitle: '<br>(or click to select {files})',
- previewZoomButtonTitles: {
- prev: 'View previous file',
- next: 'View next file',
- toggleheader: 'Toggle header',
- fullscreen: 'Toggle full screen',
- borderless: 'Toggle borderless mode',
- close: 'Close detailed preview'
- }
- };
-
- $.fn.fileinputLocales.zh = {
- fileSingle: '文件',
- filePlural: '个文件',
- browseLabel: '选择 …',
- removeLabel: '移除',
- removeTitle: '清除选中文件',
- cancelLabel: '取消',
- cancelTitle: '取消进行中的上传',
- pauseLabel: 'Pause',
- pauseTitle: 'Pause ongoing upload',
- uploadLabel: '上传',
- uploadTitle: '上传选中文件',
- msgNo: '没有',
- msgNoFilesSelected: '未选择文件',
- msgPaused: 'Paused',
- msgCancelled: '取消',
- msgPlaceholder: '选择 {files}...',
- msgZoomModalHeading: '详细预览',
- msgFileRequired: '必须选择一个文件上传.',
- msgSizeTooSmall: '文件 "{name}" (<b>{size} KB</b>) 必须大于限定大小 <b>{minSize} KB</b>.',
- msgSizeTooLarge: '文件 "{name}" (<b>{size} KB</b>) 超过了允许大小 <b>{maxSize} KB</b>.',
- msgFilesTooLess: '你必须选择最少 <b>{n}</b> {files} 来上传. ',
- msgFilesTooMany: '选择的上传文件个数 <b>({n})</b> 超出最大文件的限制个数 <b>{m}</b>.',
- msgFileNotFound: '文件 "{name}" 未找到!',
- msgFileSecured: '安全限制,为了防止读取文件 "{name}".',
- msgFileNotReadable: '文件 "{name}" 不可读.',
- msgFilePreviewAborted: '取消 "{name}" 的预览.',
- msgFilePreviewError: '读取 "{name}" 时出现了一个错误.',
- msgInvalidFileName: '文件名 "{name}" 包含非法字符.',
- msgInvalidFileType: '不正确的类型 "{name}". 只支持 "{types}" 类型的文件.',
- msgInvalidFileExtension: '不正确的文件扩展名 "{name}". 只支持 "{extensions}" 的文件扩展名.',
- msgFileTypes: {
- 'image': 'image',
- 'html': 'HTML',
- 'text': 'text',
- 'video': 'video',
- 'audio': 'audio',
- 'flash': 'flash',
- 'pdf': 'PDF',
- 'object': 'object'
- },
- msgUploadAborted: '该文件上传被中止',
- msgUploadThreshold: '处理中...',
- msgUploadBegin: '正在初始化...',
- msgUploadEnd: '完成',
- msgUploadResume: 'Resuming upload...',
- msgUploadEmpty: '无效的文件上传.',
- msgUploadError: 'Upload Error',
- msgDeleteError: 'Delete Error',
- msgProgressError: '上传出错',
- msgValidationError: '验证错误',
- msgLoading: '加载第 {index} 文件 共 {files} …',
- msgProgress: '加载第 {index} 文件 共 {files} - {name} - {percent}% 完成.',
- msgSelected: '{n} {files} 选中',
- msgFoldersNotAllowed: '只支持拖拽文件! 跳过 {n} 拖拽的文件夹.',
- msgImageWidthSmall: '图像文件的"{name}"的宽度必须是至少{size}像素.',
- msgImageHeightSmall: '图像文件的"{name}"的高度必须至少为{size}像素.',
- msgImageWidthLarge: '图像文件"{name}"的宽度不能超过{size}像素.',
- msgImageHeightLarge: '图像文件"{name}"的高度不能超过{size}像素.',
- msgImageResizeError: '无法获取的图像尺寸调整。',
- msgImageResizeException: '调整图像大小时发生错误。<pre>{errors}</pre>',
- msgAjaxError: '{operation} 发生错误. 请重试!',
- msgAjaxProgressError: '{operation} 失败',
- msgDuplicateFile: 'File "{name}" of same size "{size} KB" has already been selected earlier. Skipping duplicate selection.',
- msgResumableUploadRetriesExceeded: 'Upload aborted beyond <b>{max}</b> retries for file <b>{file}</b>! Error Details: <pre>{error}</pre>',
- msgPendingTime: '{time} remaining',
- msgCalculatingTime: 'calculating time remaining',
- ajaxOperations: {
- deleteThumb: '删除文件',
- uploadThumb: '上传文件',
- uploadBatch: '批量上传',
- uploadExtra: '表单数据上传'
- },
- dropZoneTitle: '拖拽文件到这里 …<br>支持多文件同时上传',
- dropZoneClickTitle: '<br>(或点击{files}按钮选择文件)',
- fileActionSettings: {
- removeTitle: '删除文件',
- uploadTitle: '上传文件',
- downloadTitle: '下载文件',
- uploadRetryTitle: '重试',
- zoomTitle: '查看详情',
- dragTitle: '移动 / 重置',
- indicatorNewTitle: '没有上传',
- indicatorSuccessTitle: '上传',
- indicatorErrorTitle: '上传错误',
- indicatorPausedTitle: 'Upload Paused',
- indicatorLoadingTitle: '上传 ...'
- },
- previewZoomButtonTitles: {
- prev: '预览上一个文件',
- next: '预览下一个文件',
- toggleheader: '缩放',
- fullscreen: '全屏',
- borderless: '无边界模式',
- close: '关闭当前预览'
- }
- };
- $.fn.fileinput.Constructor = FileInput;
- /**
- * Convert automatically file inputs with class 'file' into a bootstrap fileinput control.
- */
- $(document).ready(function () {
- var $input = $('input.file[type=file]');
- if ($input.length) {
- $input.fileinput();
- }
- });
- }));
|