fileinput.js 291 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404
  1. /*!
  2. * bootstrap-fileinput v5.2.4
  3. * http://plugins.krajee.com/file-input
  4. *
  5. * Author: Kartik Visweswaran
  6. * Copyright: 2014 - 2021, Kartik Visweswaran, Krajee.com
  7. *
  8. * Licensed under the BSD-3-Clause
  9. * https://github.com/kartik-v/bootstrap-fileinput/blob/master/LICENSE.md
  10. */
  11. (function (factory) {
  12. 'use strict';
  13. if (typeof define === 'function' && define.amd) {
  14. define(['jquery'], factory);
  15. } else {
  16. if (typeof module === 'object' && module.exports) {
  17. //noinspection NpmUsedModulesInstalled
  18. module.exports = factory(require('jquery'));
  19. } else {
  20. factory(window.jQuery);
  21. }
  22. }
  23. }(function ($) {
  24. 'use strict';
  25. $.fn.fileinputLocales = {};
  26. $.fn.fileinputThemes = {};
  27. if (!$.fn.fileinputBsVersion) {
  28. $.fn.fileinputBsVersion = (window.Alert && window.Alert.VERSION) ||
  29. (window.bootstrap && window.bootstrap.Alert && bootstrap.Alert.VERSION) || '3.x.x';
  30. }
  31. String.prototype.setTokens = function (replacePairs) {
  32. var str = this.toString(), key, re;
  33. for (key in replacePairs) {
  34. if (replacePairs.hasOwnProperty(key)) {
  35. re = new RegExp('\{' + key + '\}', 'g');
  36. str = str.replace(re, replacePairs[key]);
  37. }
  38. }
  39. return str;
  40. };
  41. if (!Array.prototype.flatMap) { // polyfill flatMap
  42. Array.prototype.flatMap = function (lambda) {
  43. return [].concat(this.map(lambda));
  44. };
  45. }
  46. if (!document.currentScript) {
  47. document.currentScript = function() {
  48. var scripts = document.getElementsByTagName('script');
  49. return scripts[scripts.length - 1];
  50. }();
  51. }
  52. var $h, FileInput, getLoadingUrl = function () {
  53. var src = document.currentScript.src, srcPath = src.substring(0, src.lastIndexOf("/"));
  54. return srcPath + '/loading.gif'
  55. };
  56. // fileinput helper object for all global variables and internal helper methods
  57. $h = {
  58. FRAMES: '.kv-preview-thumb',
  59. SORT_CSS: 'file-sortable',
  60. INIT_FLAG: 'init-',
  61. ZOOM_VAR: getLoadingUrl() + '?kvTemp__2873389129__=', // used to prevent 404 errors in URL parsing
  62. OBJECT_PARAMS: '<param name="controller" value="true" />\n' +
  63. '<param name="allowFullScreen" value="true" />\n' +
  64. '<param name="allowScriptAccess" value="always" />\n' +
  65. '<param name="autoPlay" value="false" />\n' +
  66. '<param name="autoStart" value="false" />\n' +
  67. '<param name="quality" value="high" />\n',
  68. DEFAULT_PREVIEW: '<div class="file-preview-other">\n' +
  69. '<span class="{previewFileIconClass}">{previewFileIcon}</span>\n' +
  70. '</div>',
  71. MODAL_ID: 'kvFileinputModal',
  72. MODAL_EVENTS: ['show', 'shown', 'hide', 'hidden', 'loaded'],
  73. logMessages: {
  74. ajaxError: '{status}: {error}. Error Details: {text}.',
  75. badDroppedFiles: 'Error scanning dropped files!',
  76. badExifParser: 'Error loading the piexif.js library. {details}',
  77. badInputType: 'The input "type" must be set to "file" for initializing the "bootstrap-fileinput" plugin.',
  78. exifWarning: 'To avoid this warning, either set "autoOrientImage" to "false" OR ensure you have loaded ' +
  79. 'the "piexif.js" library correctly on your page before the "fileinput.js" script.',
  80. invalidChunkSize: 'Invalid upload chunk size: "{chunkSize}". Resumable uploads are disabled.',
  81. invalidThumb: 'Invalid thumb frame with id: "{id}".',
  82. noResumableSupport: 'The browser does not support resumable or chunk uploads.',
  83. noUploadUrl: 'The "uploadUrl" is not set. Ajax uploads and resumable uploads have been disabled.',
  84. retryStatus: 'Retrying upload for chunk # {chunk} for {filename}... retry # {retry}.',
  85. chunkQueueError: 'Could not push task to ajax pool for chunk index # {index}.',
  86. resumableMaxRetriesReached: 'Maximum resumable ajax retries ({n}) reached.',
  87. resumableRetryError: 'Could not retry the resumable request (try # {n})... aborting.',
  88. resumableAborting: 'Aborting / cancelling the resumable request.',
  89. resumableRequestError: 'Error processing resumable request. {msg}'
  90. },
  91. objUrl: window.URL || window.webkitURL,
  92. isBs: function (ver) {
  93. var chk = $.trim(($.fn.fileinputBsVersion || '') + '');
  94. ver = parseInt(ver, 10);
  95. if (!chk) {
  96. return ver === 4;
  97. }
  98. return ver === parseInt(chk.charAt(0), 10);
  99. },
  100. defaultButtonCss: function (fill) {
  101. return 'btn-default btn-' + (fill ? '' : 'outline-') + 'secondary';
  102. },
  103. now: function () {
  104. return new Date().getTime();
  105. },
  106. round: function (num) {
  107. num = parseFloat(num);
  108. return isNaN(num) ? 0 : Math.floor(Math.round(num));
  109. },
  110. getArray: function (obj) {
  111. var i, arr = [], len = obj && obj.length || 0;
  112. for (i = 0; i < len; i++) {
  113. arr.push(obj[i]);
  114. }
  115. return arr;
  116. },
  117. getFileRelativePath: function (file) {
  118. /** @namespace file.relativePath */
  119. /** @namespace file.webkitRelativePath */
  120. return String(file.newPath || file.relativePath || file.webkitRelativePath || $h.getFileName(file) || null);
  121. },
  122. getFileId: function (file, generateFileId) {
  123. var relativePath = $h.getFileRelativePath(file);
  124. if (typeof generateFileId === 'function') {
  125. return generateFileId(file);
  126. }
  127. if (!file) {
  128. return null;
  129. }
  130. if (!relativePath) {
  131. return null;
  132. }
  133. return (file.size + '_' + encodeURIComponent(relativePath).replace(/%/g, '_'));
  134. },
  135. getFrameSelector: function (id, selector) {
  136. selector = selector || '';
  137. return '[id="' + id + '"]' + selector;
  138. },
  139. getZoomSelector: function (id, selector) {
  140. return $h.getFrameSelector('zoom-' + id, selector);
  141. },
  142. getFrameElement: function ($element, id, selector) {
  143. return $element.find($h.getFrameSelector(id, selector));
  144. },
  145. getZoomElement: function ($element, id, selector) {
  146. return $element.find($h.getZoomSelector(id, selector));
  147. },
  148. getElapsed: function (seconds) {
  149. var delta = seconds, out = '', result = {}, structure = {
  150. year: 31536000,
  151. month: 2592000,
  152. week: 604800, // uncomment row to ignore
  153. day: 86400, // feel free to add your own row
  154. hour: 3600,
  155. minute: 60,
  156. second: 1
  157. };
  158. $h.getObjectKeys(structure).forEach(function (key) {
  159. result[key] = Math.floor(delta / structure[key]);
  160. delta -= result[key] * structure[key];
  161. });
  162. $.each(result, function (key, value) {
  163. if (value > 0) {
  164. out += (out ? ' ' : '') + value + key.substring(0, 1);
  165. }
  166. });
  167. return out;
  168. },
  169. debounce: function (func, delay) {
  170. var inDebounce;
  171. return function () {
  172. var args = arguments, context = this;
  173. clearTimeout(inDebounce);
  174. inDebounce = setTimeout(function () {
  175. func.apply(context, args);
  176. }, delay);
  177. };
  178. },
  179. stopEvent: function (e) {
  180. e.stopPropagation();
  181. e.preventDefault();
  182. },
  183. getFileName: function (file) {
  184. /** @namespace file.fileName */
  185. return file ? (file.fileName || file.name || '') : ''; // some confusion in different versions of Firefox
  186. },
  187. createObjectURL: function (data) {
  188. if ($h.objUrl && $h.objUrl.createObjectURL && data) {
  189. return $h.objUrl.createObjectURL(data);
  190. }
  191. return '';
  192. },
  193. revokeObjectURL: function (data) {
  194. if ($h.objUrl && $h.objUrl.revokeObjectURL && data) {
  195. $h.objUrl.revokeObjectURL(data);
  196. }
  197. },
  198. compare: function (input, str, exact) {
  199. return input !== undefined && (exact ? input === str : input.match(str));
  200. },
  201. isIE: function (ver) {
  202. var div, status;
  203. // check for IE versions < 11
  204. if (navigator.appName !== 'Microsoft Internet Explorer') {
  205. return false;
  206. }
  207. if (ver === 10) {
  208. return new RegExp('msie\\s' + ver, 'i').test(navigator.userAgent);
  209. }
  210. div = document.createElement('div');
  211. div.innerHTML = '<!--[if IE ' + ver + ']> <i></i> <![endif]-->';
  212. status = div.getElementsByTagName('i').length;
  213. document.body.appendChild(div);
  214. div.parentNode.removeChild(div);
  215. return status;
  216. },
  217. canOrientImage: function ($el) {
  218. var $img = $(document.createElement('img')).css({width: '1px', height: '1px'}).insertAfter($el),
  219. flag = $img.css('image-orientation');
  220. $img.remove();
  221. return !!flag;
  222. },
  223. canAssignFilesToInput: function () {
  224. var input = document.createElement('input');
  225. try {
  226. input.type = 'file';
  227. input.files = null;
  228. return true;
  229. } catch (err) {
  230. return false;
  231. }
  232. },
  233. getDragDropFolders: function (items) {
  234. var i, item, len = items ? items.length : 0, folders = 0;
  235. if (len > 0 && items[0].webkitGetAsEntry()) {
  236. for (i = 0; i < len; i++) {
  237. item = items[i].webkitGetAsEntry();
  238. if (item && item.isDirectory) {
  239. folders++;
  240. }
  241. }
  242. }
  243. return folders;
  244. },
  245. initModal: function ($modal) {
  246. var $body = $('body');
  247. if ($body.length) {
  248. $modal.appendTo($body);
  249. }
  250. },
  251. isFunction: function (v) {
  252. return typeof v === 'function';
  253. },
  254. isEmpty: function (value, trim) {
  255. if (value === undefined || value === null || value === '') {
  256. return true;
  257. }
  258. if ($h.isString(value) && trim) {
  259. return $.trim(value) === '';
  260. }
  261. if ($h.isArray(value)) {
  262. return value.length === 0;
  263. }
  264. if ($.isPlainObject(value) && $.isEmptyObject(value)) {
  265. return true
  266. }
  267. return false;
  268. },
  269. isArray: function (a) {
  270. return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]';
  271. },
  272. isString: function (a) {
  273. return Object.prototype.toString.call(a) === '[object String]';
  274. },
  275. ifSet: function (needle, haystack, def) {
  276. def = def || '';
  277. return (haystack && typeof haystack === 'object' && needle in haystack) ? haystack[needle] : def;
  278. },
  279. cleanArray: function (arr) {
  280. if (!(arr instanceof Array)) {
  281. arr = [];
  282. }
  283. return arr.filter(function (e) {
  284. return (e !== undefined && e !== null);
  285. });
  286. },
  287. spliceArray: function (arr, index, reverseOrder) {
  288. var i, j = 0, out = [], newArr;
  289. if (!(arr instanceof Array)) {
  290. return [];
  291. }
  292. newArr = $.extend(true, [], arr);
  293. if (reverseOrder) {
  294. newArr.reverse();
  295. }
  296. for (i = 0; i < newArr.length; i++) {
  297. if (i !== index) {
  298. out[j] = newArr[i];
  299. j++;
  300. }
  301. }
  302. if (reverseOrder) {
  303. out.reverse();
  304. }
  305. return out;
  306. },
  307. getNum: function (num, def) {
  308. def = def || 0;
  309. if (typeof num === 'number') {
  310. return num;
  311. }
  312. if (typeof num === 'string') {
  313. num = parseFloat(num);
  314. }
  315. return isNaN(num) ? def : num;
  316. },
  317. hasFileAPISupport: function () {
  318. return !!(window.File && window.FileReader);
  319. },
  320. hasDragDropSupport: function () {
  321. var div = document.createElement('div');
  322. /** @namespace div.draggable */
  323. /** @namespace div.ondragstart */
  324. /** @namespace div.ondrop */
  325. return !$h.isIE(9) &&
  326. (div.draggable !== undefined || (div.ondragstart !== undefined && div.ondrop !== undefined));
  327. },
  328. hasFileUploadSupport: function () {
  329. return $h.hasFileAPISupport() && window.FormData;
  330. },
  331. hasBlobSupport: function () {
  332. try {
  333. return !!window.Blob && Boolean(new Blob());
  334. } catch (e) {
  335. return false;
  336. }
  337. },
  338. hasArrayBufferViewSupport: function () {
  339. try {
  340. return new Blob([new Uint8Array(100)]).size === 100;
  341. } catch (e) {
  342. return false;
  343. }
  344. },
  345. hasResumableUploadSupport: function () {
  346. /** @namespace Blob.prototype.webkitSlice */
  347. /** @namespace Blob.prototype.mozSlice */
  348. return $h.hasFileUploadSupport() && $h.hasBlobSupport() && $h.hasArrayBufferViewSupport() &&
  349. (!!Blob.prototype.webkitSlice || !!Blob.prototype.mozSlice || !!Blob.prototype.slice || false);
  350. },
  351. dataURI2Blob: function (dataURI) {
  352. var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder ||
  353. window.MSBlobBuilder, canBlob = $h.hasBlobSupport(), byteStr, arrayBuffer, intArray, i, mimeStr, bb,
  354. canProceed = (canBlob || BlobBuilder) && window.atob && window.ArrayBuffer && window.Uint8Array;
  355. if (!canProceed) {
  356. return null;
  357. }
  358. if (dataURI.split(',')[0].indexOf('base64') >= 0) {
  359. byteStr = atob(dataURI.split(',')[1]);
  360. } else {
  361. byteStr = decodeURIComponent(dataURI.split(',')[1]);
  362. }
  363. arrayBuffer = new ArrayBuffer(byteStr.length);
  364. intArray = new Uint8Array(arrayBuffer);
  365. for (i = 0; i < byteStr.length; i += 1) {
  366. intArray[i] = byteStr.charCodeAt(i);
  367. }
  368. mimeStr = dataURI.split(',')[0].split(':')[1].split(';')[0];
  369. if (canBlob) {
  370. return new Blob([$h.hasArrayBufferViewSupport() ? intArray : arrayBuffer], {type: mimeStr});
  371. }
  372. bb = new BlobBuilder();
  373. bb.append(arrayBuffer);
  374. return bb.getBlob(mimeStr);
  375. },
  376. arrayBuffer2String: function (buffer) {
  377. if (window.TextDecoder) {
  378. return new TextDecoder('utf-8').decode(buffer);
  379. }
  380. var array = Array.prototype.slice.apply(new Uint8Array(buffer)), out = '', i = 0, len, c, char2, char3;
  381. len = array.length;
  382. while (i < len) {
  383. c = array[i++];
  384. switch (c >> 4) { // jshint ignore:line
  385. case 0:
  386. case 1:
  387. case 2:
  388. case 3:
  389. case 4:
  390. case 5:
  391. case 6:
  392. case 7:
  393. // 0xxxxxxx
  394. out += String.fromCharCode(c);
  395. break;
  396. case 12:
  397. case 13:
  398. // 110x xxxx 10xx xxxx
  399. char2 = array[i++];
  400. out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); // jshint ignore:line
  401. break;
  402. case 14:
  403. // 1110 xxxx 10xx xxxx 10xx xxxx
  404. char2 = array[i++];
  405. char3 = array[i++];
  406. out += String.fromCharCode(((c & 0x0F) << 12) | // jshint ignore:line
  407. ((char2 & 0x3F) << 6) | // jshint ignore:line
  408. ((char3 & 0x3F) << 0)); // jshint ignore:line
  409. break;
  410. }
  411. }
  412. return out;
  413. },
  414. isHtml: function (str) {
  415. var a = document.createElement('div');
  416. a.innerHTML = str;
  417. for (var c = a.childNodes, i = c.length; i--;) {
  418. if (c[i].nodeType === 1) {
  419. return true;
  420. }
  421. }
  422. return false;
  423. },
  424. isSvg: function (str) {
  425. return str.match(/^\s*<\?xml/i) && (str.match(/<!DOCTYPE svg/i) || str.match(/<svg/i));
  426. },
  427. getMimeType: function (signature, contents, type) {
  428. switch (signature) {
  429. case 'ffd8ffe0':
  430. case 'ffd8ffe1':
  431. case 'ffd8ffe2':
  432. return 'image/jpeg';
  433. case '89504e47':
  434. return 'image/png';
  435. case '47494638':
  436. return 'image/gif';
  437. case '49492a00':
  438. return 'image/tiff';
  439. case '52494646':
  440. return 'image/webp';
  441. case '66747970':
  442. return 'video/3gp';
  443. case '4f676753':
  444. return 'video/ogg';
  445. case '1a45dfa3':
  446. return 'video/mkv';
  447. case '000001ba':
  448. case '000001b3':
  449. return 'video/mpeg';
  450. case '3026b275':
  451. return 'video/wmv';
  452. case '25504446':
  453. return 'application/pdf';
  454. case '25215053':
  455. return 'application/ps';
  456. case '504b0304':
  457. case '504b0506':
  458. case '504b0508':
  459. return 'application/zip';
  460. case '377abcaf':
  461. return 'application/7z';
  462. case '75737461':
  463. return 'application/tar';
  464. case '7801730d':
  465. return 'application/dmg';
  466. default:
  467. switch (signature.substring(0, 6)) {
  468. case '435753':
  469. return 'application/x-shockwave-flash';
  470. case '494433':
  471. return 'audio/mp3';
  472. case '425a68':
  473. return 'application/bzip';
  474. default:
  475. switch (signature.substring(0, 4)) {
  476. case '424d':
  477. return 'image/bmp';
  478. case 'fffb':
  479. return 'audio/mp3';
  480. case '4d5a':
  481. return 'application/exe';
  482. case '1f9d':
  483. case '1fa0':
  484. return 'application/zip';
  485. case '1f8b':
  486. return 'application/gzip';
  487. default:
  488. return contents && !contents.match(
  489. /[^\u0000-\u007f]/) ? 'application/text-plain' : type;
  490. }
  491. }
  492. }
  493. },
  494. addCss: function ($el, css) {
  495. $el.removeClass(css).addClass(css);
  496. },
  497. getElement: function (options, param, value) {
  498. return ($h.isEmpty(options) || $h.isEmpty(options[param])) ? value : $(options[param]);
  499. },
  500. createElement: function (str, tag) {
  501. tag = tag || 'div';
  502. return $($.parseHTML('<' + tag + '>' + str + '</' + tag + '>'));
  503. },
  504. uniqId: function () {
  505. return (new Date().getTime() + Math.floor(Math.random() * Math.pow(10, 15))).toString(36);
  506. },
  507. cspBuffer: {
  508. CSP_ATTRIB: 'data-csp-01928735', // a randomly named temporary attribute to store the CSP elem id
  509. domElementsStyles: {},
  510. stash: function (htmlString) {
  511. var self = this, outerDom = $.parseHTML('<div>' + htmlString + '</div>'), $el = $(outerDom);
  512. $el.find('[style]').each(function (key, elem) {
  513. var $elem = $(elem), styleDeclaration = $elem[0].style, id = $h.uniqId(), styles = {};
  514. if (styleDeclaration && styleDeclaration.length) {
  515. $(styleDeclaration).each(function () {
  516. styles[this] = styleDeclaration[this];
  517. });
  518. self.domElementsStyles[id] = styles;
  519. $elem.removeAttr('style').attr(self.CSP_ATTRIB, id);
  520. }
  521. });
  522. $el.filter('*').removeAttr('style'); // make sure all style attr are removed
  523. var values = Object.values ? Object.values(outerDom) : Object.keys(outerDom).map(function (itm) {
  524. return outerDom[itm];
  525. });
  526. return values.flatMap(function (elem) {
  527. return elem.innerHTML;
  528. }).join('');
  529. },
  530. apply: function (domElement) {
  531. var self = this, $el = $(domElement);
  532. $el.find('[' + self.CSP_ATTRIB + ']').each(function (key, elem) {
  533. var $elem = $(elem), id = $elem.attr(self.CSP_ATTRIB), styles = self.domElementsStyles[id];
  534. if (styles) {
  535. $elem.css(styles);
  536. }
  537. $elem.removeAttr(self.CSP_ATTRIB);
  538. });
  539. self.domElementsStyles = {};
  540. }
  541. },
  542. setHtml: function ($elem, htmlString) {
  543. var buf = $h.cspBuffer;
  544. $elem.html(buf.stash(htmlString));
  545. buf.apply($elem);
  546. return $elem;
  547. },
  548. htmlEncode: function (str, undefVal) {
  549. if (str === undefined) {
  550. return undefVal || null;
  551. }
  552. return str.replace(/&/g, '&amp;')
  553. .replace(/</g, '&lt;')
  554. .replace(/>/g, '&gt;')
  555. .replace(/"/g, '&quot;')
  556. .replace(/'/g, '&apos;');
  557. },
  558. replaceTags: function (str, tags) {
  559. var out = str;
  560. if (!tags) {
  561. return out;
  562. }
  563. $.each(tags, function (key, value) {
  564. if (typeof value === 'function') {
  565. value = value();
  566. }
  567. out = out.split(key).join(value);
  568. });
  569. return out;
  570. },
  571. cleanMemory: function ($thumb) {
  572. var data = $thumb.is('img') ? $thumb.attr('src') : $thumb.find('source').attr('src');
  573. $h.revokeObjectURL(data);
  574. },
  575. findFileName: function (filePath) {
  576. var sepIndex = filePath.lastIndexOf('/');
  577. if (sepIndex === -1) {
  578. sepIndex = filePath.lastIndexOf('\\');
  579. }
  580. return filePath.split(filePath.substring(sepIndex, sepIndex + 1)).pop();
  581. },
  582. checkFullScreen: function () {
  583. return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement ||
  584. document.msFullscreenElement;
  585. },
  586. toggleFullScreen: function (maximize) {
  587. var doc = document, de = doc.documentElement, isFullScreen = $h.checkFullScreen();
  588. if (de && maximize && !isFullScreen) {
  589. if (de.requestFullscreen) {
  590. de.requestFullscreen();
  591. } else {
  592. if (de.msRequestFullscreen) {
  593. de.msRequestFullscreen();
  594. } else {
  595. if (de.mozRequestFullScreen) {
  596. de.mozRequestFullScreen();
  597. } else {
  598. if (de.webkitRequestFullscreen) {
  599. de.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
  600. }
  601. }
  602. }
  603. }
  604. } else {
  605. if (isFullScreen) {
  606. if (doc.exitFullscreen) {
  607. doc.exitFullscreen();
  608. } else {
  609. if (doc.msExitFullscreen) {
  610. doc.msExitFullscreen();
  611. } else {
  612. if (doc.mozCancelFullScreen) {
  613. doc.mozCancelFullScreen();
  614. } else {
  615. if (doc.webkitExitFullscreen) {
  616. doc.webkitExitFullscreen();
  617. }
  618. }
  619. }
  620. }
  621. }
  622. }
  623. },
  624. moveArray: function (arr, oldIndex, newIndex, reverseOrder) {
  625. var newArr = $.extend(true, [], arr);
  626. if (reverseOrder) {
  627. newArr.reverse();
  628. }
  629. if (newIndex >= newArr.length) {
  630. var k = newIndex - newArr.length;
  631. while ((k--) + 1) {
  632. newArr.push(undefined);
  633. }
  634. }
  635. newArr.splice(newIndex, 0, newArr.splice(oldIndex, 1)[0]);
  636. if (reverseOrder) {
  637. newArr.reverse();
  638. }
  639. return newArr;
  640. },
  641. closeButton: function (css) {
  642. css = ($h.isBs(5) ? 'btn-close' : 'close') + (css ? ' ' + css : '');
  643. return '<button type="button" class="' + css + '" aria-label="Close">\n' +
  644. ($h.isBs(5) ? '' : ' <span aria-hidden="true">&times;</span>\n') +
  645. '</button>';
  646. },
  647. getRotation: function (value) {
  648. switch (value) {
  649. case 2:
  650. return 'rotateY(180deg)';
  651. case 3:
  652. return 'rotate(180deg)';
  653. case 4:
  654. return 'rotate(180deg) rotateY(180deg)';
  655. case 5:
  656. return 'rotate(270deg) rotateY(180deg)';
  657. case 6:
  658. return 'rotate(90deg)';
  659. case 7:
  660. return 'rotate(90deg) rotateY(180deg)';
  661. case 8:
  662. return 'rotate(270deg)';
  663. default:
  664. return '';
  665. }
  666. },
  667. setTransform: function (el, val) {
  668. if (!el) {
  669. return;
  670. }
  671. el.style.transform = val;
  672. el.style.webkitTransform = val;
  673. el.style['-moz-transform'] = val;
  674. el.style['-ms-transform'] = val;
  675. el.style['-o-transform'] = val;
  676. },
  677. getObjectKeys: function (obj) {
  678. var keys = [];
  679. if (obj) {
  680. $.each(obj, function (key) {
  681. keys.push(key);
  682. });
  683. }
  684. return keys;
  685. },
  686. getObjectSize: function (obj) {
  687. return $h.getObjectKeys(obj).length;
  688. },
  689. /**
  690. * Small dependency injection for the task manager
  691. * https://gist.github.com/fearphage/4341799
  692. */
  693. whenAll: function (array) {
  694. var s = [].slice, resolveValues = arguments.length === 1 && $h.isArray(array) ? array : s.call(arguments),
  695. deferred = $.Deferred(), i, failed = 0, value, length = resolveValues.length,
  696. remaining = length, rejectContexts, rejectValues, resolveContexts, updateFunc;
  697. rejectContexts = rejectValues = resolveContexts = Array(length);
  698. updateFunc = function (index, contexts, values) {
  699. return function () {
  700. if (values !== resolveValues) {
  701. failed++;
  702. }
  703. deferred.notifyWith(contexts[index] = this, values[index] = s.call(arguments));
  704. if (!(--remaining)) {
  705. deferred[(!failed ? 'resolve' : 'reject') + 'With'](contexts, values);
  706. }
  707. };
  708. };
  709. for (i = 0; i < length; i++) {
  710. if ((value = resolveValues[i]) && $.isFunction(value.promise)) {
  711. value.promise()
  712. .done(updateFunc(i, resolveContexts, resolveValues))
  713. .fail(updateFunc(i, rejectContexts, rejectValues));
  714. } else {
  715. deferred.notifyWith(this, value);
  716. --remaining;
  717. }
  718. }
  719. if (!remaining) {
  720. deferred.resolveWith(resolveContexts, resolveValues);
  721. }
  722. return deferred.promise();
  723. }
  724. };
  725. FileInput = function (element, options) {
  726. var self = this;
  727. self.$element = $(element);
  728. self.$parent = self.$element.parent();
  729. if (!self._validate()) {
  730. return;
  731. }
  732. self.isPreviewable = $h.hasFileAPISupport();
  733. self.isIE9 = $h.isIE(9);
  734. self.isIE10 = $h.isIE(10);
  735. if (self.isPreviewable || self.isIE9) {
  736. self._init(options);
  737. self._listen();
  738. }
  739. self.$element.removeClass('file-loading');
  740. };
  741. FileInput.prototype = {
  742. constructor: FileInput,
  743. _cleanup: function () {
  744. var self = this;
  745. self.reader = null;
  746. self.clearFileStack();
  747. self.fileBatchCompleted = true;
  748. self.isError = false;
  749. self.isDuplicateError = false;
  750. self.isPersistentError = false;
  751. self.cancelling = false;
  752. self.paused = false;
  753. self.lastProgress = 0;
  754. self._initAjax();
  755. },
  756. _isAborted: function () {
  757. var self = this;
  758. return self.cancelling || self.paused;
  759. },
  760. _initAjax: function () {
  761. var self = this, tm = self.taskManager = {
  762. pool: {},
  763. addPool: function (id) {
  764. return (tm.pool[id] = new tm.TasksPool(id));
  765. },
  766. getPool: function (id) {
  767. return tm.pool[id];
  768. },
  769. addTask: function (id, logic) { // add standalone task directly from task manager
  770. return new tm.Task(id, logic);
  771. },
  772. TasksPool: function (id) {
  773. var tp = this;
  774. tp.id = id;
  775. tp.cancelled = false;
  776. tp.cancelledDeferrer = $.Deferred();
  777. tp.tasks = {};
  778. tp.addTask = function (id, logic) {
  779. return (tp.tasks[id] = new tm.Task(id, logic));
  780. };
  781. tp.size = function () {
  782. return $h.getObjectSize(tp.tasks);
  783. };
  784. tp.run = function (maxThreads) {
  785. var i = 0, failed = false, task, tasksList = $h.getObjectKeys(tp.tasks).map(function (key) {
  786. return tp.tasks[key];
  787. }), tasksDone = [], deferred = $.Deferred(), enqueue, callback;
  788. if (tp.cancelled) {
  789. tp.cancelledDeferrer.resolve();
  790. return deferred.reject();
  791. }
  792. // if run all at once
  793. if (!maxThreads) {
  794. var tasksDeferredList = $h.getObjectKeys(tp.tasks).map(function (key) {
  795. return tp.tasks[key].deferred;
  796. });
  797. // when all are done
  798. $h.whenAll(tasksDeferredList).done(function () {
  799. var argv = $h.getArray(arguments);
  800. if (!tp.cancelled) {
  801. deferred.resolve.apply(null, argv);
  802. tp.cancelledDeferrer.reject();
  803. } else {
  804. deferred.reject.apply(null, argv);
  805. tp.cancelledDeferrer.resolve();
  806. }
  807. }).fail(function () {
  808. var argv = $h.getArray(arguments);
  809. deferred.reject.apply(null, argv);
  810. if (!tp.cancelled) {
  811. tp.cancelledDeferrer.reject();
  812. } else {
  813. tp.cancelledDeferrer.resolve();
  814. }
  815. });
  816. // run all tasks
  817. $.each(tp.tasks, function (id) {
  818. task = tp.tasks[id];
  819. task.run();
  820. });
  821. return deferred;
  822. }
  823. enqueue = function (task) {
  824. $.when(task.deferred)
  825. .fail(function () {
  826. failed = true;
  827. callback.apply(null, arguments);
  828. })
  829. .always(callback);
  830. };
  831. callback = function () {
  832. var argv = $h.getArray(arguments);
  833. // notify a task just ended
  834. deferred.notify(argv);
  835. tasksDone.push(argv);
  836. if (tp.cancelled) {
  837. deferred.reject.apply(null, tasksDone);
  838. tp.cancelledDeferrer.resolve();
  839. return;
  840. }
  841. if (tasksDone.length === tp.size()) {
  842. if (failed) {
  843. deferred.reject.apply(null, tasksDone);
  844. } else {
  845. deferred.resolve.apply(null, tasksDone);
  846. }
  847. }
  848. // if there are any tasks remaining
  849. if (tasksList.length) {
  850. task = tasksList.shift();
  851. enqueue(task);
  852. task.run();
  853. }
  854. };
  855. // run the first "maxThreads" tasks
  856. while (tasksList.length && i++ < maxThreads) {
  857. task = tasksList.shift();
  858. enqueue(task);
  859. task.run();
  860. }
  861. return deferred;
  862. };
  863. tp.cancel = function () {
  864. tp.cancelled = true;
  865. return tp.cancelledDeferrer;
  866. };
  867. },
  868. Task: function (id, logic) {
  869. var tk = this;
  870. tk.id = id;
  871. tk.deferred = $.Deferred();
  872. tk.logic = logic;
  873. tk.context = null;
  874. tk.run = function () {
  875. var argv = $h.getArray(arguments);
  876. argv.unshift(tk.deferred); // add deferrer as first argument
  877. logic.apply(tk.context, argv); // run task
  878. return tk.deferred; // return deferrer
  879. };
  880. tk.runWithContext = function (context) {
  881. tk.context = context;
  882. return tk.run();
  883. };
  884. }
  885. };
  886. self.ajaxQueue = [];
  887. self.ajaxRequests = [];
  888. self.ajaxAborted = false;
  889. },
  890. _init: function (options, refreshMode) {
  891. var self = this, f, $el = self.$element, $cont, t, tmp;
  892. self.options = options;
  893. self.canOrientImage = $h.canOrientImage($el);
  894. $.each(options, function (key, value) {
  895. switch (key) {
  896. case 'minFileCount':
  897. case 'maxFileCount':
  898. case 'maxTotalFileCount':
  899. case 'minFileSize':
  900. case 'maxFileSize':
  901. case 'maxFilePreviewSize':
  902. case 'resizeQuality':
  903. case 'resizeIfSizeMoreThan':
  904. case 'progressUploadThreshold':
  905. case 'initialPreviewCount':
  906. case 'zoomModalHeight':
  907. case 'minImageHeight':
  908. case 'maxImageHeight':
  909. case 'minImageWidth':
  910. case 'maxImageWidth':
  911. case 'bytesToKB':
  912. self[key] = $h.getNum(value);
  913. break;
  914. default:
  915. self[key] = value;
  916. break;
  917. }
  918. });
  919. if (!self.bytesToKB || self.bytesToKB <= 0) {
  920. self.bytesToKB = 1024;
  921. }
  922. if (self.errorCloseButton === undefined) {
  923. self.errorCloseButton = $h.closeButton('kv-error-close' + ($h.isBs(5) ? ' float-end' : ''));
  924. }
  925. if (self.maxTotalFileCount > 0 && self.maxTotalFileCount < self.maxFileCount) {
  926. self.maxTotalFileCount = self.maxFileCount;
  927. }
  928. if (self.rtl) { // swap buttons for rtl
  929. tmp = self.previewZoomButtonIcons.prev;
  930. self.previewZoomButtonIcons.prev = self.previewZoomButtonIcons.next;
  931. self.previewZoomButtonIcons.next = tmp;
  932. }
  933. // validate chunk threads to not exceed maxAjaxThreads
  934. if (!isNaN(self.maxAjaxThreads) && self.maxAjaxThreads < self.resumableUploadOptions.maxThreads) {
  935. self.resumableUploadOptions.maxThreads = self.maxAjaxThreads;
  936. }
  937. self._initFileManager();
  938. if (typeof self.autoOrientImage === 'function') {
  939. self.autoOrientImage = self.autoOrientImage();
  940. }
  941. if (typeof self.autoOrientImageInitial === 'function') {
  942. self.autoOrientImageInitial = self.autoOrientImageInitial();
  943. }
  944. if (!refreshMode) {
  945. self._cleanup();
  946. }
  947. self.duplicateErrors = [];
  948. self.$form = $el.closest('form');
  949. self._initTemplateDefaults();
  950. self.uploadFileAttr = !$h.isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data';
  951. t = self._getLayoutTemplate('progress');
  952. self.progressTemplate = t.replace('{class}', self.progressClass);
  953. self.progressInfoTemplate = t.replace('{class}', self.progressInfoClass);
  954. self.progressPauseTemplate = t.replace('{class}', self.progressPauseClass);
  955. self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass);
  956. self.progressErrorTemplate = t.replace('{class}', self.progressErrorClass);
  957. self.isDisabled = $el.attr('disabled') || $el.attr('readonly');
  958. if (self.isDisabled) {
  959. $el.attr('disabled', true);
  960. }
  961. self.isClickable = self.browseOnZoneClick && self.showPreview &&
  962. (self.dropZoneEnabled || !$h.isEmpty(self.defaultPreviewContent));
  963. self.isAjaxUpload = $h.hasFileUploadSupport() && !$h.isEmpty(self.uploadUrl);
  964. self.dropZoneEnabled = $h.hasDragDropSupport() && self.dropZoneEnabled;
  965. if (!self.isAjaxUpload) {
  966. self.dropZoneEnabled = self.dropZoneEnabled && $h.canAssignFilesToInput();
  967. }
  968. self.slug = typeof options.slugCallback === 'function' ? options.slugCallback : self._slugDefault;
  969. self.mainTemplate = self.showCaption ? self._getLayoutTemplate('main1') : self._getLayoutTemplate('main2');
  970. self.captionTemplate = self._getLayoutTemplate('caption');
  971. self.previewGenericTemplate = self._getPreviewTemplate('generic');
  972. if (!self.imageCanvas && self.resizeImage && (self.maxImageWidth || self.maxImageHeight)) {
  973. self.imageCanvas = document.createElement('canvas');
  974. self.imageCanvasContext = self.imageCanvas.getContext('2d');
  975. }
  976. if ($h.isEmpty($el.attr('id'))) {
  977. $el.attr('id', $h.uniqId());
  978. }
  979. self.namespace = '.fileinput_' + $el.attr('id').replace(/-/g, '_');
  980. if (self.$container === undefined) {
  981. self.$container = self._createContainer();
  982. } else {
  983. self._refreshContainer();
  984. }
  985. $cont = self.$container;
  986. self.$dropZone = $cont.find('.file-drop-zone');
  987. self.$progress = $cont.find('.kv-upload-progress');
  988. self.$btnUpload = $cont.find('.fileinput-upload');
  989. self.$captionContainer = $h.getElement(options, 'elCaptionContainer', $cont.find('.file-caption'));
  990. self.$caption = $h.getElement(options, 'elCaptionText', $cont.find('.file-caption-name'));
  991. if (!$h.isEmpty(self.msgPlaceholder)) {
  992. f = $el.attr('multiple') ? self.filePlural : self.fileSingle;
  993. self.$caption.attr('placeholder', self.msgPlaceholder.replace('{files}', f));
  994. }
  995. self.$captionIcon = self.$captionContainer.find('.file-caption-icon');
  996. self.$previewContainer = $h.getElement(options, 'elPreviewContainer', $cont.find('.file-preview'));
  997. self.$preview = $h.getElement(options, 'elPreviewImage', $cont.find('.file-preview-thumbnails'));
  998. self.$previewStatus = $h.getElement(options, 'elPreviewStatus', $cont.find('.file-preview-status'));
  999. self.$errorContainer = $h.getElement(options, 'elErrorContainer',
  1000. self.$previewContainer.find('.kv-fileinput-error'));
  1001. self._validateDisabled();
  1002. if (!$h.isEmpty(self.msgErrorClass)) {
  1003. $h.addCss(self.$errorContainer, self.msgErrorClass);
  1004. }
  1005. if (!refreshMode) {
  1006. self._resetErrors();
  1007. self.$errorContainer.hide();
  1008. self.previewInitId = 'thumb-' + $el.attr('id');
  1009. self._initPreviewCache();
  1010. self._initPreview(true);
  1011. self._initPreviewActions();
  1012. if (self.$parent.hasClass('file-loading')) {
  1013. self.$container.insertBefore(self.$parent);
  1014. self.$parent.remove();
  1015. }
  1016. } else {
  1017. if (!self._errorsExist()) {
  1018. self.$errorContainer.hide();
  1019. }
  1020. }
  1021. self._setFileDropZoneTitle();
  1022. if ($el.attr('disabled')) {
  1023. self.disable();
  1024. }
  1025. self._initZoom();
  1026. if (self.hideThumbnailContent) {
  1027. $h.addCss(self.$preview, 'hide-content');
  1028. }
  1029. },
  1030. _initFileManager: function () {
  1031. var self = this;
  1032. self.uploadStartTime = $h.now();
  1033. self.fileManager = {
  1034. stack: {},
  1035. filesProcessed: [],
  1036. errors: [],
  1037. loadedImages: {},
  1038. totalImages: 0,
  1039. totalFiles: null,
  1040. totalSize: null,
  1041. uploadedSize: 0,
  1042. stats: {},
  1043. bpsLog: [],
  1044. bps: 0,
  1045. initStats: function (id) {
  1046. var data = {started: $h.now()};
  1047. if (id) {
  1048. self.fileManager.stats[id] = data;
  1049. } else {
  1050. self.fileManager.stats = data;
  1051. }
  1052. },
  1053. getUploadStats: function (id, loaded, total) {
  1054. var fm = self.fileManager,
  1055. started = id ? fm.stats[id] && fm.stats[id].started || $h.now() : self.uploadStartTime,
  1056. elapsed = ($h.now() - started) / 1000, bps = Math.ceil(elapsed ? loaded / elapsed : 0),
  1057. pendingBytes = total - loaded, out, delay = fm.bpsLog.length ? self.bitrateUpdateDelay : 0;
  1058. setTimeout(function () {
  1059. var i, j = 0, n = 0, len, beg;
  1060. fm.bpsLog.push(bps);
  1061. fm.bpsLog.sort(function (a, b) {
  1062. return a - b;
  1063. });
  1064. len = fm.bpsLog.length;
  1065. beg = len > 10 ? len - 10 : Math.ceil(len / 2);
  1066. for (i = len; i > beg; i--) {
  1067. n = parseFloat(fm.bpsLog[i]);
  1068. j++;
  1069. }
  1070. fm.bps = (j > 0 ? n / j : 0) * 64;
  1071. }, delay);
  1072. out = {
  1073. fileId: id,
  1074. started: started,
  1075. elapsed: elapsed,
  1076. loaded: loaded,
  1077. total: total,
  1078. bps: fm.bps,
  1079. bitrate: self._getSize(fm.bps, self.bitRateUnits),
  1080. pendingBytes: pendingBytes
  1081. };
  1082. if (id) {
  1083. fm.stats[id] = out;
  1084. } else {
  1085. fm.stats = out;
  1086. }
  1087. return out;
  1088. },
  1089. exists: function (id) {
  1090. return $.inArray(id, self.fileManager.getIdList()) !== -1;
  1091. },
  1092. count: function () {
  1093. return self.fileManager.getIdList().length;
  1094. },
  1095. total: function () {
  1096. var fm = self.fileManager;
  1097. if (!fm.totalFiles) {
  1098. fm.totalFiles = fm.count();
  1099. }
  1100. return fm.totalFiles;
  1101. },
  1102. getTotalSize: function () {
  1103. var fm = self.fileManager;
  1104. if (fm.totalSize) {
  1105. return fm.totalSize;
  1106. }
  1107. fm.totalSize = 0;
  1108. $.each(self.getFileStack(), function (id, f) {
  1109. var size = parseFloat(f.size);
  1110. fm.totalSize += isNaN(size) ? 0 : size;
  1111. });
  1112. return fm.totalSize;
  1113. },
  1114. add: function (file, id) {
  1115. if (!id) {
  1116. id = self.fileManager.getId(file);
  1117. }
  1118. if (!id) {
  1119. return;
  1120. }
  1121. self.fileManager.stack[id] = {
  1122. file: file,
  1123. name: $h.getFileName(file),
  1124. relativePath: $h.getFileRelativePath(file),
  1125. size: file.size,
  1126. nameFmt: self._getFileName(file, ''),
  1127. sizeFmt: self._getSize(file.size)
  1128. };
  1129. },
  1130. remove: function ($thumb) {
  1131. var id = self._getThumbFileId($thumb);
  1132. self.fileManager.removeFile(id);
  1133. },
  1134. removeFile: function (id) {
  1135. var fm = self.fileManager;
  1136. if (!id) {
  1137. return;
  1138. }
  1139. delete fm.stack[id];
  1140. delete fm.loadedImages[id];
  1141. },
  1142. move: function (idFrom, idTo) {
  1143. var result = {}, stack = self.fileManager.stack;
  1144. if (!idFrom && !idTo || idFrom === idTo) {
  1145. return;
  1146. }
  1147. $.each(stack, function (k, v) {
  1148. if (k !== idFrom) {
  1149. result[k] = v;
  1150. }
  1151. if (k === idTo) {
  1152. result[idFrom] = stack[idFrom];
  1153. }
  1154. });
  1155. self.fileManager.stack = result;
  1156. },
  1157. list: function () {
  1158. var files = [];
  1159. $.each(self.getFileStack(), function (k, v) {
  1160. if (v && v.file) {
  1161. files.push(v.file);
  1162. }
  1163. });
  1164. return files;
  1165. },
  1166. isPending: function (id) {
  1167. return $.inArray(id, self.fileManager.filesProcessed) === -1 && self.fileManager.exists(id);
  1168. },
  1169. isProcessed: function () {
  1170. var filesProcessed = true, fm = self.fileManager;
  1171. $.each(self.getFileStack(), function (id) {
  1172. if (fm.isPending(id)) {
  1173. filesProcessed = false;
  1174. }
  1175. });
  1176. return filesProcessed;
  1177. },
  1178. clear: function () {
  1179. var fm = self.fileManager;
  1180. self.isDuplicateError = false;
  1181. self.isPersistentError = false;
  1182. fm.totalFiles = null;
  1183. fm.totalSize = null;
  1184. fm.uploadedSize = 0;
  1185. fm.stack = {};
  1186. fm.errors = [];
  1187. fm.filesProcessed = [];
  1188. fm.stats = {};
  1189. fm.bpsLog = [];
  1190. fm.bps = 0;
  1191. fm.clearImages();
  1192. },
  1193. clearImages: function () {
  1194. self.fileManager.loadedImages = {};
  1195. self.fileManager.totalImages = 0;
  1196. },
  1197. addImage: function (id, config) {
  1198. self.fileManager.loadedImages[id] = config;
  1199. },
  1200. removeImage: function (id) {
  1201. delete self.fileManager.loadedImages[id];
  1202. },
  1203. getImageIdList: function () {
  1204. return $h.getObjectKeys(self.fileManager.loadedImages);
  1205. },
  1206. getImageCount: function () {
  1207. return self.fileManager.getImageIdList().length;
  1208. },
  1209. getId: function (file) {
  1210. return self._getFileId(file);
  1211. },
  1212. getIndex: function (id) {
  1213. return self.fileManager.getIdList().indexOf(id);
  1214. },
  1215. getThumb: function (id) {
  1216. var $thumb = null;
  1217. self._getThumbs().each(function () {
  1218. var $t = $(this);
  1219. if (self._getThumbFileId($t) === id) {
  1220. $thumb = $t;
  1221. }
  1222. });
  1223. return $thumb;
  1224. },
  1225. getThumbIndex: function ($thumb) {
  1226. var id = self._getThumbFileId($thumb);
  1227. return self.fileManager.getIndex(id);
  1228. },
  1229. getIdList: function () {
  1230. return $h.getObjectKeys(self.fileManager.stack);
  1231. },
  1232. getFile: function (id) {
  1233. return self.fileManager.stack[id] || null;
  1234. },
  1235. getFileName: function (id, fmt) {
  1236. var file = self.fileManager.getFile(id);
  1237. if (!file) {
  1238. return '';
  1239. }
  1240. return fmt ? (file.nameFmt || '') : file.name || '';
  1241. },
  1242. getFirstFile: function () {
  1243. var ids = self.fileManager.getIdList(), id = ids && ids.length ? ids[0] : null;
  1244. return self.fileManager.getFile(id);
  1245. },
  1246. setFile: function (id, file) {
  1247. if (self.fileManager.getFile(id)) {
  1248. self.fileManager.stack[id].file = file;
  1249. } else {
  1250. self.fileManager.add(file, id);
  1251. }
  1252. },
  1253. setProcessed: function (id) {
  1254. self.fileManager.filesProcessed.push(id);
  1255. },
  1256. getProgress: function () {
  1257. var total = self.fileManager.total(), filesProcessed = self.fileManager.filesProcessed.length;
  1258. if (!total) {
  1259. return 0;
  1260. }
  1261. return Math.ceil(filesProcessed / total * 100);
  1262. },
  1263. setProgress: function (id, pct) {
  1264. var f = self.fileManager.getFile(id);
  1265. if (!isNaN(pct) && f) {
  1266. f.progress = pct;
  1267. }
  1268. }
  1269. };
  1270. },
  1271. _setUploadData: function (fd, config) {
  1272. var self = this;
  1273. $.each(config, function (key, value) {
  1274. var param = self.uploadParamNames[key] || key;
  1275. if ($h.isArray(value)) {
  1276. fd.append(param, value[0], value[1]);
  1277. } else {
  1278. fd.append(param, value);
  1279. }
  1280. });
  1281. },
  1282. _initResumableUpload: function () {
  1283. var self = this, opts = self.resumableUploadOptions, logs = $h.logMessages, rm, fm = self.fileManager;
  1284. if (!self.enableResumableUpload) {
  1285. return;
  1286. }
  1287. if (opts.fallback !== false && typeof opts.fallback !== 'function') {
  1288. opts.fallback = function (s) {
  1289. s._log(logs.noResumableSupport);
  1290. s.enableResumableUpload = false;
  1291. };
  1292. }
  1293. if (!$h.hasResumableUploadSupport() && opts.fallback !== false) {
  1294. opts.fallback(self);
  1295. return;
  1296. }
  1297. if (!self.uploadUrl && self.enableResumableUpload) {
  1298. self._log(logs.noUploadUrl);
  1299. self.enableResumableUpload = false;
  1300. return;
  1301. }
  1302. opts.chunkSize = parseFloat(opts.chunkSize);
  1303. if (opts.chunkSize <= 0 || isNaN(opts.chunkSize)) {
  1304. self._log(logs.invalidChunkSize, {chunkSize: opts.chunkSize});
  1305. self.enableResumableUpload = false;
  1306. return;
  1307. }
  1308. rm = self.resumableManager = {
  1309. init: function (id, f, index) {
  1310. rm.logs = [];
  1311. rm.stack = [];
  1312. rm.error = '';
  1313. rm.id = id;
  1314. rm.file = f.file;
  1315. rm.fileName = f.name;
  1316. rm.fileIndex = index;
  1317. rm.completed = false;
  1318. rm.lastProgress = 0;
  1319. if (self.showPreview) {
  1320. rm.$thumb = fm.getThumb(id) || null;
  1321. rm.$progress = rm.$btnDelete = null;
  1322. if (rm.$thumb && rm.$thumb.length) {
  1323. rm.$progress = rm.$thumb.find('.file-thumb-progress');
  1324. rm.$btnDelete = rm.$thumb.find('.kv-file-remove');
  1325. }
  1326. }
  1327. rm.chunkSize = opts.chunkSize * self.bytesToKB;
  1328. rm.chunkCount = rm.getTotalChunks();
  1329. },
  1330. setAjaxError: function (jqXHR, textStatus, errorThrown, isTest) {
  1331. if (jqXHR.responseJSON && jqXHR.responseJSON.error) {
  1332. errorThrown = jqXHR.responseJSON.error.toString();
  1333. }
  1334. if (!isTest) {
  1335. rm.error = errorThrown;
  1336. }
  1337. if (opts.showErrorLog) {
  1338. self._log(logs.ajaxError, {
  1339. status: jqXHR.status,
  1340. error: errorThrown,
  1341. text: jqXHR.responseText || ''
  1342. });
  1343. }
  1344. },
  1345. reset: function () {
  1346. rm.stack = [];
  1347. rm.chunksProcessed = {};
  1348. },
  1349. setProcessed: function (status) {
  1350. var id = rm.id, msg, $thumb = rm.$thumb, $prog = rm.$progress, hasThumb = $thumb && $thumb.length,
  1351. params = {id: hasThumb ? $thumb.attr('id') : '', index: fm.getIndex(id), fileId: id}, tokens,
  1352. skipErrorsAndProceed = self.resumableUploadOptions.skipErrorsAndProceed;
  1353. rm.completed = true;
  1354. rm.lastProgress = 0;
  1355. if (hasThumb) {
  1356. $thumb.removeClass('file-uploading');
  1357. }
  1358. if (status === 'success') {
  1359. fm.uploadedSize += rm.file.size;
  1360. if (self.showPreview) {
  1361. self._setProgress(101, $prog);
  1362. self._setThumbStatus($thumb, 'Success');
  1363. self._initUploadSuccess(rm.chunksProcessed[id].data, $thumb);
  1364. }
  1365. fm.removeFile(id);
  1366. delete rm.chunksProcessed[id];
  1367. self._raise('fileuploaded', [params.id, params.index, params.fileId]);
  1368. if (fm.isProcessed()) {
  1369. self._setProgress(101);
  1370. }
  1371. } else {
  1372. if (status !== 'cancel') {
  1373. if (self.showPreview) {
  1374. self._setThumbStatus($thumb, 'Error');
  1375. self._setPreviewError($thumb, true);
  1376. self._setProgress(101, $prog, self.msgProgressError);
  1377. self._setProgress(101, self.$progress, self.msgProgressError);
  1378. self.cancelling = !skipErrorsAndProceed;
  1379. }
  1380. if (!self.$errorContainer.find('li[data-file-id="' + params.fileId + '"]').length) {
  1381. tokens = {file: rm.fileName, max: opts.maxRetries, error: rm.error};
  1382. msg = self.msgResumableUploadRetriesExceeded.setTokens(tokens);
  1383. $.extend(params, tokens);
  1384. self._showFileError(msg, params, 'filemaxretries');
  1385. if (skipErrorsAndProceed) {
  1386. fm.removeFile(id);
  1387. delete rm.chunksProcessed[id];
  1388. if (fm.isProcessed()) {
  1389. self._setProgress(101);
  1390. }
  1391. }
  1392. }
  1393. }
  1394. }
  1395. if (fm.isProcessed()) {
  1396. rm.reset();
  1397. }
  1398. },
  1399. check: function () {
  1400. var status = true;
  1401. $.each(rm.logs, function (index, value) {
  1402. if (!value) {
  1403. status = false;
  1404. return false;
  1405. }
  1406. });
  1407. },
  1408. processedResumables: function () {
  1409. var logs = rm.logs, i, count = 0;
  1410. if (!logs || !logs.length) {
  1411. return 0;
  1412. }
  1413. for (i = 0; i < logs.length; i++) {
  1414. if (logs[i] === true) {
  1415. count++;
  1416. }
  1417. }
  1418. return count;
  1419. },
  1420. getUploadedSize: function () {
  1421. var size = rm.processedResumables() * rm.chunkSize;
  1422. return size > rm.file.size ? rm.file.size : size;
  1423. },
  1424. getTotalChunks: function () {
  1425. var chunkSize = parseFloat(rm.chunkSize);
  1426. if (!isNaN(chunkSize) && chunkSize > 0) {
  1427. return Math.ceil(rm.file.size / chunkSize);
  1428. }
  1429. return 0;
  1430. },
  1431. getProgress: function () {
  1432. var chunksProcessed = rm.processedResumables(), total = rm.chunkCount;
  1433. if (total === 0) {
  1434. return 0;
  1435. }
  1436. return Math.ceil(chunksProcessed / total * 100);
  1437. },
  1438. checkAborted: function (intervalId) {
  1439. if (self._isAborted()) {
  1440. clearInterval(intervalId);
  1441. self.unlock();
  1442. }
  1443. },
  1444. upload: function () {
  1445. var ids = fm.getIdList(), flag = 'new', intervalId;
  1446. intervalId = setInterval(function () {
  1447. var id;
  1448. rm.checkAborted(intervalId);
  1449. if (flag === 'new') {
  1450. self.lock();
  1451. flag = 'processing';
  1452. id = ids.shift();
  1453. fm.initStats(id);
  1454. if (fm.stack[id]) {
  1455. rm.init(id, fm.stack[id], fm.getIndex(id));
  1456. rm.processUpload();
  1457. }
  1458. }
  1459. if (!fm.isPending(id) && rm.completed) {
  1460. flag = 'new';
  1461. }
  1462. if (fm.isProcessed()) {
  1463. var $initThumbs = self.$preview.find('.file-preview-initial');
  1464. if ($initThumbs.length) {
  1465. $h.addCss($initThumbs, $h.SORT_CSS);
  1466. self._initSortable();
  1467. }
  1468. clearInterval(intervalId);
  1469. self._clearFileInput();
  1470. self.unlock();
  1471. setTimeout(function () {
  1472. var data = self.previewCache.data;
  1473. if (data) {
  1474. self.initialPreview = data.content;
  1475. self.initialPreviewConfig = data.config;
  1476. self.initialPreviewThumbTags = data.tags;
  1477. }
  1478. self._raise('filebatchuploadcomplete', [
  1479. self.initialPreview,
  1480. self.initialPreviewConfig,
  1481. self.initialPreviewThumbTags,
  1482. self._getExtraData()
  1483. ]);
  1484. }, self.processDelay);
  1485. }
  1486. }, self.processDelay);
  1487. },
  1488. uploadResumable: function () {
  1489. var i, pool, tm = self.taskManager, total = rm.chunkCount;
  1490. pool = tm.addPool(rm.id);
  1491. for (i = 0; i < total; i++) {
  1492. rm.logs[i] = !!(rm.chunksProcessed[rm.id] && rm.chunksProcessed[rm.id][i]);
  1493. if (!rm.logs[i]) {
  1494. rm.pushAjax(i, 0);
  1495. }
  1496. }
  1497. pool.run(opts.maxThreads)
  1498. .done(function () {
  1499. rm.setProcessed('success');
  1500. })
  1501. .fail(function () {
  1502. rm.setProcessed(pool.cancelled ? 'cancel' : 'error');
  1503. });
  1504. },
  1505. processUpload: function () {
  1506. var fd, f, id = rm.id, fnBefore, fnSuccess, fnError, fnComplete, outData;
  1507. if (!opts.testUrl) {
  1508. rm.uploadResumable();
  1509. return;
  1510. }
  1511. fd = new FormData();
  1512. f = fm.stack[id];
  1513. self._setUploadData(fd, {
  1514. fileId: id,
  1515. fileName: f.fileName,
  1516. fileSize: f.size,
  1517. fileRelativePath: f.relativePath,
  1518. chunkSize: rm.chunkSize,
  1519. chunkCount: rm.chunkCount
  1520. });
  1521. fnBefore = function (jqXHR) {
  1522. outData = self._getOutData(fd, jqXHR);
  1523. self._raise('filetestbeforesend', [id, fm, rm, outData]);
  1524. };
  1525. fnSuccess = function (data, textStatus, jqXHR) {
  1526. outData = self._getOutData(fd, jqXHR, data);
  1527. var pNames = self.uploadParamNames, chunksUploaded = pNames.chunksUploaded || 'chunksUploaded',
  1528. params = [id, fm, rm, outData];
  1529. if (!data[chunksUploaded] || !$h.isArray(data[chunksUploaded])) {
  1530. self._raise('filetesterror', params);
  1531. } else {
  1532. if (!rm.chunksProcessed[id]) {
  1533. rm.chunksProcessed[id] = {};
  1534. }
  1535. $.each(data[chunksUploaded], function (key, index) {
  1536. rm.logs[index] = true;
  1537. rm.chunksProcessed[id][index] = true;
  1538. });
  1539. rm.chunksProcessed[id].data = data;
  1540. self._raise('filetestsuccess', params);
  1541. }
  1542. rm.uploadResumable();
  1543. };
  1544. fnError = function (jqXHR, textStatus, errorThrown) {
  1545. outData = self._getOutData(fd, jqXHR);
  1546. self._raise('filetestajaxerror', [id, fm, rm, outData]);
  1547. rm.setAjaxError(jqXHR, textStatus, errorThrown, true);
  1548. rm.uploadResumable();
  1549. };
  1550. fnComplete = function () {
  1551. self._raise('filetestcomplete', [id, fm, rm, self._getOutData(fd)]);
  1552. };
  1553. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, fd, id, rm.fileIndex, opts.testUrl);
  1554. },
  1555. pushAjax: function (index, retry) {
  1556. var tm = self.taskManager, pool = tm.getPool(rm.id);
  1557. pool.addTask(pool.size() + 1, function (deferrer) {
  1558. // use fifo chunk stack
  1559. var arr = rm.stack.shift(), index;
  1560. index = arr[0];
  1561. if (!rm.chunksProcessed[rm.id] || !rm.chunksProcessed[rm.id][index]) {
  1562. rm.sendAjax(index, arr[1], deferrer);
  1563. } else {
  1564. self._log(logs.chunkQueueError, {index: index});
  1565. }
  1566. });
  1567. rm.stack.push([index, retry]);
  1568. },
  1569. sendAjax: function (index, retry, deferrer) {
  1570. var f, chunkSize = rm.chunkSize, id = rm.id, file = rm.file, $thumb = rm.$thumb,
  1571. msgs = $h.logMessages, $btnDelete = rm.$btnDelete, logError = function (msg, tokens) {
  1572. if (tokens) {
  1573. msg = msg.setTokens(tokens);
  1574. }
  1575. msg = msgs.resumableRequestError.setTokens({msg: msg});
  1576. self._log(msg);
  1577. deferrer.reject(msg);
  1578. };
  1579. if (rm.chunksProcessed[id] && rm.chunksProcessed[id][index]) {
  1580. return;
  1581. }
  1582. if (retry > opts.maxRetries) {
  1583. logError(msgs.resumableMaxRetriesReached, {n: opts.maxRetries});
  1584. rm.setProcessed('error');
  1585. return;
  1586. }
  1587. var fd, outData, fnBefore, fnSuccess, fnError, fnComplete, slice = file.slice ? 'slice' :
  1588. (file.mozSlice ? 'mozSlice' : (file.webkitSlice ? 'webkitSlice' : 'slice')),
  1589. blob = file[slice](chunkSize * index, chunkSize * (index + 1));
  1590. fd = new FormData();
  1591. f = fm.stack[id];
  1592. self._setUploadData(fd, {
  1593. chunkCount: rm.chunkCount,
  1594. chunkIndex: index,
  1595. chunkSize: chunkSize,
  1596. chunkSizeStart: chunkSize * index,
  1597. fileBlob: [blob, rm.fileName],
  1598. fileId: id,
  1599. fileName: rm.fileName,
  1600. fileRelativePath: f.relativePath,
  1601. fileSize: file.size,
  1602. retryCount: retry
  1603. });
  1604. if (rm.$progress && rm.$progress.length) {
  1605. rm.$progress.show();
  1606. }
  1607. fnBefore = function (jqXHR) {
  1608. outData = self._getOutData(fd, jqXHR);
  1609. if (self.showPreview) {
  1610. if (!$thumb.hasClass('file-preview-success')) {
  1611. self._setThumbStatus($thumb, 'Loading');
  1612. $h.addCss($thumb, 'file-uploading');
  1613. }
  1614. $btnDelete.attr('disabled', true);
  1615. }
  1616. self._raise('filechunkbeforesend', [id, index, retry, fm, rm, outData]);
  1617. };
  1618. fnSuccess = function (data, textStatus, jqXHR) {
  1619. if (self._isAborted()) {
  1620. logError(msgs.resumableAborting);
  1621. return;
  1622. }
  1623. outData = self._getOutData(fd, jqXHR, data);
  1624. var paramNames = self.uploadParamNames, chunkIndex = paramNames.chunkIndex || 'chunkIndex',
  1625. params = [id, index, retry, fm, rm, outData];
  1626. if (data.error) {
  1627. if (opts.showErrorLog) {
  1628. self._log(logs.retryStatus, {
  1629. retry: retry + 1,
  1630. filename: rm.fileName,
  1631. chunk: index
  1632. });
  1633. }
  1634. self._raise('filechunkerror', params);
  1635. rm.pushAjax(index, retry + 1);
  1636. rm.error = data.error;
  1637. logError(data.error);
  1638. } else {
  1639. rm.logs[data[chunkIndex]] = true;
  1640. if (!rm.chunksProcessed[id]) {
  1641. rm.chunksProcessed[id] = {};
  1642. }
  1643. rm.chunksProcessed[id][data[chunkIndex]] = true;
  1644. rm.chunksProcessed[id].data = data;
  1645. deferrer.resolve.call(null, data);
  1646. self._raise('filechunksuccess', params);
  1647. rm.check();
  1648. }
  1649. };
  1650. fnError = function (jqXHR, textStatus, errorThrown) {
  1651. if (self._isAborted()) {
  1652. logError(msgs.resumableAborting);
  1653. return;
  1654. }
  1655. outData = self._getOutData(fd, jqXHR);
  1656. rm.setAjaxError(jqXHR, textStatus, errorThrown);
  1657. self._raise('filechunkajaxerror', [id, index, retry, fm, rm, outData]);
  1658. rm.pushAjax(index, retry + 1); // push another task
  1659. logError(msgs.resumableRetryError, {n: retry - 1}); // resolve the current task
  1660. };
  1661. fnComplete = function () {
  1662. if (!self._isAborted()) {
  1663. self._raise('filechunkcomplete', [id, index, retry, fm, rm, self._getOutData(fd)]);
  1664. }
  1665. };
  1666. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, fd, id, rm.fileIndex);
  1667. }
  1668. };
  1669. rm.reset();
  1670. },
  1671. _initTemplateDefaults: function () {
  1672. var self = this, tMain1, tMain2, tPreview, tFileIcon, tClose, tCaption, tBtnDefault, tBtnLink, tBtnBrowse,
  1673. tModalMain, tModal, tProgress, tSize, tFooter, tActions, tActionDelete, tActionUpload, tActionDownload,
  1674. tActionZoom, tActionDrag, tIndicator, tTagBef, tTagBef1, tTagBef2, tTagAft, tGeneric, tHtml, tImage,
  1675. tText, tOffice, tGdocs, tVideo, tAudio, tFlash, tObject, tPdf, tOther, tStyle, tZoomCache, vDefaultDim,
  1676. tStats, tModalLabel, tDescClose, renderObject = function (type, mime) {
  1677. return '<object class="kv-preview-data file-preview-' + type + '" title="{caption}" ' +
  1678. 'data="{data}" type="' + mime + '"' + tStyle + '>\n' + $h.DEFAULT_PREVIEW + '\n</object>\n';
  1679. }, defBtnCss1 = 'btn btn-sm btn-kv ' + $h.defaultButtonCss();
  1680. tMain1 = '{preview}\n' +
  1681. '<div class="kv-upload-progress kv-hidden"></div><div class="clearfix"></div>\n' +
  1682. '<div class="file-caption {class}">\n' +
  1683. ' <div class="input-group {inputGroupClass}">\n' +
  1684. ' {caption}\n<span class="file-caption-icon"></span>\n' +
  1685. ($h.isBs(5) ? '' : '<div class="input-group-btn input-group-append">\n') +
  1686. ' {remove}\n' +
  1687. ' {cancel}\n' +
  1688. ' {pause}\n' +
  1689. ' {upload}\n' +
  1690. ' {browse}\n' +
  1691. ($h.isBs(5) ? '' : ' </div>\n') +
  1692. ' </div>'
  1693. '</div>';
  1694. tMain2 = '{preview}\n<div class="kv-upload-progress kv-hidden"></div>\n<div class="clearfix"></div>\n' +
  1695. '<span class="{class}">{remove}\n{cancel}\n{upload}\n{browse}\n</span>';
  1696. tPreview = '<div class="file-preview {class}">\n' +
  1697. ' {close}' +
  1698. ' <div class="{dropClass} clearfix">\n' +
  1699. ' <div class="file-preview-thumbnails clearfix">\n' +
  1700. ' </div>\n' +
  1701. ' <div class="file-preview-status text-center text-success"></div>\n' +
  1702. ' <div class="kv-fileinput-error"></div>\n' +
  1703. ' </div>\n' +
  1704. '</div>';
  1705. tClose = $h.closeButton('fileinput-remove');
  1706. tFileIcon = '<i class="glyphicon glyphicon-file"></i>';
  1707. // noinspection HtmlUnknownAttribute
  1708. tCaption = '<input readonly class="file-caption-name form-control {class}">\n';
  1709. //noinspection HtmlUnknownAttribute
  1710. tBtnDefault = '<button type="{type}" title="{title}" class="{css}" ' +
  1711. '{status} {tabIndexConfig}>{icon} {label}</button>';
  1712. //noinspection HtmlUnknownTarget,HtmlUnknownAttribute
  1713. tBtnLink = '<a href="{href}" title="{title}" class="{css}" {status} {tabIndexConfig}>{icon} {label}</a>';
  1714. //noinspection HtmlUnknownAttribute
  1715. tBtnBrowse = '<div class="{css}" {status} {tabIndexConfig}>{icon} {label}</div>';
  1716. tModalLabel = $h.MODAL_ID + 'Label';
  1717. tModalMain = '<div id="' + $h.MODAL_ID + '" class="file-zoom-dialog modal fade" ' +
  1718. 'aria-labelledby="' + tModalLabel + '" {tabIndexConfig}></div>';
  1719. tModal = '<div class="modal-dialog modal-lg{rtl}" role="document">\n' +
  1720. ' <div class="modal-content">\n' +
  1721. ' <div class="modal-header kv-zoom-header">\n' +
  1722. ' <h6 class="modal-title kv-zoom-title" id="' + tModalLabel + '"><span class="kv-zoom-caption"></span> <span class="kv-zoom-size"></span></h6>\n' +
  1723. ' <div class="kv-zoom-actions">{toggleheader}{fullscreen}{borderless}{close}</div>\n' +
  1724. ' </div>\n' +
  1725. ' <div class="floating-buttons"></div>\n' +
  1726. ' <div class="kv-zoom-body file-zoom-content {zoomFrameClass}"></div>\n' + '{prev} {next}\n' +
  1727. ' <div class="kv-zoom-description"></div>\n' +
  1728. ' </div>\n' +
  1729. '</div>\n';
  1730. tDescClose = '<button type="button" class="kv-desc-hide" aria-label="Close">{closeIcon}</button>';
  1731. tProgress = '<div class="progress">\n' +
  1732. ' <div class="{class}" role="progressbar"' +
  1733. ' aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' +
  1734. ' {status}\n' +
  1735. ' </div>\n' +
  1736. '</div>{stats}';
  1737. tStats = '<div class="text-primary file-upload-stats">' +
  1738. '<span class="pending-time">{pendingTime}</span> ' +
  1739. '<span class="upload-speed">{uploadSpeed}</span>' +
  1740. '</div>';
  1741. tSize = ' <samp>({sizeText})</samp>';
  1742. tFooter = '<div class="file-thumbnail-footer">\n' +
  1743. ' <div class="file-footer-caption" title="{caption}">\n' +
  1744. ' <div class="file-caption-info">{caption}</div>\n' +
  1745. ' <div class="file-size-info">{size}</div>\n' +
  1746. ' </div>\n' +
  1747. ' {progress}\n{indicator}\n{actions}\n' +
  1748. '</div>';
  1749. tActions = '<div class="file-actions">\n' +
  1750. ' <div class="file-footer-buttons">\n' +
  1751. ' {download} {upload} {delete} {zoom} {other}' +
  1752. ' </div>\n' +
  1753. '</div>\n' +
  1754. '{drag}\n' +
  1755. '<div class="clearfix"></div>';
  1756. //noinspection HtmlUnknownAttribute
  1757. tActionDelete = '<button type="button" class="kv-file-remove {removeClass}" ' +
  1758. 'title="{removeTitle}" {dataUrl}{dataKey}>{removeIcon}</button>\n';
  1759. tActionUpload = '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">' +
  1760. '{uploadIcon}</button>';
  1761. tActionDownload = '<a class="kv-file-download {downloadClass}" title="{downloadTitle}" ' +
  1762. 'href="{downloadUrl}" download="{caption}" target="_blank">{downloadIcon}</a>';
  1763. tActionZoom = '<button type="button" class="kv-file-zoom {zoomClass}" ' +
  1764. 'title="{zoomTitle}">{zoomIcon}</button>';
  1765. tActionDrag = '<span class="file-drag-handle {dragClass}" title="{dragTitle}">{dragIcon}</span>';
  1766. tIndicator = '<div class="file-upload-indicator" title="{indicatorTitle}">{indicator}</div>';
  1767. tTagBef = '<div class="file-preview-frame {frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  1768. ' data-fileid="{fileid}" data-template="{template}" data-zoom="{zoomData}"';
  1769. tTagBef1 = tTagBef + '><div class="kv-file-content">\n';
  1770. tTagBef2 = tTagBef + ' title="{caption}"><div class="kv-file-content">\n';
  1771. tTagAft = '</div>{footer}\n{zoomCache}</div>\n';
  1772. tGeneric = '{content}\n';
  1773. tStyle = ' {style}';
  1774. tHtml = renderObject('html', 'text/html');
  1775. tText = renderObject('text', 'text/plain;charset=UTF-8');
  1776. tPdf = renderObject('pdf', 'application/pdf');
  1777. tImage = '<img src="{data}" class="file-preview-image kv-preview-data" title="{title}" alt="{alt}"' +
  1778. tStyle + '>\n';
  1779. tOffice = '<iframe class="kv-preview-data file-preview-office" ' +
  1780. 'src="https://view.officeapps.live.com/op/embed.aspx?src={data}"' + tStyle + '></iframe>';
  1781. tGdocs = '<iframe class="kv-preview-data file-preview-gdocs" ' +
  1782. 'src="https://docs.google.com/gview?url={data}&embedded=true"' + tStyle + '></iframe>';
  1783. tVideo = '<video class="kv-preview-data file-preview-video" controls' + tStyle + '>\n' +
  1784. '<source src="{data}" type="{type}">\n' + $h.DEFAULT_PREVIEW + '\n</video>\n';
  1785. tAudio = '<!--suppress ALL --><audio class="kv-preview-data file-preview-audio" controls' + tStyle + '>\n<source src="{data}" ' +
  1786. 'type="{type}">\n' + $h.DEFAULT_PREVIEW + '\n</audio>\n';
  1787. tFlash = '<embed class="kv-preview-data file-preview-flash" src="{data}" type="application/x-shockwave-flash"' + tStyle + '>\n';
  1788. tObject = '<object class="kv-preview-data file-preview-object file-object {typeCss}" ' +
  1789. 'data="{data}" type="{type}"' + tStyle + '>\n' + '<param name="movie" value="{caption}" />\n' +
  1790. $h.OBJECT_PARAMS + ' ' + $h.DEFAULT_PREVIEW + '\n</object>\n';
  1791. tOther = '<div class="kv-preview-data file-preview-other-frame"' + tStyle + '>\n' + $h.DEFAULT_PREVIEW + '\n</div>\n';
  1792. tZoomCache = '<div class="kv-zoom-cache">{zoomContent}</div>';
  1793. vDefaultDim = {width: '100%', height: '100%', 'min-height': '480px'};
  1794. if (self._isPdfRendered()) {
  1795. tPdf = self.pdfRendererTemplate.replace('{renderer}', self._encodeURI(self.pdfRendererUrl));
  1796. }
  1797. self.defaults = {
  1798. layoutTemplates: {
  1799. main1: tMain1,
  1800. main2: tMain2,
  1801. preview: tPreview,
  1802. close: tClose,
  1803. fileIcon: tFileIcon,
  1804. caption: tCaption,
  1805. modalMain: tModalMain,
  1806. modal: tModal,
  1807. descriptionClose: tDescClose,
  1808. progress: tProgress,
  1809. stats: tStats,
  1810. size: tSize,
  1811. footer: tFooter,
  1812. indicator: tIndicator,
  1813. actions: tActions,
  1814. actionDelete: tActionDelete,
  1815. actionUpload: tActionUpload,
  1816. actionDownload: tActionDownload,
  1817. actionZoom: tActionZoom,
  1818. actionDrag: tActionDrag,
  1819. btnDefault: tBtnDefault,
  1820. btnLink: tBtnLink,
  1821. btnBrowse: tBtnBrowse,
  1822. zoomCache: tZoomCache
  1823. },
  1824. previewMarkupTags: {
  1825. tagBefore1: tTagBef1,
  1826. tagBefore2: tTagBef2,
  1827. tagAfter: tTagAft
  1828. },
  1829. previewContentTemplates: {
  1830. generic: tGeneric,
  1831. html: tHtml,
  1832. image: tImage,
  1833. text: tText,
  1834. office: tOffice,
  1835. gdocs: tGdocs,
  1836. video: tVideo,
  1837. audio: tAudio,
  1838. flash: tFlash,
  1839. object: tObject,
  1840. pdf: tPdf,
  1841. other: tOther
  1842. },
  1843. allowedPreviewTypes: ['image', 'html', 'text', 'video', 'audio', 'flash', 'pdf', 'object'],
  1844. previewTemplates: {},
  1845. previewSettings: {
  1846. image: {width: 'auto', height: 'auto', 'max-width': '100%', 'max-height': '100%'},
  1847. html: {width: '213px', height: '160px'},
  1848. text: {width: '213px', height: '160px'},
  1849. office: {width: '213px', height: '160px'},
  1850. gdocs: {width: '213px', height: '160px'},
  1851. video: {width: '213px', height: '160px'},
  1852. audio: {width: '100%', height: '30px'},
  1853. flash: {width: '213px', height: '160px'},
  1854. object: {width: '213px', height: '160px'},
  1855. pdf: {width: '100%', height: '160px', 'position': 'relative'},
  1856. other: {width: '213px', height: '160px'}
  1857. },
  1858. previewSettingsSmall: {
  1859. image: {width: 'auto', height: 'auto', 'max-width': '100%', 'max-height': '100%'},
  1860. html: {width: '100%', height: '160px'},
  1861. text: {width: '100%', height: '160px'},
  1862. office: {width: '100%', height: '160px'},
  1863. gdocs: {width: '100%', height: '160px'},
  1864. video: {width: '100%', height: 'auto'},
  1865. audio: {width: '100%', height: '30px'},
  1866. flash: {width: '100%', height: 'auto'},
  1867. object: {width: '100%', height: 'auto'},
  1868. pdf: {width: '100%', height: '160px'},
  1869. other: {width: '100%', height: '160px'}
  1870. },
  1871. previewZoomSettings: {
  1872. image: {width: 'auto', height: 'auto', 'max-width': '100%', 'max-height': '100%'},
  1873. html: vDefaultDim,
  1874. text: vDefaultDim,
  1875. office: {width: '100%', height: '100%', 'max-width': '100%', 'min-height': '480px'},
  1876. gdocs: {width: '100%', height: '100%', 'max-width': '100%', 'min-height': '480px'},
  1877. video: {width: 'auto', height: '100%', 'max-width': '100%'},
  1878. audio: {width: '100%', height: '30px'},
  1879. flash: {width: 'auto', height: '480px'},
  1880. object: {width: 'auto', height: '100%', 'max-width': '100%', 'min-height': '480px'},
  1881. pdf: vDefaultDim,
  1882. other: {width: 'auto', height: '100%', 'min-height': '480px'}
  1883. },
  1884. mimeTypeAliases: {
  1885. 'video/quicktime': 'video/mp4'
  1886. },
  1887. fileTypeSettings: {
  1888. image: function (vType, vName) {
  1889. return ($h.compare(vType, 'image.*') && !$h.compare(vType, /(tiff?|wmf)$/i) ||
  1890. $h.compare(vName, /\.(gif|png|jpe?g)$/i));
  1891. },
  1892. html: function (vType, vName) {
  1893. return $h.compare(vType, 'text/html') || $h.compare(vName, /\.(htm|html)$/i);
  1894. },
  1895. office: function (vType, vName) {
  1896. return $h.compare(vType, /(word|excel|powerpoint|office)$/i) ||
  1897. $h.compare(vName, /\.(docx?|xlsx?|pptx?|pps|potx?)$/i);
  1898. },
  1899. gdocs: function (vType, vName) {
  1900. return $h.compare(vType, /(word|excel|powerpoint|office|iwork-pages|tiff?)$/i) ||
  1901. $h.compare(vName,
  1902. /\.(docx?|xlsx?|pptx?|pps|potx?|rtf|ods|odt|pages|ai|dxf|ttf|tiff?|wmf|e?ps)$/i);
  1903. },
  1904. text: function (vType, vName) {
  1905. return $h.compare(vType, 'text.*') || $h.compare(vName, /\.(xml|javascript)$/i) ||
  1906. $h.compare(vName, /\.(txt|md|nfo|ini|json|php|js|css)$/i);
  1907. },
  1908. video: function (vType, vName) {
  1909. return $h.compare(vType, 'video.*') && ($h.compare(vType, /(ogg|mp4|mp?g|mov|webm|3gp)$/i) ||
  1910. $h.compare(vName, /\.(og?|mp4|webm|mp?g|mov|3gp)$/i));
  1911. },
  1912. audio: function (vType, vName) {
  1913. return $h.compare(vType, 'audio.*') && ($h.compare(vName, /(ogg|mp3|mp?g|wav)$/i) ||
  1914. $h.compare(vName, /\.(og?|mp3|mp?g|wav)$/i));
  1915. },
  1916. flash: function (vType, vName) {
  1917. return $h.compare(vType, 'application/x-shockwave-flash', true) || $h.compare(vName,
  1918. /\.(swf)$/i);
  1919. },
  1920. pdf: function (vType, vName) {
  1921. return $h.compare(vType, 'application/pdf', true) || $h.compare(vName, /\.(pdf)$/i);
  1922. },
  1923. object: function () {
  1924. return true;
  1925. },
  1926. other: function () {
  1927. return true;
  1928. }
  1929. },
  1930. fileActionSettings: {
  1931. showRemove: true,
  1932. showUpload: true,
  1933. showDownload: true,
  1934. showZoom: true,
  1935. showDrag: true,
  1936. removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
  1937. removeClass: defBtnCss1,
  1938. removeErrorClass: 'btn btn-sm btn-kv btn-danger',
  1939. removeTitle: 'Remove file',
  1940. uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
  1941. uploadClass: defBtnCss1,
  1942. uploadTitle: 'Upload file',
  1943. uploadRetryIcon: '<i class="glyphicon glyphicon-repeat"></i>',
  1944. uploadRetryTitle: 'Retry upload',
  1945. downloadIcon: '<i class="glyphicon glyphicon-download"></i>',
  1946. downloadClass: defBtnCss1,
  1947. downloadTitle: 'Download file',
  1948. zoomIcon: '<i class="glyphicon glyphicon-zoom-in"></i>',
  1949. zoomClass: defBtnCss1,
  1950. zoomTitle: 'View Details',
  1951. dragIcon: '<i class="glyphicon glyphicon-move"></i>',
  1952. dragClass: 'text-primary',
  1953. dragTitle: 'Move / Rearrange',
  1954. dragSettings: {},
  1955. indicatorNew: '<i class="glyphicon glyphicon-plus-sign text-warning"></i>',
  1956. indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign text-success"></i>',
  1957. indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>',
  1958. indicatorLoading: '<i class="glyphicon glyphicon-hourglass text-muted"></i>',
  1959. indicatorPaused: '<i class="glyphicon glyphicon-pause text-primary"></i>',
  1960. indicatorNewTitle: 'Not uploaded yet',
  1961. indicatorSuccessTitle: 'Uploaded',
  1962. indicatorErrorTitle: 'Upload Error',
  1963. indicatorLoadingTitle: 'Uploading &hellip;',
  1964. indicatorPausedTitle: 'Upload Paused'
  1965. }
  1966. };
  1967. $.each(self.defaults, function (key, setting) {
  1968. if (key === 'allowedPreviewTypes') {
  1969. if (self.allowedPreviewTypes === undefined) {
  1970. self.allowedPreviewTypes = setting;
  1971. }
  1972. return;
  1973. }
  1974. self[key] = $.extend(true, {}, setting, self[key]);
  1975. });
  1976. self._initPreviewTemplates();
  1977. },
  1978. _initPreviewTemplates: function () {
  1979. var self = this, tags = self.previewMarkupTags, tagBef, tagAft = tags.tagAfter;
  1980. $.each(self.previewContentTemplates, function (key, value) {
  1981. if ($h.isEmpty(self.previewTemplates[key])) {
  1982. tagBef = tags.tagBefore2;
  1983. if (key === 'generic' || key === 'image') {
  1984. tagBef = tags.tagBefore1;
  1985. }
  1986. if (self._isPdfRendered() && key === 'pdf') {
  1987. tagBef = tagBef.replace('kv-file-content', 'kv-file-content kv-pdf-rendered');
  1988. }
  1989. self.previewTemplates[key] = tagBef + value + tagAft;
  1990. }
  1991. });
  1992. },
  1993. _initPreviewCache: function () {
  1994. var self = this;
  1995. self.previewCache = {
  1996. data: {},
  1997. init: function () {
  1998. var content = self.initialPreview;
  1999. if (content.length > 0 && !$h.isArray(content)) {
  2000. content = content.split(self.initialPreviewDelimiter);
  2001. }
  2002. self.previewCache.data = {
  2003. content: content,
  2004. config: self.initialPreviewConfig,
  2005. tags: self.initialPreviewThumbTags
  2006. };
  2007. },
  2008. count: function (skipNull) {
  2009. if (!self.previewCache.data || !self.previewCache.data.content) {
  2010. return 0;
  2011. }
  2012. if (skipNull) {
  2013. var chk = self.previewCache.data.content.filter(function (n) {
  2014. return n !== null;
  2015. });
  2016. return chk.length;
  2017. }
  2018. return self.previewCache.data.content.length;
  2019. },
  2020. get: function (i, isDisabled) {
  2021. var ind = $h.INIT_FLAG + i, data = self.previewCache.data, config = data.config[i],
  2022. content = data.content[i], out, $tmp, cat, ftr,
  2023. fname, ftype, frameClass, asData = $h.ifSet('previewAsData', config, self.initialPreviewAsData),
  2024. a = config ? {title: config.title || null, alt: config.alt || null} : {title: null, alt: null},
  2025. parseTemplate = function (cat, dat, fname, ftype, ftr, ind, fclass, t) {
  2026. var fc = ' file-preview-initial ' + $h.SORT_CSS + (fclass ? ' ' + fclass : ''),
  2027. id = self.previewInitId + '-' + ind,
  2028. fileId = config && config.fileId || id;
  2029. /** @namespace config.zoomData */
  2030. return self._generatePreviewTemplate(cat, dat, fname, ftype, id, fileId, false, null, fc,
  2031. ftr, ind, t, a, config && config.zoomData || dat);
  2032. };
  2033. if (!content || !content.length) {
  2034. return '';
  2035. }
  2036. isDisabled = isDisabled === undefined ? true : isDisabled;
  2037. cat = $h.ifSet('type', config, self.initialPreviewFileType || 'generic');
  2038. fname = $h.ifSet('filename', config, $h.ifSet('caption', config));
  2039. ftype = $h.ifSet('filetype', config, cat);
  2040. ftr = self.previewCache.footer(i, isDisabled, (config && config.size || null));
  2041. frameClass = $h.ifSet('frameClass', config);
  2042. if (asData) {
  2043. out = parseTemplate(cat, content, fname, ftype, ftr, ind, frameClass);
  2044. } else {
  2045. out = parseTemplate('generic', content, fname, ftype, ftr, ind, frameClass, cat)
  2046. .setTokens({'content': data.content[i]});
  2047. }
  2048. if (data.tags.length && data.tags[i]) {
  2049. out = $h.replaceTags(out, data.tags[i]);
  2050. }
  2051. /** @namespace config.frameAttr */
  2052. if (!$h.isEmpty(config) && !$h.isEmpty(config.frameAttr)) {
  2053. $tmp = $h.createElement(out);
  2054. $tmp.find('.file-preview-initial').attr(config.frameAttr);
  2055. out = $tmp.html();
  2056. $tmp.remove();
  2057. }
  2058. return out;
  2059. },
  2060. clean: function (data) {
  2061. data.content = $h.cleanArray(data.content);
  2062. data.config = $h.cleanArray(data.config);
  2063. data.tags = $h.cleanArray(data.tags);
  2064. self.previewCache.data = data;
  2065. },
  2066. add: function (content, config, tags, append) {
  2067. var data = self.previewCache.data, index;
  2068. if (!content || !content.length) {
  2069. return 0;
  2070. }
  2071. index = content.length - 1;
  2072. if (!$h.isArray(content)) {
  2073. content = content.split(self.initialPreviewDelimiter);
  2074. }
  2075. if (append && data.content) {
  2076. index = data.content.push(content[0]) - 1;
  2077. data.config[index] = config;
  2078. data.tags[index] = tags;
  2079. } else {
  2080. data.content = content;
  2081. data.config = config;
  2082. data.tags = tags;
  2083. }
  2084. self.previewCache.clean(data);
  2085. return index;
  2086. },
  2087. set: function (content, config, tags, append) {
  2088. var data = self.previewCache.data, i, chk;
  2089. if (!content || !content.length) {
  2090. return;
  2091. }
  2092. if (!$h.isArray(content)) {
  2093. content = content.split(self.initialPreviewDelimiter);
  2094. }
  2095. chk = content.filter(function (n) {
  2096. return n !== null;
  2097. });
  2098. if (!chk.length) {
  2099. return;
  2100. }
  2101. if (data.content === undefined) {
  2102. data.content = [];
  2103. }
  2104. if (data.config === undefined) {
  2105. data.config = [];
  2106. }
  2107. if (data.tags === undefined) {
  2108. data.tags = [];
  2109. }
  2110. if (append) {
  2111. for (i = 0; i < content.length; i++) {
  2112. if (content[i]) {
  2113. data.content.push(content[i]);
  2114. }
  2115. }
  2116. for (i = 0; i < config.length; i++) {
  2117. if (config[i]) {
  2118. data.config.push(config[i]);
  2119. }
  2120. }
  2121. for (i = 0; i < tags.length; i++) {
  2122. if (tags[i]) {
  2123. data.tags.push(tags[i]);
  2124. }
  2125. }
  2126. } else {
  2127. data.content = content;
  2128. data.config = config;
  2129. data.tags = tags;
  2130. }
  2131. self.previewCache.clean(data);
  2132. },
  2133. unset: function (index) {
  2134. var chk = self.previewCache.count(), rev = self.reversePreviewOrder;
  2135. if (!chk) {
  2136. return;
  2137. }
  2138. if (chk === 1) {
  2139. self.previewCache.data.content = [];
  2140. self.previewCache.data.config = [];
  2141. self.previewCache.data.tags = [];
  2142. self.initialPreview = [];
  2143. self.initialPreviewConfig = [];
  2144. self.initialPreviewThumbTags = [];
  2145. return;
  2146. }
  2147. self.previewCache.data.content = $h.spliceArray(self.previewCache.data.content, index, rev);
  2148. self.previewCache.data.config = $h.spliceArray(self.previewCache.data.config, index, rev);
  2149. self.previewCache.data.tags = $h.spliceArray(self.previewCache.data.tags, index, rev);
  2150. var data = $.extend(true, {}, self.previewCache.data);
  2151. self.previewCache.clean(data);
  2152. },
  2153. out: function () {
  2154. var html = '', caption, len = self.previewCache.count(), i, content;
  2155. if (len === 0) {
  2156. return {content: '', caption: ''};
  2157. }
  2158. for (i = 0; i < len; i++) {
  2159. content = self.previewCache.get(i);
  2160. html = self.reversePreviewOrder ? (content + html) : (html + content);
  2161. }
  2162. caption = self._getMsgSelected(len);
  2163. return {content: html, caption: caption};
  2164. },
  2165. footer: function (i, isDisabled, size) {
  2166. var data = self.previewCache.data || {};
  2167. if ($h.isEmpty(data.content)) {
  2168. return '';
  2169. }
  2170. if ($h.isEmpty(data.config) || $h.isEmpty(data.config[i])) {
  2171. data.config[i] = {};
  2172. }
  2173. isDisabled = isDisabled === undefined ? true : isDisabled;
  2174. var config = data.config[i], caption = $h.ifSet('caption', config), a,
  2175. width = $h.ifSet('width', config, 'auto'), url = $h.ifSet('url', config, false),
  2176. key = $h.ifSet('key', config, null), fileId = $h.ifSet('fileId', config, null),
  2177. fs = self.fileActionSettings, initPreviewShowDel = self.initialPreviewShowDelete || false,
  2178. downloadInitialUrl = !self.initialPreviewDownloadUrl ? '' :
  2179. self.initialPreviewDownloadUrl + '?key=' + key + (fileId ? '&fileId=' + fileId : ''),
  2180. dUrl = config.downloadUrl || downloadInitialUrl,
  2181. dFil = config.filename || config.caption || '',
  2182. initPreviewShowDwl = !!(dUrl),
  2183. sDel = $h.ifSet('showRemove', config, initPreviewShowDel),
  2184. sDwl = $h.ifSet('showDownload', config, $h.ifSet('showDownload', fs, initPreviewShowDwl)),
  2185. sZm = $h.ifSet('showZoom', config, $h.ifSet('showZoom', fs, true)),
  2186. sDrg = $h.ifSet('showDrag', config, $h.ifSet('showDrag', fs, true)),
  2187. dis = (url === false) && isDisabled;
  2188. sDwl = sDwl && config.downloadUrl !== false && !!dUrl;
  2189. a = self._renderFileActions(config, false, sDwl, sDel, sZm, sDrg, dis, url, key, true, dUrl, dFil);
  2190. return self._getLayoutTemplate('footer').setTokens({
  2191. 'progress': self._renderThumbProgress(),
  2192. 'actions': a,
  2193. 'caption': caption,
  2194. 'size': self._getSize(size),
  2195. 'width': width,
  2196. 'indicator': ''
  2197. });
  2198. }
  2199. };
  2200. self.previewCache.init();
  2201. },
  2202. _isPdfRendered: function () {
  2203. var self = this, useLib = self.usePdfRenderer,
  2204. flag = typeof useLib === 'function' ? useLib() : !!useLib;
  2205. return flag && self.pdfRendererUrl;
  2206. },
  2207. _handler: function ($el, event, callback) {
  2208. var self = this, ns = self.namespace, ev = event.split(' ').join(ns + ' ') + ns;
  2209. if (!$el || !$el.length) {
  2210. return;
  2211. }
  2212. $el.off(ev).on(ev, callback);
  2213. },
  2214. _encodeURI: function (vUrl) {
  2215. var self = this;
  2216. return self.encodeUrl ? encodeURI(vUrl) : vUrl;
  2217. },
  2218. _log: function (msg, tokens) {
  2219. var self = this, id = self.$element.attr('id');
  2220. if (!self.showConsoleLogs) {
  2221. return;
  2222. }
  2223. if (id) {
  2224. msg = '"' + id + '": ' + msg;
  2225. }
  2226. msg = 'bootstrap-fileinput: ' + msg;
  2227. if (typeof tokens === 'object') {
  2228. msg = msg.setTokens(tokens);
  2229. }
  2230. if (window.console && typeof window.console.log !== 'undefined') {
  2231. window.console.log(msg);
  2232. } else {
  2233. window.alert(msg);
  2234. }
  2235. },
  2236. _validate: function () {
  2237. var self = this, status = self.$element.attr('type') === 'file';
  2238. if (!status) {
  2239. self._log($h.logMessages.badInputType);
  2240. }
  2241. return status;
  2242. },
  2243. _errorsExist: function () {
  2244. var self = this, $err, $errList = self.$errorContainer.find('li');
  2245. if ($errList.length) {
  2246. return true;
  2247. }
  2248. $err = $h.createElement(self.$errorContainer.html());
  2249. $err.find('.kv-error-close').remove();
  2250. $err.find('ul').remove();
  2251. return !!$.trim($err.text()).length;
  2252. },
  2253. _errorHandler: function (evt, caption) {
  2254. var self = this, err = evt.target.error, showError = function (msg) {
  2255. self._showError(msg.replace('{name}', caption));
  2256. };
  2257. /** @namespace err.NOT_FOUND_ERR */
  2258. /** @namespace err.SECURITY_ERR */
  2259. /** @namespace err.NOT_READABLE_ERR */
  2260. if (err.code === err.NOT_FOUND_ERR) {
  2261. showError(self.msgFileNotFound);
  2262. } else {
  2263. if (err.code === err.SECURITY_ERR) {
  2264. showError(self.msgFileSecured);
  2265. } else {
  2266. if (err.code === err.NOT_READABLE_ERR) {
  2267. showError(self.msgFileNotReadable);
  2268. } else {
  2269. if (err.code === err.ABORT_ERR) {
  2270. showError(self.msgFilePreviewAborted);
  2271. } else {
  2272. showError(self.msgFilePreviewError);
  2273. }
  2274. }
  2275. }
  2276. }
  2277. },
  2278. _addError: function (msg) {
  2279. var self = this, $error = self.$errorContainer;
  2280. if (msg && $error.length) {
  2281. $h.setHtml($error, self.errorCloseButton + msg);
  2282. self._handler($error.find('.kv-error-close'), 'click', function () {
  2283. setTimeout(function () {
  2284. if (self.showPreview && !self.getFrames().length) {
  2285. self.clear();
  2286. }
  2287. $error.fadeOut('slow');
  2288. }, self.processDelay);
  2289. });
  2290. }
  2291. },
  2292. _setValidationError: function (css) {
  2293. var self = this;
  2294. css = (css ? css + ' ' : '') + 'has-error';
  2295. self.$container.removeClass(css).addClass('has-error');
  2296. $h.addCss(self.$caption, 'is-invalid');
  2297. },
  2298. _resetErrors: function (fade) {
  2299. var self = this, $error = self.$errorContainer, history = self.resumableUploadOptions.retainErrorHistory;
  2300. if (self.isPersistentError || (self.enableResumableUpload && history)) {
  2301. return;
  2302. }
  2303. self.isError = false;
  2304. self.$container.removeClass('has-error');
  2305. self.$caption.removeClass('is-invalid is-valid file-processing');
  2306. $error.html('');
  2307. if (fade) {
  2308. $error.fadeOut('slow');
  2309. } else {
  2310. $error.hide();
  2311. }
  2312. },
  2313. _showFolderError: function (folders) {
  2314. var self = this, $error = self.$errorContainer, msg;
  2315. if (!folders) {
  2316. return;
  2317. }
  2318. if (!self.isAjaxUpload) {
  2319. self._clearFileInput();
  2320. }
  2321. msg = self.msgFoldersNotAllowed.replace('{n}', folders);
  2322. self._addError(msg);
  2323. self._setValidationError();
  2324. $error.fadeIn(self.fadeDelay);
  2325. self._raise('filefoldererror', [folders, msg]);
  2326. },
  2327. _showFileError: function (msg, params, event) {
  2328. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror',
  2329. fId = params && params.fileId || '', e = params && params.id ?
  2330. '<li data-thumb-id="' + params.id + '" data-file-id="' + fId + '">' + msg + '</li>' : '<li>' + msg + '</li>';
  2331. if ($error.find('ul').length === 0) {
  2332. self._addError('<ul>' + e + '</ul>');
  2333. } else {
  2334. $error.find('ul').append(e);
  2335. }
  2336. $error.fadeIn(self.fadeDelay);
  2337. self._raise(ev, [params, msg]);
  2338. self._setValidationError('file-input-new');
  2339. return true;
  2340. },
  2341. _showError: function (msg, params, event) {
  2342. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  2343. params = params || {};
  2344. params.reader = self.reader;
  2345. self._addError(msg);
  2346. $error.fadeIn(self.fadeDelay);
  2347. self._raise(ev, [params, msg]);
  2348. if (!self.isAjaxUpload) {
  2349. self._clearFileInput();
  2350. }
  2351. self._setValidationError('file-input-new');
  2352. self.$btnUpload.attr('disabled', true);
  2353. return true;
  2354. },
  2355. _noFilesError: function (params) {
  2356. var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle,
  2357. msg = self.msgFilesTooLess.replace('{n}', self.minFileCount).replace('{files}', label),
  2358. $error = self.$errorContainer;
  2359. msg = '<li>' + msg + '</li>';
  2360. if ($error.find('ul').length === 0) {
  2361. self._addError('<ul>' + msg + '</ul>');
  2362. } else {
  2363. $error.find('ul').append(msg);
  2364. }
  2365. self.isError = true;
  2366. self._updateFileDetails(0);
  2367. $error.fadeIn(self.fadeDelay);
  2368. self._raise('fileerror', [params, msg]);
  2369. self._clearFileInput();
  2370. self._setValidationError();
  2371. },
  2372. _parseError: function (operation, jqXHR, errorThrown, fileName) {
  2373. /** @namespace jqXHR.responseJSON */
  2374. var self = this, errMsg = $.trim(errorThrown + ''), textPre, errText, text;
  2375. errText = jqXHR.responseJSON && jqXHR.responseJSON.error ? jqXHR.responseJSON.error.toString() : '';
  2376. text = errText ? errText : jqXHR.responseText;
  2377. if (self.cancelling && self.msgUploadAborted) {
  2378. errMsg = self.msgUploadAborted;
  2379. }
  2380. if (self.showAjaxErrorDetails && text) {
  2381. if (errText) {
  2382. errMsg = $.trim(errText + '');
  2383. } else {
  2384. text = $.trim(text.replace(/\n\s*\n/g, '\n'));
  2385. textPre = text.length ? '<pre>' + text + '</pre>' : '';
  2386. errMsg += errMsg ? textPre : text;
  2387. }
  2388. }
  2389. if (!errMsg) {
  2390. errMsg = self.msgAjaxError.replace('{operation}', operation);
  2391. }
  2392. self.cancelling = false;
  2393. return fileName ? '<b>' + fileName + ': </b>' + errMsg : errMsg;
  2394. },
  2395. _parseFileType: function (type, name) {
  2396. var self = this, isValid, vType, cat, i, types = self.allowedPreviewTypes || [];
  2397. if (type === 'application/text-plain') {
  2398. return 'text';
  2399. }
  2400. for (i = 0; i < types.length; i++) {
  2401. cat = types[i];
  2402. isValid = self.fileTypeSettings[cat];
  2403. vType = isValid(type, name) ? cat : '';
  2404. if (!$h.isEmpty(vType)) {
  2405. return vType;
  2406. }
  2407. }
  2408. return 'other';
  2409. },
  2410. _getPreviewIcon: function (fname) {
  2411. var self = this, ext, out = null;
  2412. if (fname && fname.indexOf('.') > -1) {
  2413. ext = fname.split('.').pop();
  2414. if (self.previewFileIconSettings) {
  2415. out = self.previewFileIconSettings[ext] || self.previewFileIconSettings[ext.toLowerCase()] || null;
  2416. }
  2417. if (self.previewFileExtSettings) {
  2418. $.each(self.previewFileExtSettings, function (key, func) {
  2419. if (self.previewFileIconSettings[key] && func(ext)) {
  2420. out = self.previewFileIconSettings[key];
  2421. //noinspection UnnecessaryReturnStatementJS
  2422. return;
  2423. }
  2424. });
  2425. }
  2426. }
  2427. return out || self.previewFileIcon;
  2428. },
  2429. _parseFilePreviewIcon: function (content, fname) {
  2430. var self = this, icn = self._getPreviewIcon(fname), out = content;
  2431. if (out.indexOf('{previewFileIcon}') > -1) {
  2432. out = out.setTokens({'previewFileIconClass': self.previewFileIconClass, 'previewFileIcon': icn});
  2433. }
  2434. return out;
  2435. },
  2436. _raise: function (event, params) {
  2437. var self = this, e = $.Event(event);
  2438. if (params !== undefined) {
  2439. self.$element.trigger(e, params);
  2440. } else {
  2441. self.$element.trigger(e);
  2442. }
  2443. var out = e.result, isAborted = out === false;
  2444. if (e.isDefaultPrevented() || isAborted) {
  2445. return false;
  2446. }
  2447. if (e.type === 'filebatchpreupload' && (out || isAborted)) {
  2448. self.ajaxAborted = out;
  2449. return false;
  2450. }
  2451. switch (event) {
  2452. // ignore these events
  2453. case 'filebatchuploadcomplete':
  2454. case 'filebatchuploadsuccess':
  2455. case 'fileuploaded':
  2456. case 'fileclear':
  2457. case 'filecleared':
  2458. case 'filereset':
  2459. case 'fileerror':
  2460. case 'filefoldererror':
  2461. case 'fileuploaderror':
  2462. case 'filebatchuploaderror':
  2463. case 'filedeleteerror':
  2464. case 'filecustomerror':
  2465. case 'filesuccessremove':
  2466. break;
  2467. // receive data response via `filecustomerror` event`
  2468. default:
  2469. if (!self.ajaxAborted) {
  2470. self.ajaxAborted = out;
  2471. }
  2472. break;
  2473. }
  2474. return true;
  2475. },
  2476. _listenFullScreen: function (isFullScreen) {
  2477. var self = this, $modal = self.$modal, $btnFull, $btnBord;
  2478. if (!$modal || !$modal.length) {
  2479. return;
  2480. }
  2481. $btnFull = $modal && $modal.find('.btn-kv-fullscreen');
  2482. $btnBord = $modal && $modal.find('.btn-kv-borderless');
  2483. if (!$btnFull.length || !$btnBord.length) {
  2484. return;
  2485. }
  2486. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  2487. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  2488. if (isFullScreen) {
  2489. $btnFull.addClass('active').attr('aria-pressed', 'true');
  2490. } else {
  2491. $btnBord.addClass('active').attr('aria-pressed', 'true');
  2492. }
  2493. if ($modal.hasClass('file-zoom-fullscreen')) {
  2494. self._maximizeZoomDialog();
  2495. } else {
  2496. if (isFullScreen) {
  2497. self._maximizeZoomDialog();
  2498. } else {
  2499. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  2500. }
  2501. }
  2502. },
  2503. _listen: function () {
  2504. var self = this, $el = self.$element, $form = self.$form, $cont = self.$container, fullScreenEv;
  2505. self._handler($el, 'click', function (e) {
  2506. self._initFileSelected();
  2507. if ($el.hasClass('file-no-browse')) {
  2508. if ($el.data('zoneClicked')) {
  2509. $el.data('zoneClicked', false);
  2510. } else {
  2511. e.preventDefault();
  2512. }
  2513. }
  2514. });
  2515. self._handler($el, 'change', $.proxy(self._change, self));
  2516. self._handler(self.$caption, 'paste', $.proxy(self.paste, self));
  2517. if (self.showBrowse) {
  2518. self._handler(self.$btnFile, 'click', $.proxy(self._browse, self));
  2519. self._handler(self.$btnFile, 'keypress', function (e) {
  2520. var keycode = e.keyCode || e.which
  2521. if (keycode === 13) {
  2522. $el.trigger('click');
  2523. self._browse(e);
  2524. }
  2525. });
  2526. }
  2527. self._handler($cont.find('.fileinput-remove:not([disabled])'), 'click', $.proxy(self.clear, self));
  2528. self._handler($cont.find('.fileinput-cancel'), 'click', $.proxy(self.cancel, self));
  2529. self._handler($cont.find('.fileinput-pause'), 'click', $.proxy(self.pause, self));
  2530. self._initDragDrop();
  2531. self._handler($form, 'reset', $.proxy(self.clear, self));
  2532. if (!self.isAjaxUpload) {
  2533. self._handler($form, 'submit', $.proxy(self._submitForm, self));
  2534. }
  2535. self._handler(self.$container.find('.fileinput-upload'), 'click', $.proxy(self._uploadClick, self));
  2536. self._handler($(window), 'resize', function () {
  2537. self._listenFullScreen(screen.width === window.innerWidth && screen.height === window.innerHeight);
  2538. });
  2539. fullScreenEv = 'webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange';
  2540. self._handler($(document), fullScreenEv, function () {
  2541. self._listenFullScreen($h.checkFullScreen());
  2542. });
  2543. self.$caption.on('focus', function () {
  2544. self.$captionContainer.focus();
  2545. });
  2546. self._autoFitContent();
  2547. self._initClickable();
  2548. self._refreshPreview();
  2549. },
  2550. _autoFitContent: function () {
  2551. var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
  2552. self = this, config = width < 400 ? (self.previewSettingsSmall || self.defaults.previewSettingsSmall) :
  2553. (self.previewSettings || self.defaults.previewSettings), sel;
  2554. $.each(config, function (cat, settings) {
  2555. sel = '.file-preview-frame .file-preview-' + cat;
  2556. self.$preview.find(sel + '.kv-preview-data,' + sel + ' .kv-preview-data').css(settings);
  2557. });
  2558. },
  2559. _scanDroppedItems: function (item, files, path) {
  2560. path = path || '';
  2561. var self = this, i, dirReader, readDir, errorHandler = function (e) {
  2562. self._log($h.logMessages.badDroppedFiles);
  2563. self._log(e);
  2564. };
  2565. if (item.isFile) {
  2566. item.file(function (file) {
  2567. if (path) {
  2568. file.newPath = path + file.name;
  2569. }
  2570. files.push(file);
  2571. }, errorHandler);
  2572. } else {
  2573. if (item.isDirectory) {
  2574. dirReader = item.createReader();
  2575. readDir = function () {
  2576. dirReader.readEntries(function (entries) {
  2577. if (entries && entries.length > 0) {
  2578. for (i = 0; i < entries.length; i++) {
  2579. self._scanDroppedItems(entries[i], files, path + item.name + '/');
  2580. }
  2581. // recursively call readDir() again, since browser can only handle first 100 entries.
  2582. readDir();
  2583. }
  2584. return null;
  2585. }, errorHandler);
  2586. };
  2587. readDir();
  2588. }
  2589. }
  2590. },
  2591. _initDragDrop: function () {
  2592. var self = this, $zone = self.$dropZone;
  2593. if (self.dropZoneEnabled && self.showPreview) {
  2594. self._handler($zone, 'dragenter dragover', $.proxy(self._zoneDragEnter, self));
  2595. self._handler($zone, 'dragleave', $.proxy(self._zoneDragLeave, self));
  2596. self._handler($zone, 'drop', $.proxy(self._zoneDrop, self));
  2597. self._handler($(document), 'dragenter dragover drop', self._zoneDragDropInit);
  2598. }
  2599. },
  2600. _zoneDragDropInit: function (e) {
  2601. e.stopPropagation();
  2602. e.preventDefault();
  2603. },
  2604. _zoneDragEnter: function (e) {
  2605. var self = this, dt = e.originalEvent.dataTransfer, hasFiles = $.inArray('Files', dt.types) > -1;
  2606. self._zoneDragDropInit(e);
  2607. if (self.isDisabled || !hasFiles) {
  2608. dt.effectAllowed = 'none';
  2609. dt.dropEffect = 'none';
  2610. return;
  2611. }
  2612. dt.dropEffect = 'copy';
  2613. if (self._raise('fileDragEnter', {'sourceEvent': e, 'files': dt.types.Files})) {
  2614. $h.addCss(self.$dropZone, 'file-highlighted');
  2615. }
  2616. },
  2617. _zoneDragLeave: function (e) {
  2618. var self = this;
  2619. self._zoneDragDropInit(e);
  2620. if (self.isDisabled) {
  2621. return;
  2622. }
  2623. if (self._raise('fileDragLeave', {'sourceEvent': e})) {
  2624. self.$dropZone.removeClass('file-highlighted');
  2625. }
  2626. },
  2627. _dropFiles: function (e, files) {
  2628. var self = this, $el = self.$element;
  2629. if (!self.isAjaxUpload) {
  2630. self.changeTriggered = true;
  2631. $el.get(0).files = files;
  2632. setTimeout(function () {
  2633. self.changeTriggered = false;
  2634. $el.trigger('change' + self.namespace);
  2635. }, self.processDelay);
  2636. } else {
  2637. self._change(e, files);
  2638. }
  2639. self.$dropZone.removeClass('file-highlighted');
  2640. },
  2641. _zoneDrop: function (e) {
  2642. /** @namespace e.originalEvent.dataTransfer */
  2643. var self = this, i, $el = self.$element, dt = e.originalEvent.dataTransfer,
  2644. files = dt.files, items = dt.items, folders = $h.getDragDropFolders(items);
  2645. e.preventDefault();
  2646. if (self.isDisabled || $h.isEmpty(files)) {
  2647. return;
  2648. }
  2649. if (!self._raise('fileDragDrop', {'sourceEvent': e, 'files': files})) {
  2650. return;
  2651. }
  2652. if (folders > 0) {
  2653. if (!self.isAjaxUpload) {
  2654. self._showFolderError(folders);
  2655. return;
  2656. }
  2657. files = [];
  2658. for (i = 0; i < items.length; i++) {
  2659. var item = items[i].webkitGetAsEntry();
  2660. if (item) {
  2661. self._scanDroppedItems(item, files);
  2662. }
  2663. }
  2664. setTimeout(function () {
  2665. self._dropFiles(e, files);
  2666. }, 500);
  2667. } else {
  2668. self._dropFiles(e, files);
  2669. }
  2670. },
  2671. _uploadClick: function (e) {
  2672. var self = this, $btn = self.$container.find('.fileinput-upload'), $form,
  2673. isEnabled = !$btn.hasClass('disabled') && $h.isEmpty($btn.attr('disabled'));
  2674. if (e && e.isDefaultPrevented()) {
  2675. return;
  2676. }
  2677. if (!self.isAjaxUpload) {
  2678. if (isEnabled && $btn.attr('type') !== 'submit') {
  2679. $form = $btn.closest('form');
  2680. // downgrade to normal form submit if possible
  2681. if ($form.length) {
  2682. $form.trigger('submit');
  2683. }
  2684. e.preventDefault();
  2685. }
  2686. return;
  2687. }
  2688. e.preventDefault();
  2689. if (isEnabled) {
  2690. self.upload();
  2691. }
  2692. },
  2693. _submitForm: function () {
  2694. var self = this;
  2695. return self._isFileSelectionValid() && !self._abort({});
  2696. },
  2697. _clearPreview: function () {
  2698. var self = this,
  2699. $thumbs = self.showUploadedThumbs ? self.getFrames(':not(.file-preview-success)') : self.getFrames();
  2700. $thumbs.each(function () {
  2701. var $thumb = $(this);
  2702. $thumb.remove();
  2703. });
  2704. if (!self.getFrames().length || !self.showPreview) {
  2705. self._resetUpload();
  2706. }
  2707. self._validateDefaultPreview();
  2708. },
  2709. _initSortable: function () {
  2710. var self = this, $el = self.$preview, settings, selector = '.' + $h.SORT_CSS, $cont, $body = $('body'),
  2711. $html = $('html'), rev = self.reversePreviewOrder, Sortable = window.Sortable, beginGrab, endGrab;
  2712. if (!Sortable || $el.find(selector).length === 0) {
  2713. return;
  2714. }
  2715. $cont = $body.length ? $body : ($html.length ? $html : self.$container);
  2716. beginGrab = function () {
  2717. $cont.addClass('file-grabbing');
  2718. };
  2719. endGrab = function () {
  2720. $cont.removeClass('file-grabbing');
  2721. };
  2722. settings = {
  2723. handle: '.drag-handle-init',
  2724. dataIdAttr: 'data-fileid',
  2725. animation: 600,
  2726. draggable: selector,
  2727. scroll: false,
  2728. forceFallback: true,
  2729. onChoose: beginGrab,
  2730. onStart: beginGrab,
  2731. onUnchoose: endGrab,
  2732. onEnd: endGrab,
  2733. onSort: function (e) {
  2734. var oldIndex = e.oldIndex, newIndex = e.newIndex, i = 0, len = self.initialPreviewConfig.length,
  2735. exceedsLast = len > 0 && newIndex >= len, $item = $(e.item), $first;
  2736. if (exceedsLast) {
  2737. newIndex = len - 1;
  2738. }
  2739. self.initialPreview = $h.moveArray(self.initialPreview, oldIndex, newIndex, rev);
  2740. self.initialPreviewConfig = $h.moveArray(self.initialPreviewConfig, oldIndex, newIndex, rev);
  2741. self.previewCache.init();
  2742. self.getFrames('.file-preview-initial').each(function () {
  2743. $(this).attr('data-fileindex', $h.INIT_FLAG + i);
  2744. i++;
  2745. });
  2746. if (exceedsLast) {
  2747. $first = self.getFrames(':not(.file-preview-initial):first');
  2748. if ($first.length) {
  2749. $item.slideUp(function () {
  2750. $item.insertBefore($first).slideDown();
  2751. });
  2752. }
  2753. }
  2754. self._raise('filesorted', {
  2755. previewId: $item.attr('id'),
  2756. 'oldIndex': oldIndex,
  2757. 'newIndex': newIndex,
  2758. stack: self.initialPreviewConfig
  2759. });
  2760. },
  2761. };
  2762. $.extend(true, settings, self.fileActionSettings.dragSettings);
  2763. if (self.sortable) {
  2764. self.sortable.destroy();
  2765. }
  2766. self.sortable = Sortable.create($el[0], settings);
  2767. },
  2768. _setPreviewContent: function (content) {
  2769. var self = this;
  2770. $h.setHtml(self.$preview, content);
  2771. self._autoFitContent();
  2772. },
  2773. _initPreviewImageOrientations: function () {
  2774. var self = this, i = 0, canOrientImage = self.canOrientImage;
  2775. if (!self.autoOrientImageInitial && !canOrientImage) {
  2776. return;
  2777. }
  2778. self.getFrames('.file-preview-initial').each(function () {
  2779. var $thumb = $(this), $img, $zoomImg, id, config = self.initialPreviewConfig[i];
  2780. /** @namespace config.exif */
  2781. if (config && config.exif && config.exif.Orientation) {
  2782. id = $thumb.attr('id');
  2783. $img = $thumb.find('>.kv-file-content img');
  2784. $zoomImg = self._getZoom(id, ' >.kv-file-content img');
  2785. if (canOrientImage) {
  2786. $img.css('image-orientation', (self.autoOrientImageInitial ? 'from-image' : 'none'));
  2787. } else {
  2788. self.setImageOrientation($img, $zoomImg, config.exif.Orientation, $thumb);
  2789. }
  2790. }
  2791. i++;
  2792. });
  2793. },
  2794. _initPreview: function (isInit) {
  2795. var self = this, cap = self.initialCaption || '', out;
  2796. if (!self.previewCache.count(true)) {
  2797. self._clearPreview();
  2798. if (isInit) {
  2799. self._setCaption(cap);
  2800. } else {
  2801. self._initCaption();
  2802. }
  2803. return;
  2804. }
  2805. out = self.previewCache.out();
  2806. cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
  2807. self._setPreviewContent(out.content);
  2808. self._setInitThumbAttr();
  2809. self._setCaption(cap);
  2810. self._initSortable();
  2811. if (!$h.isEmpty(out.content)) {
  2812. self.$container.removeClass('file-input-new');
  2813. }
  2814. self._initPreviewImageOrientations();
  2815. },
  2816. _getZoomButton: function (type) {
  2817. var self = this, label = self.previewZoomButtonIcons[type], css = self.previewZoomButtonClasses[type],
  2818. title = ' title="' + (self.previewZoomButtonTitles[type] || '') + '" ', tag = $h.isBs(5) ? 'bs-' : '',
  2819. params = title + (type === 'close' ? ' data-' + tag + 'dismiss="modal" aria-hidden="true"' : '');
  2820. if (type === 'fullscreen' || type === 'borderless' || type === 'toggleheader') {
  2821. params += ' data-toggle="button" aria-pressed="false" autocomplete="off"';
  2822. }
  2823. return '<button type="button" class="' + css + ' btn-kv-' + type + '"' + params + '>' + label + '</button>';
  2824. },
  2825. _getModalContent: function () {
  2826. var self = this;
  2827. return self._getLayoutTemplate('modal').setTokens({
  2828. 'rtl': self.rtl ? ' kv-rtl' : '',
  2829. 'zoomFrameClass': self.frameClass,
  2830. 'prev': self._getZoomButton('prev'),
  2831. 'next': self._getZoomButton('next'),
  2832. 'toggleheader': self._getZoomButton('toggleheader'),
  2833. 'fullscreen': self._getZoomButton('fullscreen'),
  2834. 'borderless': self._getZoomButton('borderless'),
  2835. 'close': self._getZoomButton('close')
  2836. });
  2837. },
  2838. _listenModalEvent: function (event) {
  2839. var self = this, $modal = self.$modal, getParams = function (e) {
  2840. return {
  2841. sourceEvent: e,
  2842. previewId: $modal.data('previewId'),
  2843. modal: $modal
  2844. };
  2845. };
  2846. $modal.on(event + '.bs.modal', function (e) {
  2847. if (e.namespace !== 'bs.modal') {
  2848. return;
  2849. }
  2850. var $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless');
  2851. if ($modal.data('fileinputPluginId') === self.$element.attr('id')) {
  2852. self._raise('filezoom' + event, getParams(e));
  2853. }
  2854. if (event === 'shown') {
  2855. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  2856. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  2857. if ($modal.hasClass('file-zoom-fullscreen')) {
  2858. self._maximizeZoomDialog();
  2859. if ($h.checkFullScreen()) {
  2860. $btnFull.addClass('active').attr('aria-pressed', 'true');
  2861. } else {
  2862. $btnBord.addClass('active').attr('aria-pressed', 'true');
  2863. }
  2864. }
  2865. }
  2866. });
  2867. },
  2868. _initZoom: function () {
  2869. var self = this, $dialog, modalMain = self._getLayoutTemplate('modalMain'), modalId = '#' + $h.MODAL_ID;
  2870. modalMain = self._setTabIndex('modal', modalMain);
  2871. if (!self.showPreview) {
  2872. return;
  2873. }
  2874. self.$modal = $(modalId);
  2875. if (!self.$modal || !self.$modal.length) {
  2876. $dialog = $h.createElement($h.cspBuffer.stash(modalMain)).insertAfter(self.$container);
  2877. self.$modal = $(modalId).insertBefore($dialog);
  2878. $h.cspBuffer.apply(self.$modal);
  2879. $dialog.remove();
  2880. }
  2881. $h.initModal(self.$modal);
  2882. self.$modal.html($h.cspBuffer.stash(self._getModalContent()));
  2883. $h.cspBuffer.apply(self.$modal);
  2884. $.each($h.MODAL_EVENTS, function (key, event) {
  2885. self._listenModalEvent(event);
  2886. });
  2887. },
  2888. _initZoomButtons: function () {
  2889. var self = this, previewId = self.$modal.data('previewId') || '', $first, $last,
  2890. thumbs = self.getFrames().toArray(), len = thumbs.length, $prev = self.$modal.find('.btn-kv-prev'),
  2891. $next = self.$modal.find('.btn-kv-next');
  2892. if (thumbs.length < 2) {
  2893. $prev.hide();
  2894. $next.hide();
  2895. return;
  2896. } else {
  2897. $prev.show();
  2898. $next.show();
  2899. }
  2900. if (!len) {
  2901. return;
  2902. }
  2903. $first = $(thumbs[0]);
  2904. $last = $(thumbs[len - 1]);
  2905. $prev.removeAttr('disabled');
  2906. $next.removeAttr('disabled');
  2907. if (self.reversePreviewOrder) {
  2908. [$prev, $next] = [$next, $prev]; // swap
  2909. }
  2910. if ($first.length && $first.attr('id') === previewId) {
  2911. $prev.attr('disabled', true);
  2912. }
  2913. if ($last.length && $last.attr('id') === previewId) {
  2914. $next.attr('disabled', true);
  2915. }
  2916. },
  2917. _maximizeZoomDialog: function () {
  2918. var self = this, $modal = self.$modal, $head = $modal.find('.modal-header:visible'),
  2919. $foot = $modal.find('.modal-footer:visible'), $body = $modal.find('.kv-zoom-body'),
  2920. h = $(window).height(), diff = 0;
  2921. $modal.addClass('file-zoom-fullscreen');
  2922. if ($head && $head.length) {
  2923. h -= $head.outerHeight(true);
  2924. }
  2925. if ($foot && $foot.length) {
  2926. h -= $foot.outerHeight(true);
  2927. }
  2928. if ($body && $body.length) {
  2929. diff = $body.outerHeight(true) - $body.height();
  2930. h -= diff;
  2931. }
  2932. $modal.find('.kv-zoom-body').height(h);
  2933. },
  2934. _resizeZoomDialog: function (fullScreen) {
  2935. var self = this, $modal = self.$modal, $btnFull = $modal.find('.btn-kv-fullscreen'),
  2936. $btnBord = $modal.find('.btn-kv-borderless');
  2937. if ($modal.hasClass('file-zoom-fullscreen')) {
  2938. $h.toggleFullScreen(false);
  2939. if (!fullScreen) {
  2940. if (!$btnFull.hasClass('active')) {
  2941. $modal.removeClass('file-zoom-fullscreen');
  2942. self.$modal.find('.kv-zoom-body').css('height', self.zoomModalHeight);
  2943. } else {
  2944. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  2945. }
  2946. } else {
  2947. if (!$btnFull.hasClass('active')) {
  2948. $modal.removeClass('file-zoom-fullscreen');
  2949. self._resizeZoomDialog(true);
  2950. if ($btnBord.hasClass('active')) {
  2951. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  2952. }
  2953. }
  2954. }
  2955. } else {
  2956. if (!fullScreen) {
  2957. self._maximizeZoomDialog();
  2958. return;
  2959. }
  2960. $h.toggleFullScreen(true);
  2961. }
  2962. $modal.focus();
  2963. },
  2964. _setZoomContent: function ($frame, navigate) {
  2965. var self = this, $content, tmplt, body, title, $body, $dataEl, config, previewId = $frame.attr('id'),
  2966. $zoomPreview = self._getZoom(previewId), $modal = self.$modal, $tmp, desc, $desc,
  2967. $btnFull = $modal.find('.btn-kv-fullscreen'), $btnBord = $modal.find('.btn-kv-borderless'), cap, size,
  2968. $btnTogh = $modal.find('.btn-kv-toggleheader'), dir = navigate === 'prev' ? 'Left' : 'Right',
  2969. slideIn = 'slideIn' + dir, slideOut = 'slideOut' + dir, parsed, zoomData = $frame.data('zoom');
  2970. if (zoomData) {
  2971. zoomData = decodeURIComponent(zoomData);
  2972. parsed = $zoomPreview.html().replace($h.ZOOM_VAR, '').setTokens({zoomData: zoomData});
  2973. $zoomPreview.html(parsed);
  2974. $frame.data('zoom', '');
  2975. $zoomPreview.attr('data-zoom', zoomData);
  2976. }
  2977. tmplt = $zoomPreview.attr('data-template') || 'generic';
  2978. $content = $zoomPreview.find('.kv-file-content');
  2979. body = $content.length ? '<span class="kv-spacer"></span>\n' + $content.html() : '';
  2980. cap = $frame.data('caption') || self.msgZoomModalHeading;
  2981. size = $frame.data('size') || '';
  2982. desc = $frame.data('description') || '';
  2983. $modal.find('.kv-zoom-caption').attr('title', cap).html(cap);
  2984. $modal.find('.kv-zoom-size').html(size);
  2985. $desc = $modal.find('.kv-zoom-description').hide();
  2986. if (desc) {
  2987. if (self.showDescriptionClose) {
  2988. desc = self._getLayoutTemplate('descriptionClose').setTokens({
  2989. closeIcon: self.previewZoomButtonIcons.close
  2990. }) + '</button>' + desc;
  2991. }
  2992. $desc.show().html(desc);
  2993. if (self.showDescriptionClose) {
  2994. self._handler($modal.find('.kv-desc-hide'), 'click', function () {
  2995. $(this).parent().fadeOut('fast', function () {
  2996. $modal.focus();
  2997. });
  2998. });
  2999. }
  3000. }
  3001. $body = $modal.find('.kv-zoom-body');
  3002. $modal.removeClass('kv-single-content');
  3003. if (navigate) {
  3004. $tmp = $body.addClass('file-thumb-loading').clone().insertAfter($body);
  3005. $h.setHtml($body, body).hide();
  3006. $tmp.fadeOut('fast', function () {
  3007. $body.fadeIn('fast', function () {
  3008. $body.removeClass('file-thumb-loading');
  3009. });
  3010. $tmp.remove();
  3011. });
  3012. } else {
  3013. $h.setHtml($body, body);
  3014. }
  3015. config = self.previewZoomSettings[tmplt];
  3016. if (config) {
  3017. $dataEl = $body.find('.kv-preview-data');
  3018. $h.addCss($dataEl, 'file-zoom-detail');
  3019. $.each(config, function (key, value) {
  3020. $dataEl.css(key, value);
  3021. if (($dataEl.attr('width') && key === 'width') || ($dataEl.attr('height') && key === 'height')) {
  3022. $dataEl.removeAttr(key);
  3023. }
  3024. });
  3025. }
  3026. $modal.data('previewId', previewId);
  3027. self._handler($modal.find('.btn-kv-prev'), 'click', function () {
  3028. self._zoomSlideShow('prev', previewId);
  3029. });
  3030. self._handler($modal.find('.btn-kv-next'), 'click', function () {
  3031. self._zoomSlideShow('next', previewId);
  3032. });
  3033. self._handler($btnFull, 'click', function () {
  3034. self._resizeZoomDialog(true);
  3035. });
  3036. self._handler($btnBord, 'click', function () {
  3037. self._resizeZoomDialog(false);
  3038. });
  3039. self._handler($btnTogh, 'click', function () {
  3040. var $header = $modal.find('.modal-header'), $floatBar = $modal.find('.floating-buttons'),
  3041. ht, $actions = $header.find('.kv-zoom-actions'), resize = function (height) {
  3042. var $body = self.$modal.find('.kv-zoom-body'), h = self.zoomModalHeight;
  3043. if ($modal.hasClass('file-zoom-fullscreen')) {
  3044. h = $body.outerHeight(true);
  3045. if (!height) {
  3046. h = h - $header.outerHeight(true);
  3047. }
  3048. }
  3049. $body.css('height', height ? h + height : h);
  3050. };
  3051. if ($header.is(':visible')) {
  3052. ht = $header.outerHeight(true);
  3053. $header.slideUp('slow', function () {
  3054. $actions.find('.btn').appendTo($floatBar);
  3055. resize(ht);
  3056. });
  3057. } else {
  3058. $floatBar.find('.btn').appendTo($actions);
  3059. $header.slideDown('slow', function () {
  3060. resize();
  3061. });
  3062. }
  3063. $modal.focus();
  3064. });
  3065. self._handler($modal, 'keydown', function (e) {
  3066. var key = e.which || e.keyCode, delay = self.processDelay + 1, $prev = $(this).find('.btn-kv-prev'),
  3067. $next = $(this).find('.btn-kv-next'), vId = $(this).data('previewId'), vPrevKey, vNextKey;
  3068. [vPrevKey, vNextKey] = self.rtl ? [39, 37] : [37, 39];
  3069. $.each({prev: [$prev, vPrevKey], next: [$next, vNextKey]}, function (direction, config) {
  3070. var $btn = config[0], vKey = config[1];
  3071. if (key === vKey && $btn.length) {
  3072. $modal.focus();
  3073. if (!$btn.attr('disabled')) {
  3074. $btn.focus();
  3075. self._zoomSlideShow(direction, vId);
  3076. setTimeout(function () {
  3077. if ($btn.attr('disabled')) {
  3078. $modal.focus();
  3079. }
  3080. }, delay);
  3081. }
  3082. }
  3083. });
  3084. });
  3085. },
  3086. _showModal: function ($frame) {
  3087. var self = this, $modal = self.$modal, bs5Modal;
  3088. if (!$frame || !$frame.length) {
  3089. return;
  3090. }
  3091. $h.initModal($modal);
  3092. $h.setHtml($modal, self._getModalContent());
  3093. self._setZoomContent($frame);
  3094. $modal.data({backdrop: false});
  3095. //$modal.data('fileinputPluginId', self.$element.attr('id'));
  3096. $modal.modal('show');
  3097. self._initZoomButtons();
  3098. },
  3099. _zoomPreview: function ($btn) {
  3100. var self = this, $frame;
  3101. if (!$btn.length) {
  3102. throw 'Cannot zoom to detailed preview!';
  3103. }
  3104. $frame = $btn.closest($h.FRAMES);
  3105. self._showModal($frame);
  3106. },
  3107. _zoomSlideShow: function (dir, previewId) {
  3108. var self = this, $btn = self.$modal.find('.kv-zoom-actions .btn-kv-' + dir), $targFrame, i, $thumb,
  3109. thumbsData = self.getFrames().toArray(), thumbs = [], len = thumbsData.length, out;
  3110. if (self.reversePreviewOrder) {
  3111. dir = dir === 'prev' ? 'next' : 'prev';
  3112. }
  3113. if ($btn.attr('disabled')) {
  3114. return;
  3115. }
  3116. for (i = 0; i < len; i++) {
  3117. $thumb = $(thumbsData[i]);
  3118. if ($thumb && $thumb.length && $thumb.find('.kv-file-zoom:visible').length) {
  3119. thumbs.push(thumbsData[i]);
  3120. }
  3121. }
  3122. len = thumbs.length;
  3123. for (i = 0; i < len; i++) {
  3124. if ($(thumbs[i]).attr('id') === previewId) {
  3125. out = dir === 'prev' ? i - 1 : i + 1;
  3126. break;
  3127. }
  3128. }
  3129. if (out < 0 || out >= len || !thumbs[out]) {
  3130. return;
  3131. }
  3132. $targFrame = $(thumbs[out]);
  3133. if ($targFrame.length) {
  3134. self._setZoomContent($targFrame, dir);
  3135. }
  3136. self._initZoomButtons();
  3137. self._raise('filezoom' + dir, {'previewId': previewId, modal: self.$modal});
  3138. },
  3139. _initZoomButton: function () {
  3140. var self = this;
  3141. self.$preview.find('.kv-file-zoom').each(function () {
  3142. var $el = $(this);
  3143. self._handler($el, 'click', function () {
  3144. self._zoomPreview($el);
  3145. });
  3146. });
  3147. },
  3148. _inputFileCount: function () {
  3149. return this.$element[0].files.length;
  3150. },
  3151. _refreshPreview: function () {
  3152. var self = this, files;
  3153. if ((!self._inputFileCount() && !self.isAjaxUpload) || !self.showPreview || !self.isPreviewable) {
  3154. return;
  3155. }
  3156. if (self.isAjaxUpload) {
  3157. if (self.fileManager.count() > 0) {
  3158. files = $.extend(true, {}, self.getFileList());
  3159. self.fileManager.clear();
  3160. self._clearFileInput();
  3161. } else {
  3162. files = self.$element[0].files;
  3163. }
  3164. } else {
  3165. files = self.$element[0].files;
  3166. }
  3167. if (files && files.length) {
  3168. self.readFiles(files);
  3169. self._setFileDropZoneTitle();
  3170. }
  3171. },
  3172. _clearObjects: function ($el) {
  3173. $el.find('video audio').each(function () {
  3174. this.pause();
  3175. $(this).remove();
  3176. });
  3177. $el.find('img object div').each(function () {
  3178. $(this).remove();
  3179. });
  3180. },
  3181. _clearFileInput: function () {
  3182. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  3183. if (!self._inputFileCount()) {
  3184. return;
  3185. }
  3186. $srcFrm = $el.closest('form');
  3187. $tmpFrm = $(document.createElement('form'));
  3188. $tmpEl = $(document.createElement('div'));
  3189. $el.before($tmpEl);
  3190. if ($srcFrm.length) {
  3191. $srcFrm.after($tmpFrm);
  3192. } else {
  3193. $tmpEl.after($tmpFrm);
  3194. }
  3195. $tmpFrm.append($el).trigger('reset');
  3196. $tmpEl.before($el).remove();
  3197. $tmpFrm.remove();
  3198. },
  3199. _resetUpload: function () {
  3200. var self = this;
  3201. self.uploadStartTime = $h.now();
  3202. self.uploadCache = [];
  3203. self.$btnUpload.removeAttr('disabled');
  3204. self._setProgress(0);
  3205. self._hideProgress();
  3206. self._resetErrors(false);
  3207. self._initAjax();
  3208. self.fileManager.clearImages();
  3209. self._resetCanvas();
  3210. if (self.overwriteInitial) {
  3211. self.initialPreview = [];
  3212. self.initialPreviewConfig = [];
  3213. self.initialPreviewThumbTags = [];
  3214. self.previewCache.data = {
  3215. content: [],
  3216. config: [],
  3217. tags: []
  3218. };
  3219. }
  3220. },
  3221. _resetCanvas: function () {
  3222. var self = this;
  3223. if (self.imageCanvas && self.imageCanvasContext) {
  3224. self.imageCanvasContext.clearRect(0, 0, self.imageCanvas.width, self.imageCanvas.height);
  3225. }
  3226. },
  3227. _hasInitialPreview: function () {
  3228. var self = this;
  3229. return !self.overwriteInitial && self.previewCache.count(true);
  3230. },
  3231. _resetPreview: function () {
  3232. var self = this, out, cap, $div, hasSuc = self.showUploadedThumbs, hasErr = !self.removeFromPreviewOnError,
  3233. includeProcessed = (hasSuc || hasErr) && self.isDuplicateError;
  3234. if (self.previewCache.count(true)) {
  3235. out = self.previewCache.out();
  3236. if (includeProcessed) {
  3237. $div = $h.createElement('').insertAfter(self.$container);
  3238. self.getFrames().each(function () {
  3239. var $thumb = $(this);
  3240. if ((hasSuc && $thumb.hasClass('file-preview-success')) ||
  3241. (hasErr && $thumb.hasClass('file-preview-error'))) {
  3242. $div.append($thumb);
  3243. }
  3244. });
  3245. }
  3246. self._setPreviewContent(out.content);
  3247. self._setInitThumbAttr();
  3248. cap = self.initialCaption ? self.initialCaption : out.caption;
  3249. self._setCaption(cap);
  3250. if (includeProcessed) {
  3251. $div.contents().appendTo(self.$preview);
  3252. $div.remove();
  3253. }
  3254. } else {
  3255. self._clearPreview();
  3256. self._initCaption();
  3257. }
  3258. if (self.showPreview) {
  3259. self._initZoom();
  3260. self._initSortable();
  3261. }
  3262. self.isDuplicateError = false;
  3263. },
  3264. _clearDefaultPreview: function () {
  3265. var self = this;
  3266. self.$preview.find('.file-default-preview').remove();
  3267. },
  3268. _validateDefaultPreview: function () {
  3269. var self = this;
  3270. if (!self.showPreview || $h.isEmpty(self.defaultPreviewContent)) {
  3271. return;
  3272. }
  3273. self._setPreviewContent('<div class="file-default-preview">' + self.defaultPreviewContent + '</div>');
  3274. self.$container.removeClass('file-input-new');
  3275. self._initClickable();
  3276. },
  3277. _resetPreviewThumbs: function (isAjax) {
  3278. var self = this, out;
  3279. if (isAjax) {
  3280. self._clearPreview();
  3281. self.clearFileStack();
  3282. return;
  3283. }
  3284. if (self._hasInitialPreview()) {
  3285. out = self.previewCache.out();
  3286. self._setPreviewContent(out.content);
  3287. self._setInitThumbAttr();
  3288. self._setCaption(out.caption);
  3289. self._initPreviewActions();
  3290. } else {
  3291. self._clearPreview();
  3292. }
  3293. },
  3294. _getLayoutTemplate: function (t) {
  3295. var self = this, template = self.layoutTemplates[t];
  3296. if ($h.isEmpty(self.customLayoutTags)) {
  3297. return template;
  3298. }
  3299. return $h.replaceTags(template, self.customLayoutTags);
  3300. },
  3301. _getPreviewTemplate: function (t) {
  3302. var self = this, templates = self.previewTemplates, template = templates[t] || templates.other;
  3303. if ($h.isEmpty(self.customPreviewTags)) {
  3304. return template;
  3305. }
  3306. return $h.replaceTags(template, self.customPreviewTags);
  3307. },
  3308. _getOutData: function (formdata, jqXHR, responseData, filesData) {
  3309. var self = this;
  3310. jqXHR = jqXHR || {};
  3311. responseData = responseData || {};
  3312. filesData = filesData || self.fileManager.list();
  3313. return {
  3314. formdata: formdata,
  3315. files: filesData,
  3316. filenames: self.filenames,
  3317. filescount: self.getFilesCount(),
  3318. extra: self._getExtraData(),
  3319. response: responseData,
  3320. reader: self.reader,
  3321. jqXHR: jqXHR
  3322. };
  3323. },
  3324. _getMsgSelected: function (n, processing) {
  3325. var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural;
  3326. return n > 0 ? self.msgSelected.replace('{n}', n).replace('{files}', strFiles) :
  3327. (processing ? self.msgProcessing : self.msgNoFilesSelected);
  3328. },
  3329. _getFrame: function (id, skipWarning) {
  3330. var self = this, $frame = $h.getFrameElement(self.$preview, id);
  3331. if (self.showPreview && !skipWarning && !$frame.length) {
  3332. self._log($h.logMessages.invalidThumb, {id: id});
  3333. }
  3334. return $frame;
  3335. },
  3336. _getZoom: function (id, selector) {
  3337. var self = this, $frame = $h.getZoomElement(self.$preview, id, selector);
  3338. if (self.showPreview && !$frame.length) {
  3339. self._log($h.logMessages.invalidThumb, {id: id});
  3340. }
  3341. return $frame;
  3342. },
  3343. _getThumbs: function (css) {
  3344. css = css || '';
  3345. return this.getFrames(':not(.file-preview-initial)' + css);
  3346. },
  3347. _getThumbId: function (fileId) {
  3348. var self = this;
  3349. return self.previewInitId + '-' + fileId;
  3350. },
  3351. _getExtraData: function (fileId, index) {
  3352. var self = this, data = self.uploadExtraData;
  3353. if (typeof self.uploadExtraData === 'function') {
  3354. data = self.uploadExtraData(fileId, index);
  3355. }
  3356. return data;
  3357. },
  3358. _initXhr: function (xhrobj, fileId) {
  3359. var self = this, fm = self.fileManager, func = function (event) {
  3360. var pct = 0, total = event.total, loaded = event.loaded || event.position,
  3361. stats = fm.getUploadStats(fileId, loaded, total);
  3362. /** @namespace event.lengthComputable */
  3363. if (event.lengthComputable && !self.enableResumableUpload) {
  3364. pct = $h.round(loaded / total * 100);
  3365. }
  3366. if (fileId) {
  3367. self._setFileUploadStats(fileId, pct, stats);
  3368. } else {
  3369. self._setProgress(pct, null, null, self._getStats(stats));
  3370. }
  3371. self._raise('fileajaxprogress', [stats]);
  3372. };
  3373. if (xhrobj.upload) {
  3374. if (self.progressDelay) {
  3375. func = $h.debounce(func, self.progressDelay);
  3376. }
  3377. xhrobj.upload.addEventListener('progress', func, false);
  3378. }
  3379. return xhrobj;
  3380. },
  3381. _initAjaxSettings: function () {
  3382. var self = this;
  3383. self._ajaxSettings = $.extend(true, {}, self.ajaxSettings);
  3384. self._ajaxDeleteSettings = $.extend(true, {}, self.ajaxDeleteSettings);
  3385. },
  3386. _mergeAjaxCallback: function (funcName, srcFunc, type) {
  3387. var self = this, settings = self._ajaxSettings, flag = self.mergeAjaxCallbacks, targFunc;
  3388. if (type === 'delete') {
  3389. settings = self._ajaxDeleteSettings;
  3390. flag = self.mergeAjaxDeleteCallbacks;
  3391. }
  3392. targFunc = settings[funcName];
  3393. if (flag && typeof targFunc === 'function') {
  3394. if (flag === 'before') {
  3395. settings[funcName] = function () {
  3396. targFunc.apply(this, arguments);
  3397. srcFunc.apply(this, arguments);
  3398. };
  3399. } else {
  3400. settings[funcName] = function () {
  3401. srcFunc.apply(this, arguments);
  3402. targFunc.apply(this, arguments);
  3403. };
  3404. }
  3405. } else {
  3406. settings[funcName] = srcFunc;
  3407. }
  3408. },
  3409. _ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, formdata, fileId, index, vUrl) {
  3410. var self = this, settings, defaults, data, ajaxTask;
  3411. if (!self._raise('filepreajax', [formdata, fileId, index])) {
  3412. return;
  3413. }
  3414. formdata.append('initialPreview', JSON.stringify(self.initialPreview));
  3415. formdata.append('initialPreviewConfig', JSON.stringify(self.initialPreviewConfig));
  3416. formdata.append('initialPreviewThumbTags', JSON.stringify(self.initialPreviewThumbTags));
  3417. self._initAjaxSettings();
  3418. self._mergeAjaxCallback('beforeSend', fnBefore);
  3419. self._mergeAjaxCallback('success', fnSuccess);
  3420. self._mergeAjaxCallback('complete', fnComplete);
  3421. self._mergeAjaxCallback('error', fnError);
  3422. vUrl = vUrl || self.uploadUrlThumb || self.uploadUrl;
  3423. if (typeof vUrl === 'function') {
  3424. vUrl = vUrl();
  3425. }
  3426. data = self._getExtraData(fileId, index) || {};
  3427. if (typeof data === 'object') {
  3428. $.each(data, function (key, value) {
  3429. formdata.append(key, value);
  3430. });
  3431. }
  3432. defaults = {
  3433. xhr: function () {
  3434. var xhrobj = $.ajaxSettings.xhr();
  3435. return self._initXhr(xhrobj, fileId);
  3436. },
  3437. url: self._encodeURI(vUrl),
  3438. type: 'POST',
  3439. dataType: 'json',
  3440. data: formdata,
  3441. cache: false,
  3442. processData: false,
  3443. contentType: false
  3444. };
  3445. settings = $.extend(true, {}, defaults, self._ajaxSettings);
  3446. ajaxTask = self.taskManager.addTask(fileId + '-' + index, function () {
  3447. var self = this.self, config, xhr;
  3448. config = self.ajaxQueue.shift();
  3449. xhr = $.ajax(config);
  3450. self.ajaxRequests.push(xhr);
  3451. });
  3452. self.ajaxQueue.push(settings);
  3453. ajaxTask.runWithContext({self: self});
  3454. },
  3455. _mergeArray: function (prop, content) {
  3456. var self = this, arr1 = $h.cleanArray(self[prop]), arr2 = $h.cleanArray(content);
  3457. self[prop] = arr1.concat(arr2);
  3458. },
  3459. _initUploadSuccess: function (out, $thumb, allFiles) {
  3460. var self = this, append, data, index, $div, content, config, tags, id, i;
  3461. if (!self.showPreview || typeof out !== 'object' || $.isEmptyObject(out)) {
  3462. self._resetCaption();
  3463. return;
  3464. }
  3465. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  3466. self.hasInitData = true;
  3467. content = out.initialPreview || [];
  3468. config = out.initialPreviewConfig || [];
  3469. tags = out.initialPreviewThumbTags || [];
  3470. append = out.append === undefined || out.append;
  3471. if (content.length > 0 && !$h.isArray(content)) {
  3472. content = content.split(self.initialPreviewDelimiter);
  3473. }
  3474. if (content.length) {
  3475. self._mergeArray('initialPreview', content);
  3476. self._mergeArray('initialPreviewConfig', config);
  3477. self._mergeArray('initialPreviewThumbTags', tags);
  3478. }
  3479. if ($thumb !== undefined) {
  3480. if (!allFiles) {
  3481. index = self.previewCache.add(content[0], config[0], tags[0], append);
  3482. data = self.previewCache.get(index, false);
  3483. $div = $h.createElement(data).hide().appendTo($thumb);
  3484. $thumb.fadeOut('slow', function () {
  3485. var $newThumb = $div.find('> .file-preview-frame');
  3486. if ($newThumb && $newThumb.length) {
  3487. $newThumb.insertBefore($thumb).fadeIn('slow').css('display:inline-block');
  3488. }
  3489. self._initPreviewActions();
  3490. self._clearFileInput();
  3491. $thumb.remove();
  3492. $div.remove();
  3493. self._initSortable();
  3494. });
  3495. } else {
  3496. id = $thumb.attr('id');
  3497. i = self._getUploadCacheIndex(id);
  3498. if (i !== null) {
  3499. self.uploadCache[i] = {
  3500. id: id,
  3501. content: content[0],
  3502. config: config[0] || [],
  3503. tags: tags[0] || [],
  3504. append: append
  3505. };
  3506. }
  3507. }
  3508. } else {
  3509. self.previewCache.set(content, config, tags, append);
  3510. self._initPreview();
  3511. self._initPreviewActions();
  3512. }
  3513. }
  3514. self._resetCaption();
  3515. },
  3516. _getUploadCacheIndex: function (id) {
  3517. var self = this, i, len = self.uploadCache.length, config;
  3518. for (i = 0; i < len; i++) {
  3519. config = self.uploadCache[i];
  3520. if (config.id === id) {
  3521. return i;
  3522. }
  3523. }
  3524. return null;
  3525. },
  3526. _initSuccessThumbs: function () {
  3527. var self = this;
  3528. if (!self.showPreview) {
  3529. return;
  3530. }
  3531. setTimeout(function () {
  3532. self._getThumbs($h.FRAMES + '.file-preview-success').each(function () {
  3533. var $thumb = $(this), $remove = $thumb.find('.kv-file-remove');
  3534. $remove.removeAttr('disabled');
  3535. self._handler($remove, 'click', function () {
  3536. var id = $thumb.attr('id'),
  3537. out = self._raise('filesuccessremove', [id, $thumb.attr('data-fileindex')]);
  3538. $h.cleanMemory($thumb);
  3539. if (out === false) {
  3540. return;
  3541. }
  3542. self.$caption.attr('title', '');
  3543. $thumb.fadeOut('slow', function () {
  3544. var fm = self.fileManager;
  3545. $thumb.remove();
  3546. if (!self.getFrames().length) {
  3547. self.reset();
  3548. }
  3549. });
  3550. });
  3551. });
  3552. }, self.processDelay);
  3553. },
  3554. _updateInitialPreview: function () {
  3555. var self = this, u = self.uploadCache;
  3556. if (self.showPreview) {
  3557. $.each(u, function (key, setting) {
  3558. self.previewCache.add(setting.content, setting.config, setting.tags, setting.append);
  3559. });
  3560. if (self.hasInitData) {
  3561. self._initPreview();
  3562. self._initPreviewActions();
  3563. }
  3564. }
  3565. },
  3566. _getThumbFileId: function ($thumb) {
  3567. var self = this;
  3568. if (self.showPreview && $thumb !== undefined) {
  3569. return $thumb.attr('data-fileid');
  3570. }
  3571. return null;
  3572. },
  3573. _getThumbFile: function ($thumb) {
  3574. var self = this, id = self._getThumbFileId($thumb);
  3575. return id ? self.fileManager.getFile(id) : null;
  3576. },
  3577. _uploadSingle: function (i, id, isBatch) {
  3578. var self = this, fm = self.fileManager, count = fm.count(), formdata = new FormData(), outData,
  3579. previewId = self._getThumbId(id), $thumb, chkComplete, $btnUpload, $btnDelete,
  3580. hasPostData = count > 0 || !$.isEmptyObject(self.uploadExtraData), uploadFailed, $prog, fnBefore,
  3581. errMsg, fnSuccess, fnComplete, fnError, updateUploadLog, op = self.ajaxOperations.uploadThumb,
  3582. fileObj = fm.getFile(id), params = {id: previewId, index: i, fileId: id},
  3583. fileName = self.fileManager.getFileName(id, true);
  3584. if (self.enableResumableUpload) { // not enabled for resumable uploads
  3585. return;
  3586. }
  3587. if (self.showPreview) {
  3588. $thumb = fm.getThumb(id);
  3589. $prog = $thumb.find('.file-thumb-progress');
  3590. $btnUpload = $thumb.find('.kv-file-upload');
  3591. $btnDelete = $thumb.find('.kv-file-remove');
  3592. $prog.show();
  3593. }
  3594. if (count === 0 || !hasPostData || (self.showPreview && $btnUpload && $btnUpload.hasClass('disabled')) ||
  3595. self._abort(params)) {
  3596. return;
  3597. }
  3598. updateUploadLog = function () {
  3599. if (!uploadFailed) {
  3600. fm.removeFile(id);
  3601. } else {
  3602. fm.errors.push(id);
  3603. }
  3604. fm.setProcessed(id);
  3605. if (fm.isProcessed()) {
  3606. self.fileBatchCompleted = true;
  3607. chkComplete();
  3608. }
  3609. };
  3610. chkComplete = function () {
  3611. var $initThumbs;
  3612. if (!self.fileBatchCompleted) {
  3613. return;
  3614. }
  3615. setTimeout(function () {
  3616. var triggerReset = fm.count() === 0, errCount = fm.errors.length;
  3617. self._updateInitialPreview();
  3618. self.unlock(triggerReset);
  3619. if (triggerReset) {
  3620. self._clearFileInput();
  3621. }
  3622. $initThumbs = self.$preview.find('.file-preview-initial');
  3623. if (self.uploadAsync && $initThumbs.length) {
  3624. $h.addCss($initThumbs, $h.SORT_CSS);
  3625. self._initSortable();
  3626. }
  3627. self._raise('filebatchuploadcomplete', [fm.stack, self._getExtraData()]);
  3628. if (!self.retryErrorUploads || errCount === 0) {
  3629. fm.clear();
  3630. }
  3631. self._setProgress(101);
  3632. self.ajaxAborted = false;
  3633. }, self.processDelay);
  3634. };
  3635. fnBefore = function (jqXHR) {
  3636. outData = self._getOutData(formdata, jqXHR);
  3637. fm.initStats(id);
  3638. self.fileBatchCompleted = false;
  3639. if (!isBatch) {
  3640. self.ajaxAborted = false;
  3641. }
  3642. if (self.showPreview) {
  3643. if (!$thumb.hasClass('file-preview-success')) {
  3644. self._setThumbStatus($thumb, 'Loading');
  3645. $h.addCss($thumb, 'file-uploading');
  3646. }
  3647. $btnUpload.attr('disabled', true);
  3648. $btnDelete.attr('disabled', true);
  3649. }
  3650. if (!isBatch) {
  3651. self.lock();
  3652. }
  3653. if (fm.errors.indexOf(id) !== -1) {
  3654. delete fm.errors[id];
  3655. }
  3656. self._raise('filepreupload', [outData, previewId, i, self._getThumbFileId($thumb)]);
  3657. $.extend(true, params, outData);
  3658. if (self._abort(params)) {
  3659. jqXHR.abort();
  3660. if (!isBatch) {
  3661. self._setThumbStatus($thumb, 'New');
  3662. $thumb.removeClass('file-uploading');
  3663. $btnUpload.removeAttr('disabled');
  3664. $btnDelete.removeAttr('disabled');
  3665. }
  3666. self._setProgressCancelled();
  3667. }
  3668. };
  3669. fnSuccess = function (data, textStatus, jqXHR) {
  3670. var pid = self.showPreview && $thumb.attr('id') ? $thumb.attr('id') : previewId;
  3671. outData = self._getOutData(formdata, jqXHR, data);
  3672. $.extend(true, params, outData);
  3673. setTimeout(function () {
  3674. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  3675. if (self.showPreview) {
  3676. self._setThumbStatus($thumb, 'Success');
  3677. $btnUpload.hide();
  3678. self._initUploadSuccess(data, $thumb, isBatch);
  3679. self._setProgress(101, $prog);
  3680. }
  3681. self._raise('fileuploaded', [outData, pid, i, self._getThumbFileId($thumb)]);
  3682. if (!isBatch) {
  3683. self.fileManager.remove($thumb);
  3684. } else {
  3685. updateUploadLog();
  3686. }
  3687. } else {
  3688. uploadFailed = true;
  3689. errMsg = self._parseError(op, jqXHR, self.msgUploadError, self.fileManager.getFileName(id));
  3690. self._showFileError(errMsg, params);
  3691. self._setPreviewError($thumb, true);
  3692. if (!self.retryErrorUploads) {
  3693. $btnUpload.hide();
  3694. }
  3695. if (isBatch) {
  3696. updateUploadLog();
  3697. }
  3698. self._setProgress(101, self._getFrame(pid).find('.file-thumb-progress'),
  3699. self.msgUploadError);
  3700. }
  3701. }, self.processDelay);
  3702. };
  3703. fnComplete = function () {
  3704. if (self.showPreview) {
  3705. $btnUpload.removeAttr('disabled');
  3706. $btnDelete.removeAttr('disabled');
  3707. $thumb.removeClass('file-uploading');
  3708. }
  3709. if (!isBatch) {
  3710. self.unlock(false);
  3711. self._clearFileInput();
  3712. } else {
  3713. chkComplete();
  3714. }
  3715. self._initSuccessThumbs();
  3716. };
  3717. fnError = function (jqXHR, textStatus, errorThrown) {
  3718. errMsg = self._parseError(op, jqXHR, errorThrown, self.fileManager.getFileName(id));
  3719. uploadFailed = true;
  3720. setTimeout(function () {
  3721. var $prog;
  3722. if (isBatch) {
  3723. updateUploadLog();
  3724. }
  3725. self.fileManager.setProgress(id, 100);
  3726. self._setPreviewError($thumb, true);
  3727. if (!self.retryErrorUploads) {
  3728. $btnUpload.hide();
  3729. }
  3730. $.extend(true, params, self._getOutData(formdata, jqXHR));
  3731. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  3732. $prog = self.showPreview && $thumb ? $thumb.find('.file-thumb-progress') : '';
  3733. self._setProgress(101, $prog, self.msgUploadError);
  3734. self._showFileError(errMsg, params);
  3735. }, self.processDelay);
  3736. };
  3737. self._setFileData(formdata, fileObj.file, fileName, id);
  3738. self._setUploadData(formdata, {fileId: id});
  3739. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, formdata, id, i);
  3740. },
  3741. _setFileData: function (formdata, file, fileName, fileId) {
  3742. var self = this, preProcess = self.preProcessUpload;
  3743. if (preProcess && typeof preProcess === 'function') {
  3744. formdata.append(self.uploadFileAttr, preProcess(fileId, file));
  3745. } else {
  3746. formdata.append(self.uploadFileAttr, file, fileName);
  3747. }
  3748. },
  3749. _checkBatchPreupload: function (outData, jqXHR) {
  3750. var self = this, out = self._raise('filebatchpreupload', [outData]);
  3751. if (out) {
  3752. return true;
  3753. }
  3754. self._abort(outData);
  3755. if (jqXHR) {
  3756. jqXHR.abort();
  3757. }
  3758. self._getThumbs().each(function () {
  3759. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  3760. $btnDelete = $thumb.find('.kv-file-remove');
  3761. if ($thumb.hasClass('file-preview-loading')) {
  3762. self._setThumbStatus($thumb, 'New');
  3763. $thumb.removeClass('file-uploading');
  3764. }
  3765. $btnUpload.removeAttr('disabled');
  3766. $btnDelete.removeAttr('disabled');
  3767. });
  3768. self._setProgressCancelled();
  3769. return false;
  3770. },
  3771. _uploadBatch: function () {
  3772. var self = this, fm = self.fileManager, total = fm.total(), params = {}, fnBefore, fnSuccess, fnError,
  3773. fnComplete, hasPostData = total > 0 || !$.isEmptyObject(self.uploadExtraData), errMsg,
  3774. setAllUploaded, formdata = new FormData(), op = self.ajaxOperations.uploadBatch;
  3775. if (total === 0 || !hasPostData || self._abort(params)) {
  3776. return;
  3777. }
  3778. setAllUploaded = function () {
  3779. self.fileManager.clear();
  3780. self._clearFileInput();
  3781. };
  3782. fnBefore = function (jqXHR) {
  3783. self.lock();
  3784. fm.initStats();
  3785. var outData = self._getOutData(formdata, jqXHR);
  3786. self.ajaxAborted = false;
  3787. if (self.showPreview) {
  3788. self._getThumbs().each(function () {
  3789. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  3790. $btnDelete = $thumb.find('.kv-file-remove');
  3791. if (!$thumb.hasClass('file-preview-success')) {
  3792. self._setThumbStatus($thumb, 'Loading');
  3793. $h.addCss($thumb, 'file-uploading');
  3794. }
  3795. $btnUpload.attr('disabled', true);
  3796. $btnDelete.attr('disabled', true);
  3797. });
  3798. }
  3799. self._checkBatchPreupload(outData, jqXHR);
  3800. };
  3801. fnSuccess = function (data, textStatus, jqXHR) {
  3802. /** @namespace data.errorkeys */
  3803. var outData = self._getOutData(formdata, jqXHR, data), key = 0,
  3804. $thumbs = self._getThumbs(':not(.file-preview-success)'),
  3805. keys = $h.isEmpty(data) || $h.isEmpty(data.errorkeys) ? [] : data.errorkeys;
  3806. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  3807. self._raise('filebatchuploadsuccess', [outData]);
  3808. setAllUploaded();
  3809. if (self.showPreview) {
  3810. $thumbs.each(function () {
  3811. var $thumb = $(this);
  3812. self._setThumbStatus($thumb, 'Success');
  3813. $thumb.removeClass('file-uploading');
  3814. $thumb.find('.kv-file-upload').hide().removeAttr('disabled');
  3815. });
  3816. self._initUploadSuccess(data);
  3817. } else {
  3818. self.reset();
  3819. }
  3820. self._setProgress(101);
  3821. } else {
  3822. if (self.showPreview) {
  3823. $thumbs.each(function () {
  3824. var $thumb = $(this);
  3825. $thumb.removeClass('file-uploading');
  3826. $thumb.find('.kv-file-upload').removeAttr('disabled');
  3827. $thumb.find('.kv-file-remove').removeAttr('disabled');
  3828. if (keys.length === 0 || $.inArray(key, keys) !== -1) {
  3829. self._setPreviewError($thumb, true);
  3830. if (!self.retryErrorUploads) {
  3831. $thumb.find('.kv-file-upload').hide();
  3832. self.fileManager.remove($thumb);
  3833. }
  3834. } else {
  3835. $thumb.find('.kv-file-upload').hide();
  3836. self._setThumbStatus($thumb, 'Success');
  3837. self.fileManager.remove($thumb);
  3838. }
  3839. if (!$thumb.hasClass('file-preview-error') || self.retryErrorUploads) {
  3840. key++;
  3841. }
  3842. });
  3843. self._initUploadSuccess(data);
  3844. }
  3845. errMsg = self._parseError(op, jqXHR, self.msgUploadError);
  3846. self._showFileError(errMsg, outData, 'filebatchuploaderror');
  3847. self._setProgress(101, self.$progress, self.msgUploadError);
  3848. }
  3849. };
  3850. fnComplete = function () {
  3851. self.unlock();
  3852. self._initSuccessThumbs();
  3853. self._clearFileInput();
  3854. self._raise('filebatchuploadcomplete', [self.fileManager.stack, self._getExtraData()]);
  3855. };
  3856. fnError = function (jqXHR, textStatus, errorThrown) {
  3857. var outData = self._getOutData(formdata, jqXHR);
  3858. errMsg = self._parseError(op, jqXHR, errorThrown);
  3859. self._showFileError(errMsg, outData, 'filebatchuploaderror');
  3860. self.uploadFileCount = total - 1;
  3861. if (!self.showPreview) {
  3862. return;
  3863. }
  3864. self._getThumbs().each(function () {
  3865. var $thumb = $(this);
  3866. $thumb.removeClass('file-uploading');
  3867. if (self._getThumbFile($thumb)) {
  3868. self._setPreviewError($thumb);
  3869. }
  3870. });
  3871. self._getThumbs().removeClass('file-uploading');
  3872. self._getThumbs(' .kv-file-upload').removeAttr('disabled');
  3873. self._getThumbs(' .kv-file-delete').removeAttr('disabled');
  3874. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  3875. };
  3876. var ctr = 0;
  3877. $.each(self.fileManager.stack, function (key, data) {
  3878. if (!$h.isEmpty(data.file)) {
  3879. self._setFileData(formdata, data.file, (data.nameFmt || ('untitled_' + ctr)), key);
  3880. }
  3881. ctr++;
  3882. });
  3883. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, formdata);
  3884. },
  3885. _uploadExtraOnly: function () {
  3886. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError, formdata = new FormData(), errMsg,
  3887. op = self.ajaxOperations.uploadExtra;
  3888. fnBefore = function (jqXHR) {
  3889. self.lock();
  3890. var outData = self._getOutData(formdata, jqXHR);
  3891. self._setProgress(50);
  3892. params.data = outData;
  3893. params.xhr = jqXHR;
  3894. self._checkBatchPreupload(outData, jqXHR);
  3895. };
  3896. fnSuccess = function (data, textStatus, jqXHR) {
  3897. var outData = self._getOutData(formdata, jqXHR, data);
  3898. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  3899. self._raise('filebatchuploadsuccess', [outData]);
  3900. self._clearFileInput();
  3901. self._initUploadSuccess(data);
  3902. self._setProgress(101);
  3903. } else {
  3904. errMsg = self._parseError(op, jqXHR, self.msgUploadError);
  3905. self._showFileError(errMsg, outData, 'filebatchuploaderror');
  3906. }
  3907. };
  3908. fnComplete = function () {
  3909. self.unlock();
  3910. self._clearFileInput();
  3911. self._raise('filebatchuploadcomplete', [self.fileManager.stack, self._getExtraData()]);
  3912. };
  3913. fnError = function (jqXHR, textStatus, errorThrown) {
  3914. var outData = self._getOutData(formdata, jqXHR);
  3915. errMsg = self._parseError(op, jqXHR, errorThrown);
  3916. params.data = outData;
  3917. self._showFileError(errMsg, outData, 'filebatchuploaderror');
  3918. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  3919. };
  3920. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, formdata);
  3921. },
  3922. _deleteFileIndex: function ($frame) {
  3923. var self = this, ind = $frame.attr('data-fileindex'), rev = self.reversePreviewOrder;
  3924. if (ind.substring(0, 5) === $h.INIT_FLAG) {
  3925. ind = parseInt(ind.replace($h.INIT_FLAG, ''));
  3926. self.initialPreview = $h.spliceArray(self.initialPreview, ind, rev);
  3927. self.initialPreviewConfig = $h.spliceArray(self.initialPreviewConfig, ind, rev);
  3928. self.initialPreviewThumbTags = $h.spliceArray(self.initialPreviewThumbTags, ind, rev);
  3929. self.getFrames().each(function () {
  3930. var $nFrame = $(this), nInd = $nFrame.attr('data-fileindex');
  3931. if (nInd.substring(0, 5) === $h.INIT_FLAG) {
  3932. nInd = parseInt(nInd.replace($h.INIT_FLAG, ''));
  3933. if (nInd > ind) {
  3934. nInd--;
  3935. $nFrame.attr('data-fileindex', $h.INIT_FLAG + nInd);
  3936. }
  3937. }
  3938. });
  3939. }
  3940. },
  3941. _resetCaption: function () {
  3942. var self = this;
  3943. setTimeout(function () {
  3944. var cap = '', n, chk = self.previewCache.count(true), len = self.fileManager.count(), file,
  3945. incomplete = ':not(.file-preview-success):not(.file-preview-error)', cfg,
  3946. hasThumb = self.showPreview && self.getFrames(incomplete).length;
  3947. if (len === 0 && chk === 0 && !hasThumb) {
  3948. self.reset();
  3949. } else {
  3950. n = chk + len;
  3951. if (n > 1) {
  3952. cap = self._getMsgSelected(n);
  3953. } else {
  3954. if (len === 0) {
  3955. cfg = self.initialPreviewConfig[0];
  3956. cap = '';
  3957. if (cfg) {
  3958. cap = cfg.caption || cfg.filename || ''
  3959. }
  3960. if (!cap) {
  3961. cap = self._getMsgSelected(n);
  3962. }
  3963. } else {
  3964. file = self.fileManager.getFirstFile();
  3965. cap = file ? file.nameFmt : '_';
  3966. }
  3967. }
  3968. self._setCaption(cap);
  3969. }
  3970. }, self.processDelay);
  3971. },
  3972. _initFileActions: function () {
  3973. var self = this;
  3974. if (!self.showPreview) {
  3975. return;
  3976. }
  3977. self._initZoomButton();
  3978. self.getFrames(' .kv-file-remove').each(function () {
  3979. var $el = $(this), $frame = $el.closest($h.FRAMES), hasError, id = $frame.attr('id'),
  3980. ind = $frame.attr('data-fileindex'), status, fm = self.fileManager;
  3981. self._handler($el, 'click', function () {
  3982. status = self._raise('filepreremove', [id, ind]);
  3983. if (status === false || !self._validateMinCount()) {
  3984. return false;
  3985. }
  3986. hasError = $frame.hasClass('file-preview-error');
  3987. $h.cleanMemory($frame);
  3988. $frame.fadeOut('slow', function () {
  3989. self.fileManager.remove($frame);
  3990. self._clearObjects($frame);
  3991. $frame.remove();
  3992. if (id && hasError) {
  3993. self.$errorContainer.find('li[data-thumb-id="' + id + '"]').fadeOut('fast', function () {
  3994. $(this).remove();
  3995. if (!self._errorsExist()) {
  3996. self._resetErrors();
  3997. }
  3998. });
  3999. }
  4000. self._clearFileInput();
  4001. self._resetCaption();
  4002. self._raise('fileremoved', [id, ind]);
  4003. });
  4004. });
  4005. });
  4006. self.getFrames(' .kv-file-upload').each(function () {
  4007. var $el = $(this);
  4008. self._handler($el, 'click', function () {
  4009. var $frame = $el.closest($h.FRAMES), fileId = self._getThumbFileId($frame);
  4010. self._hideProgress();
  4011. if ($frame.hasClass('file-preview-error') && !self.retryErrorUploads) {
  4012. return;
  4013. }
  4014. self._uploadSingle(self.fileManager.getIndex(fileId), fileId, false);
  4015. });
  4016. });
  4017. },
  4018. _initPreviewActions: function () {
  4019. var self = this, $preview = self.$preview, deleteExtraData = self.deleteExtraData || {},
  4020. btnRemove = $h.FRAMES + ' .kv-file-remove', settings = self.fileActionSettings,
  4021. origClass = settings.removeClass, errClass = settings.removeErrorClass,
  4022. resetProgress = function () {
  4023. var hasFiles = self.isAjaxUpload ? self.previewCache.count(true) : self._inputFileCount();
  4024. if (!self.getFrames().length && !hasFiles) {
  4025. self._setCaption('');
  4026. self.reset();
  4027. self.initialCaption = '';
  4028. } else {
  4029. self._resetCaption();
  4030. }
  4031. };
  4032. self._initZoomButton();
  4033. $preview.find(btnRemove).each(function () {
  4034. var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key'), errMsg, fnBefore,
  4035. fnSuccess, fnError, op = self.ajaxOperations.deleteThumb;
  4036. if ($h.isEmpty(vUrl) || vKey === undefined) {
  4037. return;
  4038. }
  4039. if (typeof vUrl === 'function') {
  4040. vUrl = vUrl();
  4041. }
  4042. var $frame = $el.closest($h.FRAMES), cache = self.previewCache.data, settings, params, config,
  4043. fileName, extraData, index = $frame.attr('data-fileindex');
  4044. index = parseInt(index.replace($h.INIT_FLAG, ''));
  4045. config = $h.isEmpty(cache.config) && $h.isEmpty(cache.config[index]) ? null : cache.config[index];
  4046. extraData = $h.isEmpty(config) || $h.isEmpty(config.extra) ? deleteExtraData : config.extra;
  4047. fileName = config && (config.filename || config.caption) || '';
  4048. if (typeof extraData === 'function') {
  4049. extraData = extraData();
  4050. }
  4051. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  4052. fnBefore = function (jqXHR) {
  4053. self.ajaxAborted = false;
  4054. self._raise('filepredelete', [vKey, jqXHR, extraData]);
  4055. if (self._abort()) {
  4056. jqXHR.abort();
  4057. } else {
  4058. $el.removeClass(errClass);
  4059. $h.addCss($frame, 'file-uploading');
  4060. $h.addCss($el, 'disabled ' + origClass);
  4061. }
  4062. };
  4063. fnSuccess = function (data, textStatus, jqXHR) {
  4064. var n, cap;
  4065. if (!$h.isEmpty(data) && !$h.isEmpty(data.error)) {
  4066. params.jqXHR = jqXHR;
  4067. params.response = data;
  4068. errMsg = self._parseError(op, jqXHR, self.msgDeleteError, fileName);
  4069. self._showFileError(errMsg, params, 'filedeleteerror');
  4070. $frame.removeClass('file-uploading');
  4071. $el.removeClass('disabled ' + origClass).addClass(errClass);
  4072. resetProgress();
  4073. return;
  4074. }
  4075. $frame.removeClass('file-uploading').addClass('file-deleted');
  4076. $frame.fadeOut('slow', function () {
  4077. index = parseInt(($frame.attr('data-fileindex')).replace($h.INIT_FLAG, ''));
  4078. self.previewCache.unset(index);
  4079. self._deleteFileIndex($frame);
  4080. n = self.previewCache.count(true);
  4081. cap = n > 0 ? self._getMsgSelected(n) : '';
  4082. self._setCaption(cap);
  4083. self._raise('filedeleted', [vKey, jqXHR, extraData]);
  4084. self._clearObjects($frame);
  4085. $frame.remove();
  4086. resetProgress();
  4087. });
  4088. };
  4089. fnError = function (jqXHR, textStatus, errorThrown) {
  4090. var errMsg = self._parseError(op, jqXHR, errorThrown, fileName);
  4091. params.jqXHR = jqXHR;
  4092. params.response = {};
  4093. self._showFileError(errMsg, params, 'filedeleteerror');
  4094. $frame.removeClass('file-uploading');
  4095. $el.removeClass('disabled ' + origClass).addClass(errClass);
  4096. resetProgress();
  4097. };
  4098. self._initAjaxSettings();
  4099. self._mergeAjaxCallback('beforeSend', fnBefore, 'delete');
  4100. self._mergeAjaxCallback('success', fnSuccess, 'delete');
  4101. self._mergeAjaxCallback('error', fnError, 'delete');
  4102. settings = $.extend(true, {}, {
  4103. url: self._encodeURI(vUrl),
  4104. type: 'POST',
  4105. dataType: 'json',
  4106. data: $.extend(true, {}, {key: vKey}, extraData)
  4107. }, self._ajaxDeleteSettings);
  4108. self._handler($el, 'click', function () {
  4109. if (!self._validateMinCount()) {
  4110. return false;
  4111. }
  4112. self.ajaxAborted = false;
  4113. self._raise('filebeforedelete', [vKey, extraData]);
  4114. if (self.ajaxAborted instanceof Promise) {
  4115. self.ajaxAborted.then(function (result) {
  4116. if (!result) {
  4117. $.ajax(settings);
  4118. }
  4119. });
  4120. } else {
  4121. if (!self.ajaxAborted) {
  4122. $.ajax(settings);
  4123. }
  4124. }
  4125. });
  4126. });
  4127. },
  4128. _hideFileIcon: function () {
  4129. var self = this;
  4130. if (self.overwriteInitial) {
  4131. self.$captionContainer.removeClass('icon-visible');
  4132. }
  4133. },
  4134. _showFileIcon: function () {
  4135. var self = this;
  4136. $h.addCss(self.$captionContainer, 'icon-visible');
  4137. },
  4138. _getSize: function (bytes, sizes) {
  4139. var self = this, size = parseFloat(bytes), i, func = self.fileSizeGetter, out;
  4140. if (!$.isNumeric(bytes) || !$.isNumeric(size)) {
  4141. return '';
  4142. }
  4143. if (typeof func === 'function') {
  4144. out = func(size);
  4145. } else {
  4146. if (size === 0) {
  4147. out = '0.00 B';
  4148. } else {
  4149. if (!sizes) {
  4150. sizes = self.sizeUnits;
  4151. }
  4152. i = Math.floor(Math.log(size) / Math.log(self.bytesToKB));
  4153. out = (size / Math.pow(self.bytesToKB, i)).toFixed(2) + ' ' + sizes[i];
  4154. }
  4155. }
  4156. return self._getLayoutTemplate('size').replace('{sizeText}', out);
  4157. },
  4158. _getFileType: function (ftype) {
  4159. var self = this;
  4160. return self.mimeTypeAliases[ftype] || ftype;
  4161. },
  4162. _generatePreviewTemplate: function (
  4163. cat,
  4164. data,
  4165. fname,
  4166. ftype,
  4167. previewId,
  4168. fileId,
  4169. isError,
  4170. size,
  4171. frameClass,
  4172. foot,
  4173. ind,
  4174. templ,
  4175. attrs,
  4176. zoomData
  4177. ) {
  4178. var self = this, caption = self.slug(fname), prevContent, zoomContent = '', styleAttribs = '',
  4179. screenW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
  4180. config, title = caption, alt = caption, typeCss = 'type-default', getContent,
  4181. footer = foot || self._renderFileFooter(cat, caption, size, 'auto', isError),
  4182. forcePrevIcon = self.preferIconicPreview, forceZoomIcon = self.preferIconicZoomPreview,
  4183. newCat = forcePrevIcon ? 'other' : cat;
  4184. config = screenW < 400 ? (self.previewSettingsSmall[newCat] || self.defaults.previewSettingsSmall[newCat]) :
  4185. (self.previewSettings[newCat] || self.defaults.previewSettings[newCat]);
  4186. if (config) {
  4187. $.each(config, function (key, val) {
  4188. styleAttribs += key + ':' + val + ';';
  4189. });
  4190. }
  4191. getContent = function (vCat, vData, zoom, frameCss, vZoomData) {
  4192. var id = zoom ? 'zoom-' + previewId : previewId, tmplt = self._getPreviewTemplate(vCat),
  4193. css = (frameClass || '') + ' ' + frameCss, tokens;
  4194. if (self.frameClass) {
  4195. css = self.frameClass + ' ' + css;
  4196. }
  4197. if (zoom) {
  4198. css = css.replace(' ' + $h.SORT_CSS, '');
  4199. }
  4200. tmplt = self._parseFilePreviewIcon(tmplt, fname);
  4201. if (cat === 'object' && !ftype) {
  4202. $.each(self.defaults.fileTypeSettings, function (key, func) {
  4203. if (key === 'object' || key === 'other') {
  4204. return;
  4205. }
  4206. if (func(fname, ftype)) {
  4207. typeCss = 'type-' + key;
  4208. }
  4209. });
  4210. }
  4211. if (!$h.isEmpty(attrs)) {
  4212. if (attrs.title !== undefined && attrs.title !== null) {
  4213. title = attrs.title;
  4214. }
  4215. if (attrs.alt !== undefined && attrs.alt !== null) {
  4216. title = attrs.alt;
  4217. }
  4218. }
  4219. tokens = {
  4220. 'previewId': id,
  4221. 'caption': caption,
  4222. 'title': title,
  4223. 'alt': alt,
  4224. 'frameClass': css,
  4225. 'type': self._getFileType(ftype),
  4226. 'fileindex': ind,
  4227. 'fileid': fileId || '',
  4228. 'typeCss': typeCss,
  4229. 'footer': footer,
  4230. 'data': vData,
  4231. // 'data': zoom && vZoomData ? $h.ZOOM_VAR + '{zoomData}' : vData,
  4232. 'template': templ || cat,
  4233. 'style': styleAttribs ? 'style="' + styleAttribs + '"' : '',
  4234. 'zoomData': vZoomData ? encodeURIComponent(vZoomData) : ''
  4235. };
  4236. if (zoom) {
  4237. tokens.zoomCache = '';
  4238. tokens.zoomData = '{zoomData}';
  4239. }
  4240. return tmplt.setTokens(tokens);
  4241. };
  4242. ind = ind || previewId.slice(previewId.lastIndexOf('-') + 1);
  4243. if (self.fileActionSettings.showZoom) {
  4244. zoomContent = getContent((forceZoomIcon ? 'other' : cat), data, true, 'kv-zoom-thumb', zoomData);
  4245. }
  4246. zoomContent = '\n' + self._getLayoutTemplate('zoomCache').replace('{zoomContent}', zoomContent);
  4247. if (typeof self.sanitizeZoomCache === 'function') {
  4248. zoomContent = self.sanitizeZoomCache(zoomContent);
  4249. }
  4250. prevContent = getContent((forcePrevIcon ? 'other' : cat), data, false, 'kv-preview-thumb', zoomData);
  4251. return prevContent.setTokens({zoomCache: zoomContent});
  4252. },
  4253. _addToPreview: function ($preview, content) {
  4254. var self = this, $el;
  4255. content = $h.cspBuffer.stash(content);
  4256. $el = self.reversePreviewOrder ? $preview.prepend(content) : $preview.append(content);
  4257. $h.cspBuffer.apply($preview);
  4258. return $el;
  4259. },
  4260. _previewDefault: function (file, isDisabled) {
  4261. var self = this, $preview = self.$preview;
  4262. if (!self.showPreview) {
  4263. return;
  4264. }
  4265. var fname = $h.getFileName(file), ftype = file ? file.type : '', content, size = file.size || 0,
  4266. caption = self._getFileName(file, ''), isError = isDisabled === true && !self.isAjaxUpload,
  4267. data = $h.createObjectURL(file), fileId = self.fileManager.getId(file),
  4268. previewId = self._getThumbId(fileId);
  4269. self._clearDefaultPreview();
  4270. content = self._generatePreviewTemplate('other', data, fname, ftype, previewId, fileId, isError, size);
  4271. self._addToPreview($preview, content);
  4272. self._setThumbAttr(previewId, caption, size);
  4273. if (isDisabled === true && self.isAjaxUpload) {
  4274. self._setThumbStatus(self._getFrame(previewId), 'Error');
  4275. }
  4276. },
  4277. _previewFile: function (i, file, theFile, data, fileInfo) {
  4278. if (!this.showPreview) {
  4279. return;
  4280. }
  4281. var self = this, fname = $h.getFileName(file), ftype = fileInfo.type, caption = fileInfo.name,
  4282. cat = self._parseFileType(ftype, fname), content, $preview = self.$preview, fsize = file.size || 0,
  4283. iData = cat === 'image' ? theFile.target.result : data, fm = self.fileManager,
  4284. fileId = fm.getId(file), previewId = self._getThumbId(fileId);
  4285. /** @namespace window.DOMPurify */
  4286. content = self._generatePreviewTemplate(cat, iData, fname, ftype, previewId, fileId, false, fsize);
  4287. self._clearDefaultPreview();
  4288. self._addToPreview($preview, content);
  4289. var $thumb = self._getFrame(previewId);
  4290. self._validateImageOrientation($thumb.find('img'), file, previewId, fileId, caption, ftype, fsize, iData);
  4291. self._setThumbAttr(previewId, caption, fsize);
  4292. self._initSortable();
  4293. },
  4294. _setThumbAttr: function (id, caption, size, description) {
  4295. var self = this, $frame = self._getFrame(id);
  4296. if ($frame.length) {
  4297. size = size && size > 0 ? self._getSize(size) : '';
  4298. $frame.data({'caption': caption, 'size': size, 'description': description || ''});
  4299. }
  4300. },
  4301. _setInitThumbAttr: function () {
  4302. var self = this, data = self.previewCache.data, len = self.previewCache.count(true), config,
  4303. caption, size, description, previewId;
  4304. if (len === 0) {
  4305. return;
  4306. }
  4307. for (var i = 0; i < len; i++) {
  4308. config = data.config[i];
  4309. previewId = self.previewInitId + '-' + $h.INIT_FLAG + i;
  4310. caption = $h.ifSet('caption', config, $h.ifSet('filename', config));
  4311. size = $h.ifSet('size', config);
  4312. description = $h.ifSet('description', config);
  4313. self._setThumbAttr(previewId, caption, size, description);
  4314. }
  4315. },
  4316. _slugDefault: function (text) {
  4317. // noinspection RegExpRedundantEscape
  4318. return $h.isEmpty(text, true) ? '' : String(text).replace(/[\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_');
  4319. },
  4320. _updateFileDetails: function (numFiles) {
  4321. var self = this, $el = self.$element, label, n, log, nFiles, file,
  4322. name = ($h.isIE(9) && $h.findFileName($el.val())) || ($el[0].files[0] && $el[0].files[0].name);
  4323. if (!name && self.fileManager.count() > 0) {
  4324. file = self.fileManager.getFirstFile();
  4325. label = file.nameFmt;
  4326. } else {
  4327. label = name ? self.slug(name) : '_';
  4328. }
  4329. n = self.isAjaxUpload ? self.fileManager.count() : numFiles;
  4330. nFiles = self.previewCache.count(true) + n;
  4331. log = n === 1 ? label : self._getMsgSelected(nFiles, !self.isAjaxUpload && !self.isError);
  4332. if (self.isError) {
  4333. self.$previewContainer.removeClass('file-thumb-loading');
  4334. self._initCapStatus();
  4335. self.$previewStatus.html('');
  4336. self.$captionContainer.removeClass('icon-visible');
  4337. } else {
  4338. self._showFileIcon();
  4339. }
  4340. self._setCaption(log, self.isError);
  4341. self.$container.removeClass('file-input-new file-input-ajax-new');
  4342. self._raise('fileselect', [numFiles, label]);
  4343. if (self.previewCache.count(true)) {
  4344. self._initPreviewActions();
  4345. }
  4346. },
  4347. _setThumbStatus: function ($thumb, status) {
  4348. var self = this;
  4349. if (!self.showPreview) {
  4350. return;
  4351. }
  4352. var icon = 'indicator' + status, msg = icon + 'Title',
  4353. css = 'file-preview-' + status.toLowerCase(),
  4354. $indicator = $thumb.find('.file-upload-indicator'),
  4355. config = self.fileActionSettings;
  4356. $thumb.removeClass('file-preview-success file-preview-error file-preview-paused file-preview-loading');
  4357. if (status === 'Success') {
  4358. $thumb.find('.file-drag-handle').remove();
  4359. }
  4360. $h.setHtml($indicator, config[icon]);
  4361. $indicator.attr('title', config[msg]);
  4362. $thumb.addClass(css);
  4363. if (status === 'Error' && !self.retryErrorUploads) {
  4364. $thumb.find('.kv-file-upload').attr('disabled', true);
  4365. }
  4366. },
  4367. _setProgressCancelled: function () {
  4368. var self = this;
  4369. self._setProgress(101, self.$progress, self.msgCancelled);
  4370. },
  4371. _setProgress: function (p, $el, error, stats) {
  4372. var self = this;
  4373. $el = $el || self.$progress;
  4374. if (!$el.length) {
  4375. return;
  4376. }
  4377. var pct = Math.min(p, 100), out, pctLimit = self.progressUploadThreshold,
  4378. t = p <= 100 ? self.progressTemplate : self.progressCompleteTemplate,
  4379. template = pct < 100 ? self.progressTemplate :
  4380. (error ? (self.paused ? self.progressPauseTemplate : self.progressErrorTemplate) : t);
  4381. if (p >= 100) {
  4382. stats = '';
  4383. }
  4384. if (!$h.isEmpty(template)) {
  4385. if (pctLimit && pct > pctLimit && p <= 100) {
  4386. out = template.setTokens({'percent': pctLimit, 'status': self.msgUploadThreshold});
  4387. } else {
  4388. out = template.setTokens({'percent': pct, 'status': (p > 100 ? self.msgUploadEnd : pct + '%')});
  4389. }
  4390. stats = stats || '';
  4391. out = out.setTokens({stats: stats});
  4392. $h.setHtml($el, out);
  4393. if (error) {
  4394. $h.setHtml($el.find('[role="progressbar"]'), error);
  4395. }
  4396. }
  4397. },
  4398. _hasFiles: function () {
  4399. var el = this.$element[0];
  4400. return !!(el && el.files && el.files.length);
  4401. },
  4402. _setFileDropZoneTitle: function () {
  4403. var self = this, $zone = self.$container.find('.file-drop-zone'), title = self.dropZoneTitle, strFiles;
  4404. if (self.isClickable) {
  4405. strFiles = $h.isEmpty(self.$element.attr('multiple')) ? self.fileSingle : self.filePlural;
  4406. title += self.dropZoneClickTitle.replace('{files}', strFiles);
  4407. }
  4408. $zone.find('.' + self.dropZoneTitleClass).remove();
  4409. if (!self.showPreview || $zone.length === 0 || self.fileManager.count() > 0 || !self.dropZoneEnabled ||
  4410. self.previewCache.count() > 0 || (!self.isAjaxUpload && self._hasFiles())) {
  4411. return;
  4412. }
  4413. if ($zone.find($h.FRAMES).length === 0 && $h.isEmpty(self.defaultPreviewContent)) {
  4414. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + title + '</div>');
  4415. }
  4416. self.$container.removeClass('file-input-new');
  4417. $h.addCss(self.$container, 'file-input-ajax-new');
  4418. },
  4419. _getStats: function (stats) {
  4420. var self = this, pendingTime, t;
  4421. if (!self.showUploadStats || !stats || !stats.bitrate) {
  4422. return '';
  4423. }
  4424. t = self._getLayoutTemplate('stats');
  4425. pendingTime = (!stats.elapsed || !stats.bps) ? self.msgCalculatingTime :
  4426. self.msgPendingTime.setTokens({time: $h.getElapsed(Math.ceil(stats.pendingBytes / stats.bps))});
  4427. return t.setTokens({
  4428. uploadSpeed: stats.bitrate,
  4429. pendingTime: pendingTime
  4430. });
  4431. },
  4432. _setResumableProgress: function (pct, stats, $thumb) {
  4433. var self = this, rm = self.resumableManager, obj = $thumb ? rm : self,
  4434. $prog = $thumb ? $thumb.find('.file-thumb-progress') : null;
  4435. if (obj.lastProgress === 0) {
  4436. obj.lastProgress = pct;
  4437. }
  4438. if (pct < obj.lastProgress) {
  4439. pct = obj.lastProgress;
  4440. }
  4441. self._setProgress(pct, $prog, null, self._getStats(stats));
  4442. obj.lastProgress = pct;
  4443. },
  4444. _toggleResumableProgress: function (template, message) {
  4445. var self = this, $progress = self.$progress;
  4446. if ($progress && $progress.length) {
  4447. $h.setHtml($progress, template.setTokens({
  4448. percent: 101,
  4449. status: message,
  4450. stats: ''
  4451. }));
  4452. }
  4453. },
  4454. _setFileUploadStats: function (id, pct, stats) {
  4455. var self = this, $prog = self.$progress;
  4456. if (!self.showPreview && (!$prog || !$prog.length)) {
  4457. return;
  4458. }
  4459. var fm = self.fileManager, rm = self.resumableManager, $thumb = fm.getThumb(id), pctTot,
  4460. totUpSize = 0, totSize = fm.getTotalSize(), totStats = $.extend(true, {}, stats);
  4461. if (self.enableResumableUpload) {
  4462. var loaded = stats.loaded, currUplSize = rm.getUploadedSize(), currTotSize = rm.file.size, totLoaded;
  4463. loaded += currUplSize;
  4464. totLoaded = fm.uploadedSize + loaded;
  4465. pct = $h.round(100 * loaded / currTotSize);
  4466. stats.pendingBytes = currTotSize - currUplSize;
  4467. self._setResumableProgress(pct, stats, $thumb);
  4468. pctTot = Math.floor(100 * totLoaded / totSize);
  4469. totStats.pendingBytes = totSize - totLoaded;
  4470. self._setResumableProgress(pctTot, totStats);
  4471. } else {
  4472. fm.setProgress(id, pct);
  4473. $prog = $thumb && $thumb.length ? $thumb.find('.file-thumb-progress') : null;
  4474. self._setProgress(pct, $prog, null, self._getStats(stats));
  4475. $.each(fm.stats, function (id, cfg) {
  4476. totUpSize += cfg.loaded;
  4477. });
  4478. totStats.pendingBytes = totSize - totUpSize;
  4479. pctTot = $h.round(totUpSize / totSize * 100);
  4480. self._setProgress(pctTot, null, null, self._getStats(totStats));
  4481. }
  4482. },
  4483. _validateMinCount: function () {
  4484. var self = this, len = self.isAjaxUpload ? self.fileManager.count() : self._inputFileCount();
  4485. if (self.validateInitialCount && self.minFileCount > 0 && self._getFileCount(len - 1) < self.minFileCount) {
  4486. self._noFilesError({});
  4487. return false;
  4488. }
  4489. return true;
  4490. },
  4491. _getFileCount: function (fileCount, includeInitial) {
  4492. var self = this, addCount = 0;
  4493. if (includeInitial === undefined) {
  4494. includeInitial = self.validateInitialCount && !self.overwriteInitial;
  4495. }
  4496. if (includeInitial) {
  4497. addCount = self.previewCache.count(true);
  4498. fileCount += addCount;
  4499. }
  4500. return fileCount;
  4501. },
  4502. _getFileId: function (file) {
  4503. return $h.getFileId(file, this.generateFileId);
  4504. },
  4505. _getFileName: function (file, defaultValue) {
  4506. var self = this, fileName = $h.getFileName(file);
  4507. return fileName ? self.slug(fileName) : defaultValue;
  4508. },
  4509. _getFileNames: function (skipNull) {
  4510. var self = this;
  4511. return self.filenames.filter(function (n) {
  4512. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  4513. });
  4514. },
  4515. _setPreviewError: function ($thumb, keepFile) {
  4516. var self = this, removeFrame = self.removeFromPreviewOnError && !self.retryErrorUploads;
  4517. if (!keepFile || removeFrame) {
  4518. self.fileManager.remove($thumb);
  4519. }
  4520. if (!self.showPreview) {
  4521. return;
  4522. }
  4523. if (removeFrame) {
  4524. $thumb.remove();
  4525. return;
  4526. } else {
  4527. self._setThumbStatus($thumb, 'Error');
  4528. }
  4529. self._refreshUploadButton($thumb);
  4530. },
  4531. _refreshUploadButton: function ($thumb) {
  4532. var self = this, $btn = $thumb.find('.kv-file-upload'), cfg = self.fileActionSettings,
  4533. icon = cfg.uploadIcon, title = cfg.uploadTitle;
  4534. if (!$btn.length) {
  4535. return;
  4536. }
  4537. if (self.retryErrorUploads) {
  4538. icon = cfg.uploadRetryIcon;
  4539. title = cfg.uploadRetryTitle;
  4540. }
  4541. $btn.attr('title', title);
  4542. $h.setHtml($btn, icon);
  4543. },
  4544. _checkDimensions: function (i, chk, $img, $thumb, fname, type, params) {
  4545. var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max', limit = self[tag + 'Image' + type],
  4546. $imgEl, isValid;
  4547. if ($h.isEmpty(limit) || !$img.length) {
  4548. return;
  4549. }
  4550. $imgEl = $img[0];
  4551. dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height;
  4552. isValid = chk === 'Small' ? dim >= limit : dim <= limit;
  4553. if (isValid) {
  4554. return;
  4555. }
  4556. msg = self['msgImage' + type + chk].setTokens({'name': fname, 'size': limit});
  4557. self._showFileError(msg, params);
  4558. self._setPreviewError($thumb);
  4559. },
  4560. _getExifObj: function (data) {
  4561. var self = this, exifObj, error = $h.logMessages.exifWarning;
  4562. if (data.slice(0, 23) !== 'data:image/jpeg;base64,' && data.slice(0, 22) !== 'data:image/jpg;base64,') {
  4563. exifObj = null;
  4564. return;
  4565. }
  4566. try {
  4567. exifObj = window.piexif ? window.piexif.load(data) : null;
  4568. } catch (err) {
  4569. exifObj = null;
  4570. error = err && err.message || '';
  4571. }
  4572. if (!exifObj) {
  4573. self._log($h.logMessages.badExifParser, {details: error});
  4574. }
  4575. return exifObj;
  4576. },
  4577. setImageOrientation: function ($img, $zoomImg, value, $thumb) {
  4578. var self = this, invalidImg = !$img || !$img.length, invalidZoomImg = !$zoomImg || !$zoomImg.length, $mark,
  4579. isHidden = false, $div, zoomOnly = invalidImg && $thumb && $thumb.attr('data-template') === 'image', ev;
  4580. if (invalidImg && invalidZoomImg) {
  4581. return;
  4582. }
  4583. ev = 'load.fileinputimageorient';
  4584. if (zoomOnly) {
  4585. $img = $zoomImg;
  4586. $zoomImg = null;
  4587. $img.css(self.previewSettings.image);
  4588. $div = $(document.createElement('div')).appendTo($thumb.find('.kv-file-content'));
  4589. $mark = $(document.createElement('span')).insertBefore($img);
  4590. $img.css('visibility', 'hidden').removeClass('file-zoom-detail').appendTo($div);
  4591. } else {
  4592. isHidden = !$img.is(':visible');
  4593. }
  4594. $img.off(ev).on(ev, function () {
  4595. if (isHidden) {
  4596. self.$preview.removeClass('hide-content');
  4597. $thumb.find('.kv-file-content').css('visibility', 'hidden');
  4598. }
  4599. var img = $img[0], zoomImg = $zoomImg && $zoomImg.length ? $zoomImg[0] : null,
  4600. h = img.offsetHeight, w = img.offsetWidth, r = $h.getRotation(value);
  4601. if (isHidden) {
  4602. $thumb.find('.kv-file-content').css('visibility', 'visible');
  4603. self.$preview.addClass('hide-content');
  4604. }
  4605. $img.data('orientation', value);
  4606. if (zoomImg) {
  4607. $zoomImg.data('orientation', value);
  4608. }
  4609. if (value < 5) {
  4610. $h.setTransform(img, r);
  4611. $h.setTransform(zoomImg, r);
  4612. return;
  4613. }
  4614. var offsetAngle = Math.atan(w / h), origFactor = Math.sqrt(Math.pow(h, 2) + Math.pow(w, 2)),
  4615. scale = !origFactor ? 1 : (h / Math.cos(Math.PI / 2 + offsetAngle)) / origFactor,
  4616. s = ' scale(' + Math.abs(scale) + ')';
  4617. $h.setTransform(img, r + s);
  4618. $h.setTransform(zoomImg, r + s);
  4619. if (zoomOnly) {
  4620. $img.css('visibility', 'visible').insertAfter($mark).addClass('file-zoom-detail');
  4621. $mark.remove();
  4622. $div.remove();
  4623. }
  4624. });
  4625. },
  4626. _validateImageOrientation: function ($img, file, previewId, fileId, caption, ftype, fsize, iData) {
  4627. var self = this, exifObj = null, value, autoOrientImage = self.autoOrientImage, selector;
  4628. if (self.canOrientImage) {
  4629. $img.css('image-orientation', (autoOrientImage ? 'from-image' : 'none'));
  4630. self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj);
  4631. return;
  4632. }
  4633. selector = $h.getZoomSelector(previewId, ' img');
  4634. exifObj = autoOrientImage ? self._getExifObj(iData) : null;
  4635. value = exifObj ? exifObj['0th'][piexif.ImageIFD.Orientation] : null; // jshint ignore:line
  4636. if (!value) {
  4637. self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj);
  4638. return;
  4639. }
  4640. self.setImageOrientation($img, $(selector), value, self._getFrame(previewId));
  4641. self._raise('fileimageoriented', {'$img': $img, 'file': file});
  4642. self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj);
  4643. },
  4644. _validateImage: function (previewId, fileId, fname, ftype, fsize, iData, exifObj) {
  4645. var self = this, $preview = self.$preview, params, w1, w2, $thumb = self._getFrame(previewId),
  4646. i = $thumb.attr('data-fileindex'), $img = $thumb.find('img');
  4647. fname = fname || 'Untitled';
  4648. $img.one('load', function () {
  4649. w1 = $thumb.width();
  4650. w2 = $preview.width();
  4651. if (w1 > w2) {
  4652. $img.css('width', '100%');
  4653. }
  4654. params = {ind: i, id: previewId, fileId: fileId};
  4655. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
  4656. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
  4657. if (!self.resizeImage) {
  4658. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
  4659. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
  4660. }
  4661. self._raise('fileimageloaded', [previewId]);
  4662. self.fileManager.addImage(fileId, {
  4663. ind: i,
  4664. img: $img,
  4665. thumb: $thumb,
  4666. pid: previewId,
  4667. typ: ftype,
  4668. siz: fsize,
  4669. validated: false,
  4670. imgData: iData,
  4671. exifObj: exifObj
  4672. });
  4673. $thumb.data('exif', exifObj);
  4674. self._validateAllImages();
  4675. }).one('error', function () {
  4676. self._raise('fileimageloaderror', [previewId]);
  4677. });
  4678. },
  4679. _validateAllImages: function () {
  4680. var self = this, counter = {val: 0}, numImgs = self.fileManager.getImageCount(), fsize,
  4681. minSize = self.resizeIfSizeMoreThan;
  4682. if (numImgs !== self.fileManager.totalImages) {
  4683. return;
  4684. }
  4685. self._raise('fileimagesloaded');
  4686. if (!self.resizeImage) {
  4687. return;
  4688. }
  4689. $.each(self.fileManager.loadedImages, function (id, config) {
  4690. if (!config.validated) {
  4691. fsize = config.siz;
  4692. if (fsize && fsize > minSize * self.bytesToKB) {
  4693. self._getResizedImage(id, config, counter, numImgs);
  4694. }
  4695. config.validated = true;
  4696. }
  4697. });
  4698. },
  4699. _getResizedImage: function (id, config, counter, numImgs) {
  4700. var self = this, img = $(config.img)[0], width = img.naturalWidth, height = img.naturalHeight, blob,
  4701. ratio = 1, maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height,
  4702. isValidImage = !!(width && height), chkWidth, chkHeight, canvas = self.imageCanvas, dataURI,
  4703. context = self.imageCanvasContext, type = config.typ, pid = config.pid, ind = config.ind,
  4704. $thumb = config.thumb, throwError, msg, exifObj = config.exifObj, exifStr, file, params, evParams;
  4705. throwError = function (msg, params, ev) {
  4706. if (self.isAjaxUpload) {
  4707. self._showFileError(msg, params, ev);
  4708. } else {
  4709. self._showError(msg, params, ev);
  4710. }
  4711. self._setPreviewError($thumb);
  4712. };
  4713. file = self.fileManager.getFile(id);
  4714. params = {id: pid, 'index': ind, fileId: id};
  4715. evParams = [id, pid, ind];
  4716. if (!file || !isValidImage || (width <= maxWidth && height <= maxHeight)) {
  4717. if (isValidImage && file) {
  4718. self._raise('fileimageresized', evParams);
  4719. }
  4720. counter.val++;
  4721. if (counter.val === numImgs) {
  4722. self._raise('fileimagesresized');
  4723. }
  4724. if (!isValidImage) {
  4725. throwError(self.msgImageResizeError, params, 'fileimageresizeerror');
  4726. return;
  4727. }
  4728. }
  4729. type = type || self.resizeDefaultImageType;
  4730. chkWidth = width > maxWidth;
  4731. chkHeight = height > maxHeight;
  4732. if (self.resizePreference === 'width') {
  4733. ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1);
  4734. } else {
  4735. ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1);
  4736. }
  4737. self._resetCanvas();
  4738. width *= ratio;
  4739. height *= ratio;
  4740. canvas.width = width;
  4741. canvas.height = height;
  4742. try {
  4743. context.drawImage(img, 0, 0, width, height);
  4744. dataURI = canvas.toDataURL(type, self.resizeQuality);
  4745. if (exifObj) {
  4746. exifStr = window.piexif.dump(exifObj);
  4747. dataURI = window.piexif.insert(exifStr, dataURI);
  4748. }
  4749. blob = $h.dataURI2Blob(dataURI);
  4750. self.fileManager.setFile(id, blob);
  4751. self._raise('fileimageresized', evParams);
  4752. counter.val++;
  4753. if (counter.val === numImgs) {
  4754. self._raise('fileimagesresized', [undefined, undefined]);
  4755. }
  4756. if (!(blob instanceof Blob)) {
  4757. throwError(self.msgImageResizeError, params, 'fileimageresizeerror');
  4758. }
  4759. } catch (err) {
  4760. counter.val++;
  4761. if (counter.val === numImgs) {
  4762. self._raise('fileimagesresized', [undefined, undefined]);
  4763. }
  4764. msg = self.msgImageResizeException.replace('{errors}', err.message);
  4765. throwError(msg, params, 'fileimageresizeexception');
  4766. }
  4767. },
  4768. _showProgress: function () {
  4769. var self = this;
  4770. if (self.$progress && self.$progress.length) {
  4771. self.$progress.show();
  4772. }
  4773. },
  4774. _hideProgress: function () {
  4775. var self = this;
  4776. if (self.$progress && self.$progress.length) {
  4777. self.$progress.hide();
  4778. }
  4779. },
  4780. _initBrowse: function ($container) {
  4781. var self = this, $el = self.$element;
  4782. if (self.showBrowse) {
  4783. self.$btnFile = $container.find('.btn-file').append($el);
  4784. } else {
  4785. $el.appendTo($container).attr('tabindex', -1);
  4786. $h.addCss($el, 'file-no-browse');
  4787. }
  4788. },
  4789. _initClickable: function () {
  4790. var self = this, $zone, $tmpZone;
  4791. if (!self.isClickable) {
  4792. return;
  4793. }
  4794. $zone = self.$dropZone;
  4795. if (!self.isAjaxUpload) {
  4796. $tmpZone = self.$preview.find('.file-default-preview');
  4797. if ($tmpZone.length) {
  4798. $zone = $tmpZone;
  4799. }
  4800. }
  4801. $h.addCss($zone, 'clickable');
  4802. $zone.attr('tabindex', -1);
  4803. self._handler($zone, 'click', function (e) {
  4804. var $tar = $(e.target);
  4805. if (!self.$errorContainer.is(':visible') && (!$tar.parents(
  4806. '.file-preview-thumbnails').length || $tar.parents(
  4807. '.file-default-preview').length)) {
  4808. self.$element.data('zoneClicked', true).trigger('click');
  4809. $zone.blur();
  4810. }
  4811. });
  4812. },
  4813. _initCaption: function () {
  4814. var self = this, cap = self.initialCaption || '';
  4815. if (self.overwriteInitial || $h.isEmpty(cap)) {
  4816. self.$caption.val('');
  4817. return false;
  4818. }
  4819. self._setCaption(cap);
  4820. return true;
  4821. },
  4822. _setCaption: function (content, isError) {
  4823. var self = this, title, out, icon, n, cap, file;
  4824. if (!self.$caption.length) {
  4825. return;
  4826. }
  4827. self.$captionContainer.removeClass('icon-visible');
  4828. if (isError) {
  4829. title = $('<div>' + self.msgValidationError + '</div>').text();
  4830. n = self.fileManager.count();
  4831. if (n) {
  4832. file = self.fileManager.getFirstFile();
  4833. cap = n === 1 && file ? file.nameFmt : self._getMsgSelected(n);
  4834. } else {
  4835. cap = self._getMsgSelected(self.msgNo);
  4836. }
  4837. out = $h.isEmpty(content) ? cap : content;
  4838. icon = '<span class="' + self.msgValidationErrorClass + '">' + self.msgValidationErrorIcon + '</span>';
  4839. } else {
  4840. if ($h.isEmpty(content)) {
  4841. self.$caption.attr('title', '');
  4842. return;
  4843. }
  4844. title = $('<div>' + content + '</div>').text();
  4845. out = title;
  4846. icon = self._getLayoutTemplate('fileIcon');
  4847. }
  4848. self.$captionContainer.addClass('icon-visible');
  4849. self.$caption.attr('title', title).val(out);
  4850. $h.setHtml(self.$captionIcon, icon);
  4851. },
  4852. _createContainer: function () {
  4853. var self = this, attribs = {'class': 'file-input file-input-new' + (self.rtl ? ' kv-rtl' : '')},
  4854. $container = $h.createElement($h.cspBuffer.stash(self._renderMain()));
  4855. $h.cspBuffer.apply($container);
  4856. $container.insertBefore(self.$element).attr(attribs);
  4857. self._initBrowse($container);
  4858. if (self.theme) {
  4859. $container.addClass('theme-' + self.theme);
  4860. }
  4861. return $container;
  4862. },
  4863. _refreshContainer: function () {
  4864. var self = this, $container = self.$container, $el = self.$element;
  4865. $el.insertAfter($container);
  4866. $h.setHtml($container, self._renderMain());
  4867. self._initBrowse($container);
  4868. self._validateDisabled();
  4869. },
  4870. _validateDisabled: function () {
  4871. var self = this;
  4872. self.$caption.attr({readonly: self.isDisabled});
  4873. },
  4874. _setTabIndex: function (type, html) {
  4875. var self = this, index = self.tabIndexConfig[type];
  4876. return html.setTokens({
  4877. tabIndexConfig: index === undefined || index === null ? '' : 'tabindex="' + index + '"'
  4878. });
  4879. },
  4880. _renderMain: function () {
  4881. var self = this,
  4882. dropCss = self.dropZoneEnabled ? ' file-drop-zone' : 'file-drop-disabled',
  4883. close = !self.showClose ? '' : self._getLayoutTemplate('close'),
  4884. preview = !self.showPreview ? '' : self._getLayoutTemplate('preview')
  4885. .setTokens({'class': self.previewClass, 'dropClass': dropCss}),
  4886. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  4887. caption = self.captionTemplate.setTokens({'class': css + ' kv-fileinput-caption'});
  4888. caption = self._setTabIndex('caption', caption);
  4889. return self.mainTemplate.setTokens({
  4890. 'class': self.mainClass + (!self.showBrowse && self.showCaption ? ' no-browse' : ''),
  4891. 'inputGroupClass': self.inputGroupClass,
  4892. 'preview': preview,
  4893. 'close': close,
  4894. 'caption': caption,
  4895. 'upload': self._renderButton('upload'),
  4896. 'remove': self._renderButton('remove'),
  4897. 'cancel': self._renderButton('cancel'),
  4898. 'pause': self._renderButton('pause'),
  4899. 'browse': self._renderButton('browse')
  4900. });
  4901. },
  4902. _renderButton: function (type) {
  4903. var self = this, tmplt = self._getLayoutTemplate('btnDefault'), css = self[type + 'Class'],
  4904. title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'],
  4905. status = self.isDisabled ? ' disabled' : '', btnType = 'button';
  4906. switch (type) {
  4907. case 'remove':
  4908. if (!self.showRemove) {
  4909. return '';
  4910. }
  4911. break;
  4912. case 'cancel':
  4913. if (!self.showCancel) {
  4914. return '';
  4915. }
  4916. css += ' kv-hidden';
  4917. break;
  4918. case 'pause':
  4919. if (!self.showPause) {
  4920. return '';
  4921. }
  4922. css += ' kv-hidden';
  4923. break;
  4924. case 'upload':
  4925. if (!self.showUpload) {
  4926. return '';
  4927. }
  4928. if (self.isAjaxUpload && !self.isDisabled) {
  4929. tmplt = self._getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl);
  4930. } else {
  4931. btnType = 'submit';
  4932. }
  4933. break;
  4934. case 'browse':
  4935. if (!self.showBrowse) {
  4936. return '';
  4937. }
  4938. tmplt = self._getLayoutTemplate('btnBrowse');
  4939. break;
  4940. default:
  4941. return '';
  4942. }
  4943. tmplt = self._setTabIndex(type, tmplt);
  4944. css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button';
  4945. if (!$h.isEmpty(label)) {
  4946. label = ' <span class="' + self.buttonLabelClass + '">' + label + '</span>';
  4947. }
  4948. return tmplt.setTokens({
  4949. 'type': btnType, 'css': css, 'title': title, 'status': status, 'icon': icon, 'label': label
  4950. });
  4951. },
  4952. _renderThumbProgress: function () {
  4953. var self = this;
  4954. return '<div class="file-thumb-progress kv-hidden">' +
  4955. self.progressInfoTemplate.setTokens({percent: 101, status: self.msgUploadBegin, stats: ''}) +
  4956. '</div>';
  4957. },
  4958. _renderFileFooter: function (cat, caption, size, width, isError) {
  4959. var self = this, config = self.fileActionSettings, rem = config.showRemove, drg = config.showDrag,
  4960. upl = config.showUpload, zoom = config.showZoom, out, params,
  4961. template = self._getLayoutTemplate('footer'), tInd = self._getLayoutTemplate('indicator'),
  4962. ind = isError ? config.indicatorError : config.indicatorNew,
  4963. title = isError ? config.indicatorErrorTitle : config.indicatorNewTitle,
  4964. indicator = tInd.setTokens({'indicator': ind, 'indicatorTitle': title});
  4965. size = self._getSize(size);
  4966. params = {type: cat, caption: caption, size: size, width: width, progress: '', indicator: indicator};
  4967. if (self.isAjaxUpload) {
  4968. params.progress = self._renderThumbProgress();
  4969. params.actions = self._renderFileActions(params, upl, false, rem, zoom, drg, false, false, false);
  4970. } else {
  4971. params.actions = self._renderFileActions(params, false, false, false, zoom, drg, false, false, false);
  4972. }
  4973. out = template.setTokens(params);
  4974. out = $h.replaceTags(out, self.previewThumbTags);
  4975. return out;
  4976. },
  4977. _renderFileActions: function (
  4978. cfg,
  4979. showUpl,
  4980. showDwn,
  4981. showDel,
  4982. showZoom,
  4983. showDrag,
  4984. disabled,
  4985. url,
  4986. key,
  4987. isInit,
  4988. dUrl,
  4989. dFile
  4990. ) {
  4991. var self = this;
  4992. if (!cfg.type && isInit) {
  4993. cfg.type = 'image';
  4994. }
  4995. if (self.enableResumableUpload) {
  4996. showUpl = false;
  4997. } else {
  4998. if (typeof showUpl === 'function') {
  4999. showUpl = showUpl(cfg);
  5000. }
  5001. }
  5002. if (typeof showDwn === 'function') {
  5003. showDwn = showDwn(cfg);
  5004. }
  5005. if (typeof showDel === 'function') {
  5006. showDel = showDel(cfg);
  5007. }
  5008. if (typeof showZoom === 'function') {
  5009. showZoom = showZoom(cfg);
  5010. }
  5011. if (typeof showDrag === 'function') {
  5012. showDrag = showDrag(cfg);
  5013. }
  5014. if (!showUpl && !showDwn && !showDel && !showZoom && !showDrag) {
  5015. return '';
  5016. }
  5017. var vUrl = url === false ? '' : ' data-url="' + url + '"', btnZoom = '', btnDrag = '', css,
  5018. vKey = key === false ? '' : ' data-key="' + key + '"', btnDelete = '', btnUpload = '', btnDownload = '',
  5019. template = self._getLayoutTemplate('actions'), config = self.fileActionSettings,
  5020. otherButtons = self.otherActionButtons.setTokens({'dataKey': vKey, 'key': key}),
  5021. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  5022. if (showDel) {
  5023. btnDelete = self._getLayoutTemplate('actionDelete').setTokens({
  5024. 'removeClass': removeClass,
  5025. 'removeIcon': config.removeIcon,
  5026. 'removeTitle': config.removeTitle,
  5027. 'dataUrl': vUrl,
  5028. 'dataKey': vKey,
  5029. 'key': key
  5030. });
  5031. }
  5032. if (showUpl) {
  5033. btnUpload = self._getLayoutTemplate('actionUpload').setTokens({
  5034. 'uploadClass': config.uploadClass,
  5035. 'uploadIcon': config.uploadIcon,
  5036. 'uploadTitle': config.uploadTitle
  5037. });
  5038. }
  5039. if (showDwn) {
  5040. btnDownload = self._getLayoutTemplate('actionDownload').setTokens({
  5041. 'downloadClass': config.downloadClass,
  5042. 'downloadIcon': config.downloadIcon,
  5043. 'downloadTitle': config.downloadTitle,
  5044. 'downloadUrl': dUrl || self.initialPreviewDownloadUrl
  5045. });
  5046. btnDownload = btnDownload.setTokens({'filename': dFile, 'key': key});
  5047. }
  5048. if (showZoom) {
  5049. btnZoom = self._getLayoutTemplate('actionZoom').setTokens({
  5050. 'zoomClass': config.zoomClass,
  5051. 'zoomIcon': config.zoomIcon,
  5052. 'zoomTitle': config.zoomTitle
  5053. });
  5054. }
  5055. if (showDrag && isInit) {
  5056. css = 'drag-handle-init ' + config.dragClass;
  5057. btnDrag = self._getLayoutTemplate('actionDrag').setTokens({
  5058. 'dragClass': css,
  5059. 'dragTitle': config.dragTitle,
  5060. 'dragIcon': config.dragIcon
  5061. });
  5062. }
  5063. return template.setTokens({
  5064. 'delete': btnDelete,
  5065. 'upload': btnUpload,
  5066. 'download': btnDownload,
  5067. 'zoom': btnZoom,
  5068. 'drag': btnDrag,
  5069. 'other': otherButtons
  5070. });
  5071. },
  5072. _browse: function (e) {
  5073. var self = this;
  5074. if (e && e.isDefaultPrevented() || !self._raise('filebrowse')) {
  5075. return;
  5076. }
  5077. if (self.isError && !self.isAjaxUpload) {
  5078. self.clear();
  5079. }
  5080. if (self.focusCaptionOnBrowse) {
  5081. self.$captionContainer.focus();
  5082. }
  5083. },
  5084. _change: function (e) {
  5085. var self = this;
  5086. $(document.body).off('focusin.fileinput focusout.fileinput');
  5087. if (self.changeTriggered) {
  5088. return;
  5089. }
  5090. self._setLoading('show');
  5091. var $el = self.$element, isDragDrop = arguments.length > 1, isAjaxUpload = self.isAjaxUpload,
  5092. tfiles, files = isDragDrop ? arguments[1] : $el[0].files, ctr = self.fileManager.count(),
  5093. total, initCount, len, isSingleUpl = $h.isEmpty($el.attr('multiple')),
  5094. maxCount = !isAjaxUpload && isSingleUpl ? 1 : self.maxFileCount, maxTotCount = self.maxTotalFileCount,
  5095. inclAll = maxTotCount > 0 && maxTotCount > maxCount, flagSingle = (isSingleUpl && ctr > 0),
  5096. throwError = function (mesg, file, previewId, index) {
  5097. var p1 = $.extend(true, {}, self._getOutData(null, {}, {}, files), {id: previewId, index: index}),
  5098. p2 = {id: previewId, index: index, file: file, files: files};
  5099. self.isPersistentError = true;
  5100. self._setLoading('hide');
  5101. return isAjaxUpload ? self._showFileError(mesg, p1) : self._showError(mesg, p2);
  5102. },
  5103. maxCountCheck = function (n, m, all) {
  5104. var msg = all ? self.msgTotalFilesTooMany : self.msgFilesTooMany;
  5105. msg = msg.replace('{m}', m).replace('{n}', n);
  5106. self.isError = throwError(msg, null, null, null);
  5107. self.$captionContainer.removeClass('icon-visible');
  5108. self._setCaption('', true);
  5109. self.$container.removeClass('file-input-new file-input-ajax-new');
  5110. };
  5111. self.reader = null;
  5112. self._resetUpload();
  5113. self._hideFileIcon();
  5114. if (self.dropZoneEnabled) {
  5115. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  5116. }
  5117. if (!isAjaxUpload) {
  5118. if (e.target && e.target.files === undefined) {
  5119. files = e.target.value ? [{name: e.target.value.replace(/^.+\\/, '')}] : [];
  5120. } else {
  5121. files = e.target.files || {};
  5122. }
  5123. }
  5124. tfiles = files;
  5125. if ($h.isEmpty(tfiles) || tfiles.length === 0) {
  5126. if (!isAjaxUpload) {
  5127. self.clear();
  5128. }
  5129. self._raise('fileselectnone');
  5130. return;
  5131. }
  5132. self._resetErrors();
  5133. len = tfiles.length;
  5134. initCount = isAjaxUpload ? (self.fileManager.count() + len) : len;
  5135. total = self._getFileCount(initCount, inclAll ? false : undefined);
  5136. if (maxCount > 0 && total > maxCount) {
  5137. if (!self.autoReplace || len > maxCount) {
  5138. maxCountCheck((self.autoReplace && len > maxCount ? len : total), maxCount);
  5139. return;
  5140. }
  5141. if (total > maxCount) {
  5142. self._resetPreviewThumbs(isAjaxUpload);
  5143. }
  5144. } else {
  5145. if (inclAll) {
  5146. total = self._getFileCount(initCount, true);
  5147. if (maxTotCount > 0 && total > maxTotCount) {
  5148. if (!self.autoReplace || len > maxCount) {
  5149. maxCountCheck((self.autoReplace && len > maxTotCount ? len : total), maxTotCount, true);
  5150. return;
  5151. }
  5152. if (total > maxCount) {
  5153. self._resetPreviewThumbs(isAjaxUpload);
  5154. }
  5155. }
  5156. }
  5157. if (!isAjaxUpload || flagSingle) {
  5158. self._resetPreviewThumbs(false);
  5159. if (flagSingle) {
  5160. self.clearFileStack();
  5161. }
  5162. } else {
  5163. if (isAjaxUpload && ctr === 0 && (!self.previewCache.count(true) || self.overwriteInitial)) {
  5164. self._resetPreviewThumbs(true);
  5165. }
  5166. }
  5167. }
  5168. self.readFiles(tfiles);
  5169. self._setLoading('hide');
  5170. },
  5171. _abort: function (params) {
  5172. var self = this, data;
  5173. if (self.ajaxAborted && typeof self.ajaxAborted === 'object' && self.ajaxAborted.message !== undefined) {
  5174. data = $.extend(true, {}, self._getOutData(null), params);
  5175. data.abortData = self.ajaxAborted.data || {};
  5176. data.abortMessage = self.ajaxAborted.message;
  5177. self._setProgress(101, self.$progress, self.msgCancelled);
  5178. self._showFileError(self.ajaxAborted.message, data, 'filecustomerror');
  5179. self.cancel();
  5180. self.unlock();
  5181. return true;
  5182. }
  5183. return !!self.ajaxAborted;
  5184. },
  5185. _resetFileStack: function () {
  5186. var self = this, i = 0;
  5187. self._getThumbs().each(function () {
  5188. var $thumb = $(this), ind = $thumb.attr('data-fileindex'), pid = $thumb.attr('id');
  5189. if (ind === '-1' || ind === -1) {
  5190. return;
  5191. }
  5192. if (!self._getThumbFile($thumb)) {
  5193. $thumb.attr({'data-fileindex': i});
  5194. i++;
  5195. } else {
  5196. $thumb.attr({'data-fileindex': '-1'});
  5197. }
  5198. self._getZoom(pid).attr({
  5199. 'data-fileindex': $thumb.attr('data-fileindex')
  5200. });
  5201. });
  5202. },
  5203. _isFileSelectionValid: function (cnt) {
  5204. var self = this;
  5205. cnt = cnt || 0;
  5206. if (self.required && !self.getFilesCount()) {
  5207. self.$errorContainer.html('');
  5208. self._showFileError(self.msgFileRequired);
  5209. return false;
  5210. }
  5211. if (self.minFileCount > 0 && self._getFileCount(cnt) < self.minFileCount) {
  5212. self._noFilesError({});
  5213. return false;
  5214. }
  5215. return true;
  5216. },
  5217. _canPreview: function (file) {
  5218. var self = this;
  5219. if (!file || !self.showPreview || !self.$preview || !self.$preview.length) {
  5220. return false;
  5221. }
  5222. var name = file.name || '', type = file.type || '', size = (file.size || 0) / self.bytesToKB,
  5223. cat = self._parseFileType(type, name), allowedTypes, allowedMimes, allowedExts, skipPreview,
  5224. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes,
  5225. exts = self.allowedPreviewExtensions || [], dTypes = self.disabledPreviewTypes,
  5226. dMimes = self.disabledPreviewMimeTypes, dExts = self.disabledPreviewExtensions || [],
  5227. maxSize = self.maxFilePreviewSize && parseFloat(self.maxFilePreviewSize) || 0,
  5228. expAllExt = new RegExp('\\.(' + exts.join('|') + ')$', 'i'),
  5229. expDisExt = new RegExp('\\.(' + dExts.join('|') + ')$', 'i');
  5230. allowedTypes = !types || types.indexOf(cat) !== -1;
  5231. allowedMimes = !mimes || mimes.indexOf(type) !== -1;
  5232. allowedExts = !exts.length || $h.compare(name, expAllExt);
  5233. skipPreview = (dTypes && dTypes.indexOf(cat) !== -1) || (dMimes && dMimes.indexOf(type) !== -1) ||
  5234. (dExts.length && $h.compare(name, expDisExt)) || (maxSize && !isNaN(maxSize) && size > maxSize);
  5235. return !skipPreview && (allowedTypes || allowedMimes || allowedExts);
  5236. },
  5237. addToStack: function (file, id) {
  5238. this.fileManager.add(file, id);
  5239. },
  5240. clearFileStack: function () {
  5241. var self = this;
  5242. self.fileManager.clear();
  5243. self._initResumableUpload();
  5244. if (self.enableResumableUpload) {
  5245. if (self.showPause === null) {
  5246. self.showPause = true;
  5247. }
  5248. if (self.showCancel === null) {
  5249. self.showCancel = false;
  5250. }
  5251. } else {
  5252. self.showPause = false;
  5253. if (self.showCancel === null) {
  5254. self.showCancel = true;
  5255. }
  5256. }
  5257. return self.$element;
  5258. },
  5259. getFileStack: function () {
  5260. return this.fileManager.stack;
  5261. },
  5262. getFileList: function () {
  5263. return this.fileManager.list();
  5264. },
  5265. getFilesSize: function () {
  5266. return this.fileManager.getTotalSize();
  5267. },
  5268. getFilesCount: function (includeInitial) {
  5269. var self = this, len = self.isAjaxUpload ? self.fileManager.count() : self._inputFileCount();
  5270. if (includeInitial) {
  5271. len += self.previewCache.count(true);
  5272. }
  5273. return self._getFileCount(len);
  5274. },
  5275. _initCapStatus: function (status) {
  5276. var self = this, $cap = self.$caption;
  5277. $cap.removeClass('is-valid file-processing');
  5278. if (!status) {
  5279. return;
  5280. }
  5281. if (status === 'processing') {
  5282. $cap.addClass('file-processing');
  5283. } else {
  5284. $cap.addClass('is-valid');
  5285. }
  5286. },
  5287. _setLoading: function (type) {
  5288. var self = this;
  5289. self.$previewStatus.html(type === 'hide' ? '' : self.msgProcessing);
  5290. self.$container.removeClass('file-thumb-loading');
  5291. self._initCapStatus(type === 'hide' ? '' : 'processing');
  5292. if (type !== 'hide') {
  5293. if (self.dropZoneEnabled) {
  5294. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  5295. }
  5296. self.$container.addClass('file-thumb-loading');
  5297. }
  5298. },
  5299. _initFileSelected: function () {
  5300. var self = this, $el = self.$element, $body = $(document.body), ev = 'focusin.fileinput focusout.fileinput';
  5301. if ($body.length) {
  5302. $body.off(ev).on('focusout.fileinput', function () {
  5303. self._setLoading('show');
  5304. }).on('focusin.fileinput', function () {
  5305. setTimeout(function () {
  5306. if (!$el.val()) {
  5307. self._setLoading('hide');
  5308. self._setFileDropZoneTitle();
  5309. }
  5310. $body.off(ev);
  5311. }, 2500);
  5312. });
  5313. } else {
  5314. self._setLoading('hide');
  5315. }
  5316. },
  5317. readFiles: function (files) {
  5318. this.reader = new FileReader();
  5319. var self = this, reader = self.reader, $container = self.$previewContainer,
  5320. $status = self.$previewStatus, msgLoading = self.msgLoading, msgProgress = self.msgProgress,
  5321. previewInitId = self.previewInitId, numFiles = files.length, settings = self.fileTypeSettings,
  5322. readFile, fileTypes = self.allowedFileTypes, typLen = fileTypes ? fileTypes.length : 0,
  5323. fileExt = self.allowedFileExtensions, strExt = $h.isEmpty(fileExt) ? '' : fileExt.join(', '),
  5324. throwError = function (msg, file, previewId, index, fileId) {
  5325. var $thumb, p1 = $.extend(true, {}, self._getOutData(null, {}, {}, files),
  5326. {id: previewId, index: index, fileId: fileId}),
  5327. p2 = {id: previewId, index: index, fileId: fileId, file: file, files: files};
  5328. self._previewDefault(file, true);
  5329. $thumb = self._getFrame(previewId, true);
  5330. self._setLoading('hide');
  5331. if (self.isAjaxUpload) {
  5332. setTimeout(function () {
  5333. readFile(index + 1);
  5334. }, self.processDelay);
  5335. } else {
  5336. self.unlock();
  5337. numFiles = 0;
  5338. }
  5339. if (self.removeFromPreviewOnError && $thumb.length) {
  5340. $thumb.remove();
  5341. } else {
  5342. self._initFileActions();
  5343. $thumb.find('.kv-file-upload').remove();
  5344. }
  5345. self.isPersistentError = true;
  5346. self.isError = self.isAjaxUpload ? self._showFileError(msg, p1) : self._showError(msg, p2);
  5347. self._updateFileDetails(numFiles);
  5348. };
  5349. self.fileManager.clearImages();
  5350. $.each(files, function (key, file) {
  5351. var func = self.fileTypeSettings.image;
  5352. if (func && func(file.type)) {
  5353. self.fileManager.totalImages++;
  5354. }
  5355. });
  5356. readFile = function (i) {
  5357. var $error = self.$errorContainer, errors, fm = self.fileManager;
  5358. if (i >= numFiles) {
  5359. self.unlock();
  5360. if (self.duplicateErrors.length) {
  5361. errors = '<li>' + self.duplicateErrors.join('</li><li>') + '</li>';
  5362. if ($error.find('ul').length === 0) {
  5363. $h.setHtml($error, self.errorCloseButton + '<ul>' + errors + '</ul>');
  5364. } else {
  5365. $error.find('ul').append(errors);
  5366. }
  5367. $error.fadeIn(self.fadeDelay);
  5368. self._handler($error.find('.kv-error-close'), 'click', function () {
  5369. $error.fadeOut(self.fadeDelay);
  5370. });
  5371. self.duplicateErrors = [];
  5372. }
  5373. if (self.isAjaxUpload) {
  5374. self._raise('filebatchselected', [fm.stack]);
  5375. if (fm.count() === 0 && !self.isError) {
  5376. self.reset();
  5377. }
  5378. } else {
  5379. self._raise('filebatchselected', [files]);
  5380. }
  5381. $container.removeClass('file-thumb-loading');
  5382. self._initCapStatus('valid');
  5383. $status.html('');
  5384. return;
  5385. }
  5386. self.lock(true);
  5387. var file = files[i], id = self._getFileId(file), previewId = previewInitId + '-' + id, fSizeKB, j, msg,
  5388. fnImage = settings.image, typ, chk, typ1, typ2,
  5389. caption = self._getFileName(file, ''), fileSize = (file && file.size || 0) / self.bytesToKB,
  5390. fileExtExpr = '', previewData = $h.createObjectURL(file), fileCount = 0,
  5391. strTypes = '', fileId, canLoad, fileReaderAborted = false,
  5392. func, knownTypes = 0, isImage, txtFlag, processFileLoaded = function () {
  5393. var isImageResized = !!fm.loadedImages[id], msg = msgProgress.setTokens({
  5394. 'index': i + 1,
  5395. 'files': numFiles,
  5396. 'percent': 50,
  5397. 'name': caption
  5398. });
  5399. setTimeout(function () {
  5400. $status.html(msg);
  5401. self._updateFileDetails(numFiles);
  5402. readFile(i + 1);
  5403. }, self.processDelay);
  5404. if (self._raise('fileloaded', [file, previewId, id, i, reader]) && self.isAjaxUpload) {
  5405. if (!isImageResized) {
  5406. fm.add(file);
  5407. }
  5408. } else {
  5409. if (isImageResized) {
  5410. fm.removeFile(id);
  5411. }
  5412. }
  5413. };
  5414. if (!file) {
  5415. return;
  5416. }
  5417. fileId = fm.getId(file);
  5418. if (typLen > 0) {
  5419. for (j = 0; j < typLen; j++) {
  5420. typ1 = fileTypes[j];
  5421. typ2 = self.msgFileTypes[typ1] || typ1;
  5422. strTypes += j === 0 ? typ2 : ', ' + typ2;
  5423. }
  5424. }
  5425. if (caption === false) {
  5426. readFile(i + 1);
  5427. return;
  5428. }
  5429. if (caption.length === 0) {
  5430. msg = self.msgInvalidFileName.replace('{name}', $h.htmlEncode($h.getFileName(file), '[unknown]'));
  5431. throwError(msg, file, previewId, i, fileId);
  5432. return;
  5433. }
  5434. if (!$h.isEmpty(fileExt)) {
  5435. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  5436. }
  5437. fSizeKB = fileSize.toFixed(2);
  5438. if (self.isAjaxUpload && fm.exists(fileId) || self._getFrame(previewId, true).length) {
  5439. var p2 = {id: previewId, index: i, fileId: fileId, file: file, files: files};
  5440. msg = self.msgDuplicateFile.setTokens({name: caption, size: fSizeKB});
  5441. if (self.isAjaxUpload) {
  5442. self.duplicateErrors.push(msg);
  5443. self.isDuplicateError = true;
  5444. self._raise('fileduplicateerror', [file, fileId, caption, fSizeKB, previewId, i]);
  5445. readFile(i + 1);
  5446. self._updateFileDetails(numFiles);
  5447. } else {
  5448. self._showError(msg, p2);
  5449. self.unlock();
  5450. numFiles = 0;
  5451. self._clearFileInput();
  5452. self.reset();
  5453. self._updateFileDetails(numFiles);
  5454. }
  5455. return;
  5456. }
  5457. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  5458. msg = self.msgSizeTooLarge.setTokens({
  5459. 'name': caption,
  5460. 'size': fSizeKB,
  5461. 'maxSize': self.maxFileSize
  5462. });
  5463. throwError(msg, file, previewId, i, fileId);
  5464. return;
  5465. }
  5466. if (self.minFileSize !== null && fileSize <= $h.getNum(self.minFileSize)) {
  5467. msg = self.msgSizeTooSmall.setTokens({
  5468. 'name': caption,
  5469. 'size': fSizeKB,
  5470. 'minSize': self.minFileSize
  5471. });
  5472. throwError(msg, file, previewId, i, fileId);
  5473. return;
  5474. }
  5475. if (!$h.isEmpty(fileTypes) && $h.isArray(fileTypes)) {
  5476. for (j = 0; j < fileTypes.length; j += 1) {
  5477. typ = fileTypes[j];
  5478. func = settings[typ];
  5479. fileCount += !func || (typeof func !== 'function') ? 0 : (func(file.type,
  5480. $h.getFileName(file)) ? 1 : 0);
  5481. }
  5482. if (fileCount === 0) {
  5483. msg = self.msgInvalidFileType.setTokens({name: caption, types: strTypes});
  5484. throwError(msg, file, previewId, i, fileId);
  5485. return;
  5486. }
  5487. }
  5488. if (fileCount === 0 && !$h.isEmpty(fileExt) && $h.isArray(fileExt) && !$h.isEmpty(fileExtExpr)) {
  5489. chk = $h.compare(caption, fileExtExpr);
  5490. fileCount += $h.isEmpty(chk) ? 0 : chk.length;
  5491. if (fileCount === 0) {
  5492. msg = self.msgInvalidFileExtension.setTokens({name: caption, extensions: strExt});
  5493. throwError(msg, file, previewId, i, fileId);
  5494. return;
  5495. }
  5496. }
  5497. if (!self._canPreview(file)) {
  5498. canLoad = self.isAjaxUpload && self._raise('filebeforeload', [file, i, reader]);
  5499. if (self.isAjaxUpload && canLoad) {
  5500. fm.add(file);
  5501. }
  5502. if (self.showPreview && canLoad) {
  5503. $container.addClass('file-thumb-loading');
  5504. self._initCapStatus('processing');
  5505. self._previewDefault(file);
  5506. self._initFileActions();
  5507. }
  5508. setTimeout(function () {
  5509. if (canLoad) {
  5510. self._updateFileDetails(numFiles);
  5511. }
  5512. readFile(i + 1);
  5513. self._raise('fileloaded', [file, previewId, id, i]);
  5514. }, 10);
  5515. return;
  5516. }
  5517. isImage = fnImage(file.type, caption);
  5518. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  5519. $container.addClass('file-thumb-loading');
  5520. self._initCapStatus('processing');
  5521. reader.onerror = function (evt) {
  5522. self._errorHandler(evt, caption);
  5523. };
  5524. reader.onload = function (theFile) {
  5525. var hex, fileInfo, uint, byte, bytes = [], contents, mime, readImage = function () {
  5526. var newReader = new FileReader();
  5527. newReader.onerror = function (theFileNew) {
  5528. self._errorHandler(theFileNew, caption);
  5529. };
  5530. newReader.onload = function (theFileNew) {
  5531. if (self.isAjaxUpload && !self._raise('filebeforeload', [file, i, reader])) {
  5532. fileReaderAborted = true;
  5533. self._resetCaption();
  5534. reader.abort();
  5535. $status.html('');
  5536. $container.removeClass('file-thumb-loading');
  5537. self._initCapStatus('valid');
  5538. self.enable();
  5539. return;
  5540. }
  5541. self._previewFile(i, file, theFileNew, previewData, fileInfo);
  5542. self._initFileActions();
  5543. processFileLoaded();
  5544. };
  5545. newReader.readAsDataURL(file);
  5546. };
  5547. fileInfo = {'name': caption, 'type': file.type};
  5548. $.each(settings, function (k, f) {
  5549. if (k !== 'object' && k !== 'other' && typeof f === 'function' && f(file.type, caption)) {
  5550. knownTypes++;
  5551. }
  5552. });
  5553. if (knownTypes === 0) { // auto detect mime types from content if no known file types detected
  5554. uint = new Uint8Array(theFile.target.result);
  5555. for (j = 0; j < uint.length; j++) {
  5556. byte = uint[j].toString(16);
  5557. bytes.push(byte);
  5558. }
  5559. hex = bytes.join('').toLowerCase().substring(0, 8);
  5560. mime = $h.getMimeType(hex, '', '');
  5561. if ($h.isEmpty(mime)) { // look for ascii text content
  5562. contents = $h.arrayBuffer2String(reader.result);
  5563. mime = $h.isSvg(contents) ? 'image/svg+xml' : $h.getMimeType(hex, contents, file.type);
  5564. }
  5565. fileInfo = {'name': caption, 'type': mime};
  5566. isImage = fnImage(mime, '');
  5567. if (isImage) {
  5568. readImage(txtFlag);
  5569. return;
  5570. }
  5571. }
  5572. if (self.isAjaxUpload && !self._raise('filebeforeload', [file, i, reader])) {
  5573. fileReaderAborted = true;
  5574. self._resetCaption();
  5575. reader.abort();
  5576. $status.html('');
  5577. $container.removeClass('file-thumb-loading');
  5578. self._initCapStatus('valid');
  5579. self.enable();
  5580. return;
  5581. }
  5582. self._previewFile(i, file, theFile, previewData, fileInfo);
  5583. self._initFileActions();
  5584. processFileLoaded();
  5585. };
  5586. reader.onprogress = function (data) {
  5587. if (data.lengthComputable) {
  5588. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  5589. msg = msgProgress.setTokens({
  5590. 'index': i + 1,
  5591. 'files': numFiles,
  5592. 'percent': progress,
  5593. 'name': caption
  5594. });
  5595. setTimeout(function () {
  5596. if (!fileReaderAborted) {
  5597. $status.html(msg);
  5598. }
  5599. }, self.processDelay);
  5600. }
  5601. };
  5602. if (isImage) {
  5603. reader.readAsDataURL(file);
  5604. } else {
  5605. reader.readAsArrayBuffer(file);
  5606. }
  5607. };
  5608. readFile(0);
  5609. self._updateFileDetails(numFiles);
  5610. },
  5611. lock: function (selectMode) {
  5612. var self = this, $container = self.$container;
  5613. self._resetErrors();
  5614. self.disable();
  5615. if (!selectMode && self.showCancel) {
  5616. $container.find('.fileinput-cancel').show();
  5617. }
  5618. if (!selectMode && self.showPause) {
  5619. $container.find('.fileinput-pause').show();
  5620. }
  5621. self._initCapStatus('processing');
  5622. self._raise('filelock', [self.fileManager.stack, self._getExtraData()]);
  5623. return self.$element;
  5624. },
  5625. unlock: function (reset) {
  5626. var self = this, $container = self.$container;
  5627. if (reset === undefined) {
  5628. reset = true;
  5629. }
  5630. self.enable();
  5631. $container.removeClass('is-locked');
  5632. if (self.showCancel) {
  5633. $container.find('.fileinput-cancel').hide();
  5634. }
  5635. if (self.showPause) {
  5636. $container.find('.fileinput-pause').hide();
  5637. }
  5638. if (reset) {
  5639. self._resetFileStack();
  5640. }
  5641. self._initCapStatus();
  5642. self._raise('fileunlock', [self.fileManager.stack, self._getExtraData()]);
  5643. return self.$element;
  5644. },
  5645. resume: function () {
  5646. var self = this, fm = self.fileManager, flag = false, rm = self.resumableManager;
  5647. fm.bpsLog = [];
  5648. fm.bps = 0;
  5649. if (!self.enableResumableUpload) {
  5650. return self.$element;
  5651. }
  5652. if (self.paused) {
  5653. self._toggleResumableProgress(self.progressPauseTemplate, self.msgUploadResume);
  5654. } else {
  5655. flag = true;
  5656. }
  5657. self.paused = false;
  5658. if (flag) {
  5659. self._toggleResumableProgress(self.progressInfoTemplate, self.msgUploadBegin);
  5660. }
  5661. setTimeout(function () {
  5662. rm.upload();
  5663. }, self.processDelay);
  5664. return self.$element;
  5665. },
  5666. paste: function (e) {
  5667. var self = this, ev = e.originalEvent, files = ev.clipboardData && ev.clipboardData.files || null;
  5668. if (files) {
  5669. self._dropFiles(e, files);
  5670. }
  5671. return self.$element;
  5672. },
  5673. pause: function () {
  5674. var self = this, rm = self.resumableManager, xhr = self.ajaxRequests, len = xhr.length, i,
  5675. pct = rm.getProgress(), actions = self.fileActionSettings, tm = self.taskManager,
  5676. pool = tm.getPool(rm.id);
  5677. if (!self.enableResumableUpload) {
  5678. return self.$element;
  5679. } else {
  5680. if (pool) {
  5681. pool.cancel();
  5682. }
  5683. }
  5684. self._raise('fileuploadpaused', [self.fileManager, rm]);
  5685. if (len > 0) {
  5686. for (i = 0; i < len; i += 1) {
  5687. self.paused = true;
  5688. xhr[i].abort();
  5689. }
  5690. }
  5691. if (self.showPreview) {
  5692. self._getThumbs().each(function () {
  5693. var $thumb = $(this), t = self._getLayoutTemplate('stats'), stats,
  5694. $indicator = $thumb.find('.file-upload-indicator');
  5695. $thumb.removeClass('file-uploading');
  5696. if ($indicator.attr('title') === actions.indicatorLoadingTitle) {
  5697. self._setThumbStatus($thumb, 'Paused');
  5698. stats = t.setTokens({pendingTime: self.msgPaused, uploadSpeed: ''});
  5699. self.paused = true;
  5700. self._setProgress(pct, $thumb.find('.file-thumb-progress'), pct + '%', stats);
  5701. }
  5702. if (!self._getThumbFile($thumb)) {
  5703. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  5704. }
  5705. });
  5706. }
  5707. self._setProgress(101, self.$progress, self.msgPaused);
  5708. return self.$element;
  5709. },
  5710. cancel: function () {
  5711. var self = this, xhr = self.ajaxRequests,
  5712. rm = self.resumableManager, tm = self.taskManager,
  5713. pool = rm ? tm.getPool(rm.id) : undefined, len = xhr.length, i;
  5714. if (self.enableResumableUpload && pool) {
  5715. pool.cancel().done(function () {
  5716. self._setProgressCancelled();
  5717. });
  5718. rm.reset();
  5719. self._raise('fileuploadcancelled', [self.fileManager, rm]);
  5720. } else {
  5721. self._raise('fileuploadcancelled', [self.fileManager]);
  5722. }
  5723. self._initAjax();
  5724. if (len > 0) {
  5725. for (i = 0; i < len; i += 1) {
  5726. self.cancelling = true;
  5727. xhr[i].abort();
  5728. }
  5729. }
  5730. self._getThumbs().each(function () {
  5731. var $thumb = $(this), $prog = $thumb.find('.file-thumb-progress');
  5732. $thumb.removeClass('file-uploading');
  5733. self._setProgress(0, $prog);
  5734. $prog.hide();
  5735. if (!self._getThumbFile($thumb)) {
  5736. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  5737. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  5738. }
  5739. self.unlock();
  5740. });
  5741. setTimeout(function () {
  5742. self._setProgressCancelled();
  5743. }, self.processDelay);
  5744. return self.$element;
  5745. },
  5746. clear: function () {
  5747. var self = this, cap;
  5748. if (!self._raise('fileclear')) {
  5749. return;
  5750. }
  5751. self.$btnUpload.removeAttr('disabled');
  5752. self._getThumbs().find('video,audio,img').each(function () {
  5753. $h.cleanMemory($(this));
  5754. });
  5755. self._clearFileInput();
  5756. self._resetUpload();
  5757. self.clearFileStack();
  5758. self.isDuplicateError = false;
  5759. self.isPersistentError = false;
  5760. self._resetErrors(true);
  5761. if (self._hasInitialPreview()) {
  5762. self._showFileIcon();
  5763. self._resetPreview();
  5764. self._initPreviewActions();
  5765. self.$container.removeClass('file-input-new');
  5766. } else {
  5767. self._getThumbs().each(function () {
  5768. self._clearObjects($(this));
  5769. });
  5770. if (self.isAjaxUpload) {
  5771. self.previewCache.data = {};
  5772. }
  5773. self.$preview.html('');
  5774. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  5775. self.$caption.attr('title', '').val(cap);
  5776. $h.addCss(self.$container, 'file-input-new');
  5777. self._validateDefaultPreview();
  5778. }
  5779. if (self.$container.find($h.FRAMES).length === 0) {
  5780. if (!self._initCaption()) {
  5781. self.$captionContainer.removeClass('icon-visible');
  5782. }
  5783. }
  5784. self._hideFileIcon();
  5785. if (self.focusCaptionOnClear) {
  5786. self.$captionContainer.focus();
  5787. }
  5788. self._setFileDropZoneTitle();
  5789. self._raise('filecleared');
  5790. return self.$element;
  5791. },
  5792. reset: function () {
  5793. var self = this;
  5794. if (!self._raise('filereset')) {
  5795. return;
  5796. }
  5797. self.lastProgress = 0;
  5798. self._resetPreview();
  5799. self.$container.find('.fileinput-filename').text('');
  5800. $h.addCss(self.$container, 'file-input-new');
  5801. if (self.getFrames().length) {
  5802. self.$container.removeClass('file-input-new');
  5803. }
  5804. self.clearFileStack();
  5805. self._setFileDropZoneTitle();
  5806. return self.$element;
  5807. },
  5808. disable: function () {
  5809. var self = this, $container = self.$container;
  5810. self.isDisabled = true;
  5811. self._raise('filedisabled');
  5812. self.$element.attr('disabled', 'disabled');
  5813. $container.addClass('is-locked');
  5814. $h.addCss($container.find('.btn-file'), 'disabled');
  5815. $container.find('.kv-fileinput-caption').addClass('file-caption-disabled');
  5816. $container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button')
  5817. .attr('disabled', true);
  5818. self._initDragDrop();
  5819. return self.$element;
  5820. },
  5821. enable: function () {
  5822. var self = this, $container = self.$container;
  5823. self.isDisabled = false;
  5824. self._raise('fileenabled');
  5825. self.$element.removeAttr('disabled');
  5826. $container.removeClass('is-locked');
  5827. $container.find('.kv-fileinput-caption').removeClass('file-caption-disabled');
  5828. $container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button')
  5829. .removeAttr('disabled');
  5830. $container.find('.btn-file').removeClass('disabled');
  5831. self._initDragDrop();
  5832. return self.$element;
  5833. },
  5834. upload: function () {
  5835. var self = this, fm = self.fileManager, totLen = fm.count(), i, outData,
  5836. hasExtraData = !$.isEmptyObject(self._getExtraData());
  5837. fm.bpsLog = [];
  5838. fm.bps = 0;
  5839. if (!self.isAjaxUpload || self.isDisabled || !self._isFileSelectionValid(totLen)) {
  5840. return;
  5841. }
  5842. self.lastProgress = 0;
  5843. self._resetUpload();
  5844. if (totLen === 0 && !hasExtraData) {
  5845. self._showFileError(self.msgUploadEmpty);
  5846. return;
  5847. }
  5848. self.cancelling = false;
  5849. self._showProgress();
  5850. self.lock();
  5851. if (totLen === 0 && hasExtraData) {
  5852. self._setProgress(2);
  5853. self._uploadExtraOnly();
  5854. return;
  5855. }
  5856. if (self.enableResumableUpload) {
  5857. return self.resume();
  5858. }
  5859. if (self.uploadAsync || self.enableResumableUpload) {
  5860. outData = self._getOutData(null);
  5861. if (!self._checkBatchPreupload(outData)) {
  5862. return;
  5863. }
  5864. self.fileBatchCompleted = false;
  5865. self.uploadCache = [];
  5866. $.each(self.getFileStack(), function (id) {
  5867. var previewId = self._getThumbId(id);
  5868. self.uploadCache.push({id: previewId, content: null, config: null, tags: null, append: true});
  5869. });
  5870. self.$preview.find('.file-preview-initial').removeClass($h.SORT_CSS);
  5871. self._initSortable();
  5872. }
  5873. self._setProgress(2);
  5874. self.hasInitData = false;
  5875. if (self.uploadAsync) {
  5876. i = 0;
  5877. $.each(self.getFileStack(), function (id) {
  5878. self._uploadSingle(i, id, true);
  5879. i++;
  5880. });
  5881. return;
  5882. }
  5883. self._uploadBatch();
  5884. return self.$element;
  5885. },
  5886. destroy: function () {
  5887. var self = this, $form = self.$form, $cont = self.$container, $el = self.$element, ns = self.namespace;
  5888. $(document).off(ns);
  5889. $(window).off(ns);
  5890. if ($form && $form.length) {
  5891. $form.off(ns);
  5892. }
  5893. if (self.isAjaxUpload) {
  5894. self._clearFileInput();
  5895. }
  5896. self._cleanup();
  5897. self._initPreviewCache();
  5898. $el.insertBefore($cont).off(ns).removeData();
  5899. $cont.off().remove();
  5900. return $el;
  5901. },
  5902. refresh: function (options) {
  5903. var self = this, $el = self.$element;
  5904. if (typeof options !== 'object' || $h.isEmpty(options)) {
  5905. options = self.options;
  5906. } else {
  5907. options = $.extend(true, {}, self.options, options);
  5908. }
  5909. self._init(options, true);
  5910. self._listen();
  5911. return $el;
  5912. },
  5913. zoom: function (frameId) {
  5914. var self = this, $frame = self._getFrame(frameId);
  5915. self._showModal($frame);
  5916. },
  5917. getExif: function (frameId) {
  5918. var self = this, $frame = self._getFrame(frameId);
  5919. return $frame && $frame.data('exif') || null;
  5920. },
  5921. getFrames: function (cssFilter) {
  5922. var self = this, $frames;
  5923. cssFilter = cssFilter || '';
  5924. $frames = self.$preview.find($h.FRAMES + cssFilter);
  5925. if (self.reversePreviewOrder) {
  5926. $frames = $($frames.get().reverse());
  5927. }
  5928. return $frames;
  5929. },
  5930. getPreview: function () {
  5931. var self = this;
  5932. return {
  5933. content: self.initialPreview,
  5934. config: self.initialPreviewConfig,
  5935. tags: self.initialPreviewThumbTags
  5936. };
  5937. }
  5938. };
  5939. $.fn.fileinput = function (option) {
  5940. if (!$h.hasFileAPISupport() && !$h.isIE(9)) {
  5941. return;
  5942. }
  5943. var args = Array.apply(null, arguments), retvals = [];
  5944. args.shift();
  5945. this.each(function () {
  5946. var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option,
  5947. theme = options.theme || self.data('theme'), l = {}, t = {},
  5948. lang = options.language || self.data('language') || $.fn.fileinput.defaults.language || 'en', opt;
  5949. if (!data) {
  5950. if (theme) {
  5951. t = $.fn.fileinputThemes[theme] || {};
  5952. }
  5953. if (lang !== 'en' && !$h.isEmpty($.fn.fileinputLocales[lang])) {
  5954. l = $.fn.fileinputLocales[lang] || {};
  5955. }
  5956. opt = $.extend(true, {}, $.fn.fileinput.defaults, t, $.fn.fileinputLocales.en, l, options, self.data());
  5957. data = new FileInput(this, opt);
  5958. self.data('fileinput', data);
  5959. }
  5960. if (typeof option === 'string') {
  5961. retvals.push(data[option].apply(data, args));
  5962. }
  5963. });
  5964. switch (retvals.length) {
  5965. case 0:
  5966. return this;
  5967. case 1:
  5968. return retvals[0];
  5969. default:
  5970. return retvals;
  5971. }
  5972. };
  5973. var IFRAME_ATTRIBS = 'class="kv-preview-data file-preview-pdf" src="{renderer}?file={data}" {style}',
  5974. defBtnCss1 = 'btn btn-sm btn-kv ' + $h.defaultButtonCss(), defBtnCss2 = 'btn ' + $h.defaultButtonCss(true);
  5975. $.fn.fileinput.defaults = {
  5976. language: 'zh',
  5977. bytesToKB: 1024,
  5978. showCaption: true,
  5979. showBrowse: true,
  5980. showPreview: true,
  5981. showRemove: true,
  5982. showUpload: true,
  5983. showUploadStats: true,
  5984. showCancel: null,
  5985. showPause: null,
  5986. showClose: true,
  5987. showUploadedThumbs: true,
  5988. showConsoleLogs: false,
  5989. browseOnZoneClick: false,
  5990. autoReplace: false,
  5991. showDescriptionClose: true,
  5992. autoOrientImage: function () { // applicable for JPEG images only and non ios safari
  5993. var ua = window.navigator.userAgent, webkit = !!ua.match(/WebKit/i),
  5994. iOS = !!ua.match(/iP(od|ad|hone)/i), iOSSafari = iOS && webkit && !ua.match(/CriOS/i);
  5995. return !iOSSafari;
  5996. },
  5997. autoOrientImageInitial: true,
  5998. required: false,
  5999. rtl: false,
  6000. hideThumbnailContent: false,
  6001. encodeUrl: true,
  6002. focusCaptionOnBrowse: true,
  6003. focusCaptionOnClear: true,
  6004. generateFileId: null,
  6005. previewClass: '',
  6006. captionClass: '',
  6007. frameClass: 'krajee-default',
  6008. mainClass: '',
  6009. inputGroupClass: '',
  6010. mainTemplate: null,
  6011. fileSizeGetter: null,
  6012. initialCaption: '',
  6013. initialPreview: [],
  6014. initialPreviewDelimiter: '*$$*',
  6015. initialPreviewAsData: false,
  6016. initialPreviewFileType: 'image',
  6017. initialPreviewConfig: [],
  6018. initialPreviewThumbTags: [],
  6019. previewThumbTags: {},
  6020. initialPreviewShowDelete: true,
  6021. initialPreviewDownloadUrl: '',
  6022. removeFromPreviewOnError: false,
  6023. deleteUrl: '',
  6024. deleteExtraData: {},
  6025. overwriteInitial: true,
  6026. sanitizeZoomCache: function (content) {
  6027. var $container = $h.createElement(content);
  6028. $container.find('input,textarea,select,datalist,form,.file-thumbnail-footer').remove();
  6029. return $container.html();
  6030. },
  6031. previewZoomButtonIcons: {
  6032. prev: '<i class="glyphicon glyphicon-triangle-left"></i>',
  6033. next: '<i class="glyphicon glyphicon-triangle-right"></i>',
  6034. toggleheader: '<i class="glyphicon glyphicon-resize-vertical"></i>',
  6035. fullscreen: '<i class="glyphicon glyphicon-fullscreen"></i>',
  6036. borderless: '<i class="glyphicon glyphicon-resize-full"></i>',
  6037. close: '<i class="glyphicon glyphicon-remove"></i>'
  6038. },
  6039. previewZoomButtonClasses: {
  6040. prev: 'btn btn-default btn-outline-secondary btn-navigate',
  6041. next: 'btn btn-default btn-outline-secondary btn-navigate',
  6042. toggleheader: defBtnCss1,
  6043. fullscreen: defBtnCss1,
  6044. borderless: defBtnCss1,
  6045. close: defBtnCss1
  6046. },
  6047. previewTemplates: {},
  6048. previewContentTemplates: {},
  6049. preferIconicPreview: false,
  6050. preferIconicZoomPreview: false,
  6051. allowedFileTypes: null,
  6052. allowedFileExtensions: null,
  6053. allowedPreviewTypes: undefined,
  6054. allowedPreviewMimeTypes: null,
  6055. allowedPreviewExtensions: null,
  6056. disabledPreviewTypes: undefined,
  6057. disabledPreviewExtensions: ['msi', 'exe', 'com', 'zip', 'rar', 'app', 'vb', 'scr'],
  6058. disabledPreviewMimeTypes: null,
  6059. defaultPreviewContent: null,
  6060. customLayoutTags: {},
  6061. customPreviewTags: {},
  6062. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  6063. previewFileIconClass: 'file-other-icon',
  6064. previewFileIconSettings: {},
  6065. previewFileExtSettings: {},
  6066. buttonLabelClass: 'hidden-xs',
  6067. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i>&nbsp;',
  6068. browseClass: 'btn btn-primary',
  6069. removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
  6070. removeClass: defBtnCss2,
  6071. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i>',
  6072. cancelClass: defBtnCss2,
  6073. pauseIcon: '<i class="glyphicon glyphicon-pause"></i>',
  6074. pauseClass: defBtnCss2,
  6075. uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
  6076. uploadClass: defBtnCss2,
  6077. uploadUrl: null,
  6078. uploadUrlThumb: null,
  6079. uploadAsync: true,
  6080. uploadParamNames: {
  6081. chunkCount: 'chunkCount',
  6082. chunkIndex: 'chunkIndex',
  6083. chunkSize: 'chunkSize',
  6084. chunkSizeStart: 'chunkSizeStart',
  6085. chunksUploaded: 'chunksUploaded',
  6086. fileBlob: 'fileBlob',
  6087. fileId: 'fileId',
  6088. fileName: 'fileName',
  6089. fileRelativePath: 'fileRelativePath',
  6090. fileSize: 'fileSize',
  6091. retryCount: 'retryCount'
  6092. },
  6093. maxAjaxThreads: 5,
  6094. fadeDelay: 800,
  6095. processDelay: 100,
  6096. bitrateUpdateDelay: 500,
  6097. queueDelay: 10, // must be lesser than process delay
  6098. progressDelay: 0, // must be lesser than process delay
  6099. enableResumableUpload: false,
  6100. resumableUploadOptions: {
  6101. fallback: null,
  6102. testUrl: null, // used for checking status of chunks/ files previously / partially uploaded
  6103. chunkSize: 2048, // in KB
  6104. maxThreads: 4,
  6105. maxRetries: 3,
  6106. showErrorLog: true,
  6107. retainErrorHistory: true, // display complete error history always unless user explicitly resets upload
  6108. skipErrorsAndProceed: false // when set to true, files with errors will be skipped and upload will continue with other files
  6109. },
  6110. uploadExtraData: {},
  6111. zoomModalHeight: 480,
  6112. minImageWidth: null,
  6113. minImageHeight: null,
  6114. maxImageWidth: null,
  6115. maxImageHeight: null,
  6116. resizeImage: false,
  6117. resizePreference: 'width',
  6118. resizeQuality: 0.92,
  6119. resizeDefaultImageType: 'image/jpeg',
  6120. resizeIfSizeMoreThan: 0, // in KB
  6121. minFileSize: -1,
  6122. maxFileSize: 0,
  6123. maxFilePreviewSize: 25600, // 25 MB
  6124. minFileCount: 0,
  6125. maxFileCount: 0,
  6126. maxTotalFileCount: 0,
  6127. validateInitialCount: false,
  6128. msgValidationErrorClass: 'text-danger',
  6129. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  6130. msgErrorClass: 'file-error-message',
  6131. progressThumbClass: 'progress-bar progress-bar-striped active progress-bar-animated',
  6132. progressClass: 'progress-bar bg-success progress-bar-success progress-bar-striped active progress-bar-animated',
  6133. progressInfoClass: 'progress-bar bg-info progress-bar-info progress-bar-striped active progress-bar-animated',
  6134. progressCompleteClass: 'progress-bar bg-success progress-bar-success',
  6135. progressPauseClass: 'progress-bar bg-primary progress-bar-primary progress-bar-striped active progress-bar-animated',
  6136. progressErrorClass: 'progress-bar bg-danger progress-bar-danger',
  6137. progressUploadThreshold: 99,
  6138. previewFileType: 'image',
  6139. elCaptionContainer: null,
  6140. elCaptionText: null,
  6141. elPreviewContainer: null,
  6142. elPreviewImage: null,
  6143. elPreviewStatus: null,
  6144. elErrorContainer: null,
  6145. errorCloseButton: undefined,
  6146. slugCallback: null,
  6147. dropZoneEnabled: true,
  6148. dropZoneTitleClass: 'file-drop-zone-title',
  6149. fileActionSettings: {},
  6150. otherActionButtons: '',
  6151. textEncoding: 'UTF-8',
  6152. preProcessUpload: null,
  6153. ajaxSettings: {},
  6154. ajaxDeleteSettings: {},
  6155. showAjaxErrorDetails: true,
  6156. mergeAjaxCallbacks: false,
  6157. mergeAjaxDeleteCallbacks: false,
  6158. retryErrorUploads: true,
  6159. reversePreviewOrder: false,
  6160. usePdfRenderer: function () {
  6161. var isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
  6162. return !!navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/i) || isIE11;
  6163. },
  6164. pdfRendererUrl: '',
  6165. pdfRendererTemplate: '<iframe ' + IFRAME_ATTRIBS + '></iframe>',
  6166. tabIndexConfig: {
  6167. browse: 500,
  6168. remove: 500,
  6169. upload: 500,
  6170. cancel: null,
  6171. pause: null,
  6172. modal: -1
  6173. }
  6174. };
  6175. // noinspection HtmlUnknownAttribute
  6176. $.fn.fileinputLocales.en = {
  6177. sizeUnits: ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
  6178. bitRateUnits: ['B/s', 'KB/s', 'MB/s', 'GB/s', 'TB/s', 'PB/s', 'EB/s', 'ZB/s', 'YB/s'],
  6179. fileSingle: 'file',
  6180. filePlural: 'files',
  6181. browseLabel: 'Browse &hellip;',
  6182. removeLabel: 'Remove',
  6183. removeTitle: 'Clear all unprocessed files',
  6184. cancelLabel: 'Cancel',
  6185. cancelTitle: 'Abort ongoing upload',
  6186. pauseLabel: 'Pause',
  6187. pauseTitle: 'Pause ongoing upload',
  6188. uploadLabel: 'Upload',
  6189. uploadTitle: 'Upload selected files',
  6190. msgNo: 'No',
  6191. msgNoFilesSelected: 'No files selected',
  6192. msgCancelled: 'Cancelled',
  6193. msgPaused: 'Paused',
  6194. msgPlaceholder: 'Select {files} ...',
  6195. msgZoomModalHeading: 'Detailed Preview',
  6196. msgFileRequired: 'You must select a file to upload.',
  6197. msgSizeTooSmall: 'File "{name}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.',
  6198. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
  6199. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
  6200. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
  6201. msgTotalFilesTooMany: 'You can upload a maximum of <b>{m}</b> files (<b>{n}</b> files detected).',
  6202. msgFileNotFound: 'File "{name}" not found!',
  6203. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  6204. msgFileNotReadable: 'File "{name}" is not readable.',
  6205. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  6206. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  6207. msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".',
  6208. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  6209. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  6210. msgFileTypes: {
  6211. 'image': 'image',
  6212. 'html': 'HTML',
  6213. 'text': 'text',
  6214. 'video': 'video',
  6215. 'audio': 'audio',
  6216. 'flash': 'flash',
  6217. 'pdf': 'PDF',
  6218. 'object': 'object'
  6219. },
  6220. msgUploadAborted: 'The file upload was aborted',
  6221. msgUploadThreshold: 'Processing &hellip;',
  6222. msgUploadBegin: 'Initializing &hellip;',
  6223. msgUploadEnd: 'Done',
  6224. msgUploadResume: 'Resuming upload &hellip;',
  6225. msgUploadEmpty: 'No valid data available for upload.',
  6226. msgUploadError: 'Upload Error',
  6227. msgDeleteError: 'Delete Error',
  6228. msgProgressError: 'Error',
  6229. msgValidationError: 'Validation Error',
  6230. msgLoading: 'Loading file {index} of {files} &hellip;',
  6231. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  6232. msgSelected: '{n} {files} selected',
  6233. msgProcessing: 'Processing ...',
  6234. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  6235. msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
  6236. msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
  6237. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
  6238. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
  6239. msgImageResizeError: 'Could not get the image dimensions to resize.',
  6240. msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>',
  6241. msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!',
  6242. msgAjaxProgressError: '{operation} failed',
  6243. msgDuplicateFile: 'File "{name}" of same size "{size} KB" has already been selected earlier. Skipping duplicate selection.',
  6244. msgResumableUploadRetriesExceeded: 'Upload aborted beyond <b>{max}</b> retries for file <b>{file}</b>! Error Details: <pre>{error}</pre>',
  6245. msgPendingTime: '{time} remaining',
  6246. msgCalculatingTime: 'calculating time remaining',
  6247. ajaxOperations: {
  6248. deleteThumb: 'file delete',
  6249. uploadThumb: 'file upload',
  6250. uploadBatch: 'batch file upload',
  6251. uploadExtra: 'form data upload'
  6252. },
  6253. dropZoneTitle: 'Drag & drop files here &hellip;',
  6254. dropZoneClickTitle: '<br>(or click to select {files})',
  6255. previewZoomButtonTitles: {
  6256. prev: 'View previous file',
  6257. next: 'View next file',
  6258. toggleheader: 'Toggle header',
  6259. fullscreen: 'Toggle full screen',
  6260. borderless: 'Toggle borderless mode',
  6261. close: 'Close detailed preview'
  6262. }
  6263. };
  6264. $.fn.fileinputLocales.zh = {
  6265. sizeUnits: ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
  6266. bitRateUnits: ['B/s', 'KB/s', 'MB/s', 'GB/s', 'TB/s', 'PB/s', 'EB/s', 'ZB/s', 'YB/s'],
  6267. fileSingle: '文件',
  6268. filePlural: '个文件',
  6269. browseLabel: '选择 &hellip;',
  6270. removeLabel: '移除',
  6271. removeTitle: '清除选中文件',
  6272. cancelLabel: '取消',
  6273. cancelTitle: '取消进行中的上传',
  6274. pauseLabel: '暂停',
  6275. pauseTitle: '暂停上传',
  6276. uploadLabel: '上传',
  6277. uploadTitle: '上传选中文件',
  6278. msgNo: '没有',
  6279. msgNoFilesSelected: '未选择文件',
  6280. msgPaused: '已暂停',
  6281. msgCancelled: '取消',
  6282. msgPlaceholder: '选择 {files} ...',
  6283. msgZoomModalHeading: '详细预览',
  6284. msgFileRequired: '必须选择一个文件上传.',
  6285. msgSizeTooSmall: '文件 "{name}" (<b>{size} KB</b>) 必须大于限定大小 <b>{minSize} KB</b>.',
  6286. msgSizeTooLarge: '文件 "{name}" (<b>{size} KB</b>) 超过了允许大小 <b>{maxSize} KB</b>.',
  6287. msgFilesTooLess: '你必须选择最少 <b>{n}</b> {files} 来上传. ',
  6288. msgFilesTooMany: '选择的上传文件个数 <b>({n})</b> 超出最大文件的限制个数 <b>{m}</b>.',
  6289. msgTotalFilesTooMany: '你最多可以上传 <b>{m}</b> 个文件 (当前有<b>{n}</b> 个文件).',
  6290. msgFileNotFound: '文件 "{name}" 未找到!',
  6291. msgFileSecured: '安全限制,为了防止读取文件 "{name}".',
  6292. msgFileNotReadable: '文件 "{name}" 不可读.',
  6293. msgFilePreviewAborted: '取消 "{name}" 的预览.',
  6294. msgFilePreviewError: '读取 "{name}" 时出现了一个错误.',
  6295. msgInvalidFileName: '文件名 "{name}" 包含非法字符.',
  6296. msgInvalidFileType: '不正确的类型 "{name}". 只支持 "{types}" 类型的文件.',
  6297. msgInvalidFileExtension: '不正确的文件扩展名 "{name}". 只支持 "{extensions}" 的文件扩展名.',
  6298. msgFileTypes: {
  6299. 'image': 'image',
  6300. 'html': 'HTML',
  6301. 'text': 'text',
  6302. 'video': 'video',
  6303. 'audio': 'audio',
  6304. 'flash': 'flash',
  6305. 'pdf': 'PDF',
  6306. 'object': 'object'
  6307. },
  6308. msgUploadAborted: '该文件上传被中止',
  6309. msgUploadThreshold: '处理中 &hellip;',
  6310. msgUploadBegin: '正在初始化 &hellip;',
  6311. msgUploadEnd: '完成',
  6312. msgUploadResume: '继续上传 &hellip;',
  6313. msgUploadEmpty: '无效的文件上传.',
  6314. msgUploadError: '上传出错',
  6315. msgDeleteError: '删除出错',
  6316. msgProgressError: '上传出错',
  6317. msgValidationError: '验证错误',
  6318. msgLoading: '加载第 {index} 文件 共 {files} &hellip;',
  6319. msgProgress: '加载第 {index} 文件 共 {files} - {name} - {percent}% 完成.',
  6320. msgSelected: '{n} {files} 选中',
  6321. msgProcessing: '处理中 ...',
  6322. msgFoldersNotAllowed: '只支持拖拽文件! 跳过 {n} 拖拽的文件夹.',
  6323. msgImageWidthSmall: '图像文件的"{name}"的宽度必须是至少{size}像素.',
  6324. msgImageHeightSmall: '图像文件的"{name}"的高度必须至少为{size}像素.',
  6325. msgImageWidthLarge: '图像文件"{name}"的宽度不能超过{size}像素.',
  6326. msgImageHeightLarge: '图像文件"{name}"的高度不能超过{size}像素.',
  6327. msgImageResizeError: '无法获取的图像尺寸调整。',
  6328. msgImageResizeException: '调整图像大小时发生错误。<pre>{errors}</pre>',
  6329. msgAjaxError: '{operation} 发生错误. 请重试!',
  6330. msgAjaxProgressError: '{operation} 失败',
  6331. msgDuplicateFile: '文件 "{name}",大小 "{size} KB" 已经被选中.忽略相同的文件.',
  6332. msgResumableUploadRetriesExceeded: '文件 <b>{file}</b> 上传失败超过 <b>{max}</b> 次重试 ! 错误详情: <pre>{error}</pre>',
  6333. msgPendingTime: '{time} 剩余',
  6334. msgCalculatingTime: '计算剩余时间',
  6335. ajaxOperations: {
  6336. deleteThumb: '删除文件',
  6337. uploadThumb: '上传文件',
  6338. uploadBatch: '批量上传',
  6339. uploadExtra: '表单数据上传'
  6340. },
  6341. dropZoneTitle: '拖拽文件到这里 &hellip;<br>支持多文件同时上传',
  6342. dropZoneClickTitle: '<br>(或点击{files}按钮选择文件)',
  6343. fileActionSettings: {
  6344. removeTitle: '删除文件',
  6345. uploadTitle: '上传文件',
  6346. downloadTitle: '下载文件',
  6347. uploadRetryTitle: '重试',
  6348. zoomTitle: '查看详情',
  6349. dragTitle: '移动 / 重置',
  6350. indicatorNewTitle: '没有上传',
  6351. indicatorSuccessTitle: '上传',
  6352. indicatorErrorTitle: '上传错误',
  6353. indicatorPausedTitle: '上传已暂停',
  6354. indicatorLoadingTitle: '上传 &hellip;'
  6355. },
  6356. previewZoomButtonTitles: {
  6357. prev: '预览上一个文件',
  6358. next: '预览下一个文件',
  6359. toggleheader: '缩放',
  6360. fullscreen: '全屏',
  6361. borderless: '无边界模式',
  6362. close: '关闭当前预览'
  6363. }
  6364. };
  6365. $.fn.fileinput.Constructor = FileInput;
  6366. /**
  6367. * Convert automatically file inputs with class 'file' into a bootstrap fileinput control.
  6368. */
  6369. $(document).ready(function () {
  6370. var $input = $('input.file[type=file]');
  6371. if ($input.length) {
  6372. $input.fileinput();
  6373. }
  6374. });
  6375. }));