webuploader.min.js 181 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771
  1. /*! WebUploader 0.1.2 */
  2. /**
  3. * @fileOverview 让内部各个部件的代码可以用[amd](https://github.com/amdjs/amdjs-api/wiki/AMD)模块定义方式组织起来。
  4. *
  5. * AMD API 内部的简单不完全实现,请忽略。只有当WebUploader被合并成一个文件的时候才会引入。
  6. */
  7. ;(function (root, factory) {
  8. var modules = {},
  9. // 内部require, 简单不完全实现。
  10. // https://github.com/amdjs/amdjs-api/wiki/require
  11. _require = function (deps, callback) {
  12. var args, len, i
  13. // 如果deps不是数组,则直接返回指定module
  14. if (typeof deps === 'string') {
  15. return getModule(deps)
  16. } else {
  17. args = []
  18. for (len = deps.length, i = 0; i < len; i++) {
  19. args.push(getModule(deps[i]))
  20. }
  21. return callback.apply(null, args)
  22. }
  23. },
  24. // 内部define,暂时不支持不指定id.
  25. _define = function (id, deps, factory) {
  26. if (arguments.length === 2) {
  27. factory = deps
  28. deps = null
  29. }
  30. _require(deps || [], function () {
  31. setModule(id, factory, arguments)
  32. })
  33. },
  34. // 设置module, 兼容CommonJs写法。
  35. setModule = function (id, factory, args) {
  36. var module = {
  37. exports: factory
  38. },
  39. returned
  40. if (typeof factory === 'function') {
  41. args.length || (args = [_require, module.exports, module])
  42. returned = factory.apply(null, args)
  43. returned !== undefined && (module.exports = returned)
  44. }
  45. modules[id] = module.exports
  46. },
  47. // 根据id获取module
  48. getModule = function (id) {
  49. var module = modules[id] || root[id]
  50. if (!module) {
  51. throw new Error('`' + id + '` is undefined')
  52. }
  53. return module
  54. },
  55. // 将所有modules,将路径ids装换成对象。
  56. exportsTo = function (obj) {
  57. var key, host, parts, part, last, ucFirst
  58. // make the first character upper case.
  59. ucFirst = function (str) {
  60. return str && str.charAt(0).toUpperCase() + str.substr(1)
  61. }
  62. for (key in modules) {
  63. host = obj
  64. if (!modules.hasOwnProperty(key)) {
  65. continue
  66. }
  67. parts = key.split('/')
  68. last = ucFirst(parts.pop())
  69. while ((part = ucFirst(parts.shift()))) {
  70. host[part] = host[part] || {}
  71. host = host[part]
  72. }
  73. host[last] = modules[key]
  74. }
  75. },
  76. exports = factory(root, _define, _require),
  77. origin
  78. // exports every module.
  79. exportsTo(exports)
  80. if (typeof module === 'object' && typeof module.exports === 'object') {
  81. // For CommonJS and CommonJS-like environments where a proper window is present,
  82. module.exports = exports
  83. } else if (typeof define === 'function' && define.amd) {
  84. // Allow using this built library as an AMD module
  85. // in another project. That other project will only
  86. // see this AMD call, not the internal modules in
  87. // the closure below.
  88. define([], exports)
  89. } else {
  90. // Browser globals case. Just assign the
  91. // result to a property on the global.
  92. origin = root.WebUploader
  93. root.WebUploader = exports
  94. root.WebUploader.noConflict = function () {
  95. root.WebUploader = origin
  96. }
  97. }
  98. })(this, function (window, define, require) {
  99. /**
  100. * @fileOverview jQuery or Zepto
  101. */
  102. define('dollar-third', [], function () {
  103. return window.jQuery || window.Zepto
  104. })
  105. /**
  106. * @fileOverview Dom 操作相关
  107. */
  108. define('dollar', ['dollar-third'], function (_) {
  109. return _
  110. })
  111. /**
  112. * @fileOverview 使用jQuery的Promise
  113. */
  114. define('promise-third', ['dollar'], function ($) {
  115. return {
  116. Deferred: $.Deferred,
  117. when: $.when,
  118. isPromise: function (anything) {
  119. return anything && typeof anything.then === 'function'
  120. }
  121. }
  122. })
  123. /**
  124. * @fileOverview Promise/A+
  125. */
  126. define('promise', ['promise-third'], function (_) {
  127. return _
  128. })
  129. /**
  130. * @fileOverview 基础类方法。
  131. */
  132. /**
  133. * Web Uploader内部类的详细说明,以下提及的功能类,都可以在`WebUploader`这个变量中访问到。
  134. *
  135. * As you know, Web Uploader的每个文件都是用过[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD)规范中的`define`组织起来的, 每个Module都会有个module id.
  136. * 默认module id该文件的路径,而此路径将会转化成名字空间存放在WebUploader中。如:
  137. *
  138. * * module `base`:WebUploader.Base
  139. * * module `file`: WebUploader.File
  140. * * module `lib/dnd`: WebUploader.Lib.Dnd
  141. * * module `runtime/html5/dnd`: WebUploader.Runtime.Html5.Dnd
  142. *
  143. *
  144. * 以下文档将可能省略`WebUploader`前缀。
  145. * @module WebUploader
  146. * @title WebUploader API文档
  147. */
  148. define('base', ['dollar', 'promise'], function ($, promise) {
  149. var noop = function () {},
  150. call = Function.call
  151. // http://jsperf.com/uncurrythis
  152. // 反科里化
  153. function uncurryThis(fn) {
  154. return function () {
  155. return call.apply(fn, arguments)
  156. }
  157. }
  158. function bindFn(fn, context) {
  159. return function () {
  160. return fn.apply(context, arguments)
  161. }
  162. }
  163. function createObject(proto) {
  164. var f
  165. if (Object.create) {
  166. return Object.create(proto)
  167. } else {
  168. f = function () {}
  169. f.prototype = proto
  170. return new f()
  171. }
  172. }
  173. /**
  174. * 基础类,提供一些简单常用的方法。
  175. * @class Base
  176. */
  177. return {
  178. /**
  179. * @property {String} version 当前版本号。
  180. */
  181. version: '0.1.2',
  182. /**
  183. * @property {jQuery|Zepto} $ 引用依赖的jQuery或者Zepto对象。
  184. */
  185. $: $,
  186. Deferred: promise.Deferred,
  187. isPromise: promise.isPromise,
  188. when: promise.when,
  189. /**
  190. * @description 简单的浏览器检查结果。
  191. *
  192. * * `webkit` webkit版本号,如果浏览器为非webkit内核,此属性为`undefined`。
  193. * * `chrome` chrome浏览器版本号,如果浏览器为chrome,此属性为`undefined`。
  194. * * `ie` ie浏览器版本号,如果浏览器为非ie,此属性为`undefined`。**暂不支持ie10+**
  195. * * `firefox` firefox浏览器版本号,如果浏览器为非firefox,此属性为`undefined`。
  196. * * `safari` safari浏览器版本号,如果浏览器为非safari,此属性为`undefined`。
  197. * * `opera` opera浏览器版本号,如果浏览器为非opera,此属性为`undefined`。
  198. *
  199. * @property {Object} [browser]
  200. */
  201. browser: (function (ua) {
  202. var ret = {},
  203. webkit = ua.match(/WebKit\/([\d.]+)/),
  204. chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/),
  205. ie =
  206. ua.match(/MSIE\s([\d\.]+)/) ||
  207. ua.match(/(?:trident)(?:.*rv:([\w.]+))?/i),
  208. firefox = ua.match(/Firefox\/([\d.]+)/),
  209. safari = ua.match(/Safari\/([\d.]+)/),
  210. opera = ua.match(/OPR\/([\d.]+)/)
  211. webkit && (ret.webkit = parseFloat(webkit[1]))
  212. chrome && (ret.chrome = parseFloat(chrome[1]))
  213. ie && (ret.ie = parseFloat(ie[1]))
  214. firefox && (ret.firefox = parseFloat(firefox[1]))
  215. safari && (ret.safari = parseFloat(safari[1]))
  216. opera && (ret.opera = parseFloat(opera[1]))
  217. return ret
  218. })(navigator.userAgent),
  219. /**
  220. * @description 操作系统检查结果。
  221. *
  222. * * `android` 如果在android浏览器环境下,此值为对应的android版本号,否则为`undefined`。
  223. * * `ios` 如果在ios浏览器环境下,此值为对应的ios版本号,否则为`undefined`。
  224. * @property {Object} [os]
  225. */
  226. os: (function (ua) {
  227. var ret = {},
  228. // osx = !!ua.match( /\(Macintosh\; Intel / ),
  229. android = ua.match(/(?:Android);?[\s\/]+([\d.]+)?/),
  230. ios = ua.match(/(?:iPad|iPod|iPhone).*OS\s([\d_]+)/)
  231. // osx && (ret.osx = true);
  232. android && (ret.android = parseFloat(android[1]))
  233. ios && (ret.ios = parseFloat(ios[1].replace(/_/g, '.')))
  234. return ret
  235. })(navigator.userAgent),
  236. /**
  237. * 实现类与类之间的继承。
  238. * @method inherits
  239. * @grammar Base.inherits( super ) => child
  240. * @grammar Base.inherits( super, protos ) => child
  241. * @grammar Base.inherits( super, protos, statics ) => child
  242. * @param {Class} super 父类
  243. * @param {Object | Function} [protos] 子类或者对象。如果对象中包含constructor,子类将是用此属性值。
  244. * @param {Function} [protos.constructor] 子类构造器,不指定的话将创建个临时的直接执行父类构造器的方法。
  245. * @param {Object} [statics] 静态属性或方法。
  246. * @return {Class} 返回子类。
  247. * @example
  248. * function Person() {
  249. * console.log( 'Super' );
  250. * }
  251. * Person.prototype.hello = function() {
  252. * console.log( 'hello' );
  253. * };
  254. *
  255. * var Manager = Base.inherits( Person, {
  256. * world: function() {
  257. * console.log( 'World' );
  258. * }
  259. * });
  260. *
  261. * // 因为没有指定构造器,父类的构造器将会执行。
  262. * var instance = new Manager(); // => Super
  263. *
  264. * // 继承子父类的方法
  265. * instance.hello(); // => hello
  266. * instance.world(); // => World
  267. *
  268. * // 子类的__super__属性指向父类
  269. * console.log( Manager.__super__ === Person ); // => true
  270. */
  271. inherits: function (Super, protos, staticProtos) {
  272. var child
  273. if (typeof protos === 'function') {
  274. child = protos
  275. protos = null
  276. } else if (protos && protos.hasOwnProperty('constructor')) {
  277. child = protos.constructor
  278. } else {
  279. child = function () {
  280. return Super.apply(this, arguments)
  281. }
  282. }
  283. // 复制静态方法
  284. $.extend(true, child, Super, staticProtos || {})
  285. /* jshint camelcase: false */
  286. // 让子类的__super__属性指向父类。
  287. child.__super__ = Super.prototype
  288. // 构建原型,添加原型方法或属性。
  289. // 暂时用Object.create实现。
  290. child.prototype = createObject(Super.prototype)
  291. protos && $.extend(true, child.prototype, protos)
  292. return child
  293. },
  294. /**
  295. * 一个不做任何事情的方法。可以用来赋值给默认的callback.
  296. * @method noop
  297. */
  298. noop: noop,
  299. /**
  300. * 返回一个新的方法,此方法将已指定的`context`来执行。
  301. * @grammar Base.bindFn( fn, context ) => Function
  302. * @method bindFn
  303. * @example
  304. * var doSomething = function() {
  305. * console.log( this.name );
  306. * },
  307. * obj = {
  308. * name: 'Object Name'
  309. * },
  310. * aliasFn = Base.bind( doSomething, obj );
  311. *
  312. * aliasFn(); // => Object Name
  313. *
  314. */
  315. bindFn: bindFn,
  316. /**
  317. * 引用Console.log如果存在的话,否则引用一个[空函数loop](#WebUploader:Base.log)。
  318. * @grammar Base.log( args... ) => undefined
  319. * @method log
  320. */
  321. log: (function () {
  322. if (window.console) {
  323. return bindFn(console.log, console)
  324. }
  325. return noop
  326. })(),
  327. nextTick: (function () {
  328. return function (cb) {
  329. setTimeout(cb, 1)
  330. }
  331. // @bug 当浏览器不在当前窗口时就停了。
  332. // var next = window.requestAnimationFrame ||
  333. // window.webkitRequestAnimationFrame ||
  334. // window.mozRequestAnimationFrame ||
  335. // function( cb ) {
  336. // window.setTimeout( cb, 1000 / 60 );
  337. // };
  338. // // fix: Uncaught TypeError: Illegal invocation
  339. // return bindFn( next, window );
  340. })(),
  341. /**
  342. * 被[uncurrythis](http://www.2ality.com/2011/11/uncurrying-this.html)的数组slice方法。
  343. * 将用来将非数组对象转化成数组对象。
  344. * @grammar Base.slice( target, start[, end] ) => Array
  345. * @method slice
  346. * @example
  347. * function doSomthing() {
  348. * var args = Base.slice( arguments, 1 );
  349. * console.log( args );
  350. * }
  351. *
  352. * doSomthing( 'ignored', 'arg2', 'arg3' ); // => Array ["arg2", "arg3"]
  353. */
  354. slice: uncurryThis([].slice),
  355. /**
  356. * 生成唯一的ID
  357. * @method guid
  358. * @grammar Base.guid() => String
  359. * @grammar Base.guid( prefx ) => String
  360. */
  361. guid: (function () {
  362. var counter = 0
  363. return function (prefix) {
  364. var guid = (+new Date()).toString(32),
  365. i = 0
  366. for (; i < 5; i++) {
  367. guid += Math.floor(Math.random() * 65535).toString(32)
  368. }
  369. return (prefix || 'wu_') + guid + (counter++).toString(32)
  370. }
  371. })(),
  372. /**
  373. * 格式化文件大小, 输出成带单位的字符串
  374. * @method formatSize
  375. * @grammar Base.formatSize( size ) => String
  376. * @grammar Base.formatSize( size, pointLength ) => String
  377. * @grammar Base.formatSize( size, pointLength, units ) => String
  378. * @param {Number} size 文件大小
  379. * @param {Number} [pointLength=2] 精确到的小数点数。
  380. * @param {Array} [units=[ 'B', 'K', 'M', 'G', 'TB' ]] 单位数组。从字节,到千字节,一直往上指定。如果单位数组里面只指定了到了K(千字节),同时文件大小大于M, 此方法的输出将还是显示成多少K.
  381. * @example
  382. * console.log( Base.formatSize( 100 ) ); // => 100B
  383. * console.log( Base.formatSize( 1024 ) ); // => 1.00K
  384. * console.log( Base.formatSize( 1024, 0 ) ); // => 1K
  385. * console.log( Base.formatSize( 1024 * 1024 ) ); // => 1.00M
  386. * console.log( Base.formatSize( 1024 * 1024 * 1024 ) ); // => 1.00G
  387. * console.log( Base.formatSize( 1024 * 1024 * 1024, 0, ['B', 'KB', 'MB'] ) ); // => 1024MB
  388. */
  389. formatSize: function (size, pointLength, units) {
  390. var unit
  391. units = units || ['B', 'K', 'M', 'G', 'TB']
  392. while ((unit = units.shift()) && size > 1024) {
  393. size = size / 1024
  394. }
  395. return (unit === 'B' ? size : size.toFixed(pointLength || 2)) + unit
  396. }
  397. }
  398. })
  399. /**
  400. * 事件处理类,可以独立使用,也可以扩展给对象使用。
  401. * @fileOverview Mediator
  402. */
  403. define('mediator', ['base'], function (Base) {
  404. var $ = Base.$,
  405. slice = [].slice,
  406. separator = /\s+/,
  407. protos
  408. // 根据条件过滤出事件handlers.
  409. function findHandlers(arr, name, callback, context) {
  410. return $.grep(arr, function (handler) {
  411. return (
  412. handler &&
  413. (!name || handler.e === name) &&
  414. (!callback ||
  415. handler.cb === callback ||
  416. handler.cb._cb === callback) &&
  417. (!context || handler.ctx === context)
  418. )
  419. })
  420. }
  421. function eachEvent(events, callback, iterator) {
  422. // 不支持对象,只支持多个event用空格隔开
  423. $.each((events || '').split(separator), function (_, key) {
  424. iterator(key, callback)
  425. })
  426. }
  427. function triggerHanders(events, args) {
  428. var stoped = false,
  429. i = -1,
  430. len = events.length,
  431. handler
  432. while (++i < len) {
  433. handler = events[i]
  434. if (handler.cb.apply(handler.ctx2, args) === false) {
  435. stoped = true
  436. break
  437. }
  438. }
  439. return !stoped
  440. }
  441. protos = {
  442. /**
  443. * 绑定事件。
  444. *
  445. * `callback`方法在执行时,arguments将会来源于trigger的时候携带的参数。如
  446. * ```javascript
  447. * var obj = {};
  448. *
  449. * // 使得obj有事件行为
  450. * Mediator.installTo( obj );
  451. *
  452. * obj.on( 'testa', function( arg1, arg2 ) {
  453. * console.log( arg1, arg2 ); // => 'arg1', 'arg2'
  454. * });
  455. *
  456. * obj.trigger( 'testa', 'arg1', 'arg2' );
  457. * ```
  458. *
  459. * 如果`callback`中,某一个方法`return false`了,则后续的其他`callback`都不会被执行到。
  460. * 切会影响到`trigger`方法的返回值,为`false`。
  461. *
  462. * `on`还可以用来添加一个特殊事件`all`, 这样所有的事件触发都会响应到。同时此类`callback`中的arguments有一个不同处,
  463. * 就是第一个参数为`type`,记录当前是什么事件在触发。此类`callback`的优先级比脚低,会再正常`callback`执行完后触发。
  464. * ```javascript
  465. * obj.on( 'all', function( type, arg1, arg2 ) {
  466. * console.log( type, arg1, arg2 ); // => 'testa', 'arg1', 'arg2'
  467. * });
  468. * ```
  469. *
  470. * @method on
  471. * @grammar on( name, callback[, context] ) => self
  472. * @param {String} name 事件名,支持多个事件用空格隔开
  473. * @param {Function} callback 事件处理器
  474. * @param {Object} [context] 事件处理器的上下文。
  475. * @return {self} 返回自身,方便链式
  476. * @chainable
  477. * @class Mediator
  478. */
  479. on: function (name, callback, context) {
  480. var me = this,
  481. set
  482. if (!callback) {
  483. return this
  484. }
  485. set = this._events || (this._events = [])
  486. eachEvent(name, callback, function (name, callback) {
  487. var handler = { e: name }
  488. handler.cb = callback
  489. handler.ctx = context
  490. handler.ctx2 = context || me
  491. handler.id = set.length
  492. set.push(handler)
  493. })
  494. return this
  495. },
  496. /**
  497. * 绑定事件,且当handler执行完后,自动解除绑定。
  498. * @method once
  499. * @grammar once( name, callback[, context] ) => self
  500. * @param {String} name 事件名
  501. * @param {Function} callback 事件处理器
  502. * @param {Object} [context] 事件处理器的上下文。
  503. * @return {self} 返回自身,方便链式
  504. * @chainable
  505. */
  506. once: function (name, callback, context) {
  507. var me = this
  508. if (!callback) {
  509. return me
  510. }
  511. eachEvent(name, callback, function (name, callback) {
  512. var once = function () {
  513. me.off(name, once)
  514. return callback.apply(context || me, arguments)
  515. }
  516. once._cb = callback
  517. me.on(name, once, context)
  518. })
  519. return me
  520. },
  521. /**
  522. * 解除事件绑定
  523. * @method off
  524. * @grammar off( [name[, callback[, context] ] ] ) => self
  525. * @param {String} [name] 事件名
  526. * @param {Function} [callback] 事件处理器
  527. * @param {Object} [context] 事件处理器的上下文。
  528. * @return {self} 返回自身,方便链式
  529. * @chainable
  530. */
  531. off: function (name, cb, ctx) {
  532. var events = this._events
  533. if (!events) {
  534. return this
  535. }
  536. if (!name && !cb && !ctx) {
  537. this._events = []
  538. return this
  539. }
  540. eachEvent(name, cb, function (name, cb) {
  541. $.each(findHandlers(events, name, cb, ctx), function () {
  542. delete events[this.id]
  543. })
  544. })
  545. return this
  546. },
  547. /**
  548. * 触发事件
  549. * @method trigger
  550. * @grammar trigger( name[, args...] ) => self
  551. * @param {String} type 事件名
  552. * @param {*} [...] 任意参数
  553. * @return {Boolean} 如果handler中return false了,则返回false, 否则返回true
  554. */
  555. trigger: function (type) {
  556. var args, events, allEvents
  557. if (!this._events || !type) {
  558. return this
  559. }
  560. args = slice.call(arguments, 1)
  561. events = findHandlers(this._events, type)
  562. allEvents = findHandlers(this._events, 'all')
  563. return (
  564. triggerHanders(events, args) && triggerHanders(allEvents, arguments)
  565. )
  566. }
  567. }
  568. /**
  569. * 中介者,它本身是个单例,但可以通过[installTo](#WebUploader:Mediator:installTo)方法,使任何对象具备事件行为。
  570. * 主要目的是负责模块与模块之间的合作,降低耦合度。
  571. *
  572. * @class Mediator
  573. */
  574. return $.extend(
  575. {
  576. /**
  577. * 可以通过这个接口,使任何对象具备事件功能。
  578. * @method installTo
  579. * @param {Object} obj 需要具备事件行为的对象。
  580. * @return {Object} 返回obj.
  581. */
  582. installTo: function (obj) {
  583. return $.extend(obj, protos)
  584. }
  585. },
  586. protos
  587. )
  588. })
  589. /**
  590. * @fileOverview Uploader上传类
  591. */
  592. define('uploader', ['base', 'mediator'], function (Base, Mediator) {
  593. var $ = Base.$
  594. /**
  595. * 上传入口类。
  596. * @class Uploader
  597. * @constructor
  598. * @grammar new Uploader( opts ) => Uploader
  599. * @example
  600. * var uploader = WebUploader.Uploader({
  601. * swf: 'path_of_swf/Uploader.swf',
  602. *
  603. * // 开起分片上传。
  604. * chunked: true
  605. * });
  606. */
  607. function Uploader(opts) {
  608. this.options = $.extend(true, {}, Uploader.options, opts)
  609. this._init(this.options)
  610. }
  611. // default Options
  612. // widgets中有相应扩展
  613. Uploader.options = {}
  614. Mediator.installTo(Uploader.prototype)
  615. // 批量添加纯命令式方法。
  616. $.each(
  617. {
  618. upload: 'start-upload',
  619. stop: 'stop-upload',
  620. getFile: 'get-file',
  621. getFiles: 'get-files',
  622. addFile: 'add-file',
  623. addFiles: 'add-file',
  624. sort: 'sort-files',
  625. removeFile: 'remove-file',
  626. skipFile: 'skip-file',
  627. retry: 'retry',
  628. isInProgress: 'is-in-progress',
  629. makeThumb: 'make-thumb',
  630. getDimension: 'get-dimension',
  631. addButton: 'add-btn',
  632. getRuntimeType: 'get-runtime-type',
  633. refresh: 'refresh',
  634. disable: 'disable',
  635. enable: 'enable',
  636. reset: 'reset'
  637. },
  638. function (fn, command) {
  639. Uploader.prototype[fn] = function () {
  640. return this.request(command, arguments)
  641. }
  642. }
  643. )
  644. $.extend(Uploader.prototype, {
  645. state: 'pending',
  646. _init: function (opts) {
  647. var me = this
  648. me.request('init', opts, function () {
  649. me.state = 'ready'
  650. me.trigger('ready')
  651. })
  652. },
  653. /**
  654. * 获取或者设置Uploader配置项。
  655. * @method option
  656. * @grammar option( key ) => *
  657. * @grammar option( key, val ) => self
  658. * @example
  659. *
  660. * // 初始状态图片上传前不会压缩
  661. * var uploader = new WebUploader.Uploader({
  662. * resize: null;
  663. * });
  664. *
  665. * // 修改后图片上传前,尝试将图片压缩到1600 * 1600
  666. * uploader.options( 'resize', {
  667. * width: 1600,
  668. * height: 1600
  669. * });
  670. */
  671. option: function (key, val) {
  672. var opts = this.options
  673. // setter
  674. if (arguments.length > 1) {
  675. if ($.isPlainObject(val) && $.isPlainObject(opts[key])) {
  676. $.extend(opts[key], val)
  677. } else {
  678. opts[key] = val
  679. }
  680. } else {
  681. // getter
  682. return key ? opts[key] : opts
  683. }
  684. },
  685. /**
  686. * 获取文件统计信息。返回一个包含一下信息的对象。
  687. * * `successNum` 上传成功的文件数
  688. * * `uploadFailNum` 上传失败的文件数
  689. * * `cancelNum` 被删除的文件数
  690. * * `invalidNum` 无效的文件数
  691. * * `queueNum` 还在队列中的文件数
  692. * @method getStats
  693. * @grammar getStats() => Object
  694. */
  695. getStats: function () {
  696. // return this._mgr.getStats.apply( this._mgr, arguments );
  697. var stats = this.request('get-stats')
  698. return {
  699. successNum: stats.numOfSuccess,
  700. // who care?
  701. // queueFailNum: 0,
  702. cancelNum: stats.numOfCancel,
  703. invalidNum: stats.numOfInvalid,
  704. uploadFailNum: stats.numOfUploadFailed,
  705. queueNum: stats.numOfQueue
  706. }
  707. },
  708. // 需要重写此方法来来支持opts.onEvent和instance.onEvent的处理器
  709. trigger: function (type /*, args...*/) {
  710. var args = [].slice.call(arguments, 1),
  711. opts = this.options,
  712. name = 'on' + type.substring(0, 1).toUpperCase() + type.substring(1)
  713. if (
  714. // 调用通过on方法注册的handler.
  715. Mediator.trigger.apply(this, arguments) === false ||
  716. // 调用opts.onEvent
  717. ($.isFunction(opts[name]) &&
  718. opts[name].apply(this, args) === false) ||
  719. // 调用this.onEvent
  720. ($.isFunction(this[name]) &&
  721. this[name].apply(this, args) === false) ||
  722. // 广播所有uploader的事件。
  723. Mediator.trigger.apply(Mediator, [this, type].concat(args)) === false
  724. ) {
  725. return false
  726. }
  727. return true
  728. },
  729. // widgets/widget.js将补充此方法的详细文档。
  730. request: Base.noop
  731. })
  732. /**
  733. * 创建Uploader实例,等同于new Uploader( opts );
  734. * @method create
  735. * @class Base
  736. * @static
  737. * @grammar Base.create( opts ) => Uploader
  738. */
  739. Base.create = Uploader.create = function (opts) {
  740. return new Uploader(opts)
  741. }
  742. // 暴露Uploader,可以通过它来扩展业务逻辑。
  743. Base.Uploader = Uploader
  744. return Uploader
  745. })
  746. /**
  747. * @fileOverview Runtime管理器,负责Runtime的选择, 连接
  748. */
  749. define('runtime/runtime', ['base', 'mediator'], function (Base, Mediator) {
  750. var $ = Base.$,
  751. factories = {},
  752. // 获取对象的第一个key
  753. getFirstKey = function (obj) {
  754. for (var key in obj) {
  755. if (obj.hasOwnProperty(key)) {
  756. return key
  757. }
  758. }
  759. return null
  760. }
  761. // 接口类。
  762. function Runtime(options) {
  763. this.options = $.extend(
  764. {
  765. container: document.body
  766. },
  767. options
  768. )
  769. this.uid = Base.guid('rt_')
  770. }
  771. $.extend(Runtime.prototype, {
  772. getContainer: function () {
  773. var opts = this.options,
  774. parent,
  775. container
  776. if (this._container) {
  777. return this._container
  778. }
  779. parent = $(opts.container || document.body)
  780. container = $(document.createElement('div'))
  781. container.attr('id', 'rt_' + this.uid)
  782. container.css({
  783. position: 'absolute',
  784. top: '0px',
  785. left: '0px',
  786. width: '1px',
  787. height: '1px',
  788. overflow: 'hidden'
  789. })
  790. parent.append(container)
  791. parent.addClass('webuploader-container')
  792. this._container = container
  793. return container
  794. },
  795. init: Base.noop,
  796. exec: Base.noop,
  797. destroy: function () {
  798. if (this._container) {
  799. this._container.parentNode.removeChild(this.__container)
  800. }
  801. this.off()
  802. }
  803. })
  804. Runtime.orders = 'html5,flash'
  805. /**
  806. * 添加Runtime实现。
  807. * @param {String} type 类型
  808. * @param {Runtime} factory 具体Runtime实现。
  809. */
  810. Runtime.addRuntime = function (type, factory) {
  811. factories[type] = factory
  812. }
  813. Runtime.hasRuntime = function (type) {
  814. return !!(type ? factories[type] : getFirstKey(factories))
  815. }
  816. Runtime.create = function (opts, orders) {
  817. var type, runtime
  818. orders = orders || Runtime.orders
  819. $.each(orders.split(/\s*,\s*/g), function () {
  820. if (factories[this]) {
  821. type = this
  822. return false
  823. }
  824. })
  825. type = type || getFirstKey(factories)
  826. if (!type) {
  827. throw new Error('Runtime Error')
  828. }
  829. runtime = new factories[type](opts)
  830. return runtime
  831. }
  832. Mediator.installTo(Runtime.prototype)
  833. return Runtime
  834. })
  835. /**
  836. * @fileOverview Runtime管理器,负责Runtime的选择, 连接
  837. */
  838. define('runtime/client', [
  839. 'base',
  840. 'mediator',
  841. 'runtime/runtime'
  842. ], function (Base, Mediator, Runtime) {
  843. var cache
  844. cache = (function () {
  845. var obj = {}
  846. return {
  847. add: function (runtime) {
  848. obj[runtime.uid] = runtime
  849. },
  850. get: function (ruid, standalone) {
  851. var i
  852. if (ruid) {
  853. return obj[ruid]
  854. }
  855. for (i in obj) {
  856. // 有些类型不能重用,比如filepicker.
  857. if (standalone && obj[i].__standalone) {
  858. continue
  859. }
  860. return obj[i]
  861. }
  862. return null
  863. },
  864. remove: function (runtime) {
  865. delete obj[runtime.uid]
  866. }
  867. }
  868. })()
  869. function RuntimeClient(component, standalone) {
  870. var deferred = Base.Deferred(),
  871. runtime
  872. this.uid = Base.guid('client_')
  873. // 允许runtime没有初始化之前,注册一些方法在初始化后执行。
  874. this.runtimeReady = function (cb) {
  875. return deferred.done(cb)
  876. }
  877. this.connectRuntime = function (opts, cb) {
  878. // already connected.
  879. if (runtime) {
  880. throw new Error('already connected!')
  881. }
  882. deferred.done(cb)
  883. if (typeof opts === 'string' && cache.get(opts)) {
  884. runtime = cache.get(opts)
  885. }
  886. // 像filePicker只能独立存在,不能公用。
  887. runtime = runtime || cache.get(null, standalone)
  888. // 需要创建
  889. if (!runtime) {
  890. runtime = Runtime.create(opts, opts.runtimeOrder)
  891. runtime.__promise = deferred.promise()
  892. runtime.once('ready', deferred.resolve)
  893. runtime.init()
  894. cache.add(runtime)
  895. runtime.__client = 1
  896. } else {
  897. // 来自cache
  898. Base.$.extend(runtime.options, opts)
  899. runtime.__promise.then(deferred.resolve)
  900. runtime.__client++
  901. }
  902. standalone && (runtime.__standalone = standalone)
  903. return runtime
  904. }
  905. this.getRuntime = function () {
  906. return runtime
  907. }
  908. this.disconnectRuntime = function () {
  909. if (!runtime) {
  910. return
  911. }
  912. runtime.__client--
  913. if (runtime.__client <= 0) {
  914. cache.remove(runtime)
  915. delete runtime.__promise
  916. runtime.destroy()
  917. }
  918. runtime = null
  919. }
  920. this.exec = function () {
  921. if (!runtime) {
  922. return
  923. }
  924. var args = Base.slice(arguments)
  925. component && args.unshift(component)
  926. return runtime.exec.apply(this, args)
  927. }
  928. this.getRuid = function () {
  929. return runtime && runtime.uid
  930. }
  931. this.destroy = (function (destroy) {
  932. return function () {
  933. destroy && destroy.apply(this, arguments)
  934. this.trigger('destroy')
  935. this.off()
  936. this.exec('destroy')
  937. this.disconnectRuntime()
  938. }
  939. })(this.destroy)
  940. }
  941. Mediator.installTo(RuntimeClient.prototype)
  942. return RuntimeClient
  943. })
  944. /**
  945. * @fileOverview 错误信息
  946. */
  947. define('lib/dnd', [
  948. 'base',
  949. 'mediator',
  950. 'runtime/client'
  951. ], function (Base, Mediator, RuntimeClent) {
  952. var $ = Base.$
  953. function DragAndDrop(opts) {
  954. opts = this.options = $.extend({}, DragAndDrop.options, opts)
  955. opts.container = $(opts.container)
  956. if (!opts.container.length) {
  957. return
  958. }
  959. RuntimeClent.call(this, 'DragAndDrop')
  960. }
  961. DragAndDrop.options = {
  962. accept: null,
  963. disableGlobalDnd: false
  964. }
  965. Base.inherits(RuntimeClent, {
  966. constructor: DragAndDrop,
  967. init: function () {
  968. var me = this
  969. me.connectRuntime(me.options, function () {
  970. me.exec('init')
  971. me.trigger('ready')
  972. })
  973. },
  974. destroy: function () {
  975. this.disconnectRuntime()
  976. }
  977. })
  978. Mediator.installTo(DragAndDrop.prototype)
  979. return DragAndDrop
  980. })
  981. /**
  982. * @fileOverview 组件基类。
  983. */
  984. define('widgets/widget', ['base', 'uploader'], function (Base, Uploader) {
  985. var $ = Base.$,
  986. _init = Uploader.prototype._init,
  987. IGNORE = {},
  988. widgetClass = []
  989. function isArrayLike(obj) {
  990. if (!obj) {
  991. return false
  992. }
  993. var length = obj.length,
  994. type = $.type(obj)
  995. if (obj.nodeType === 1 && length) {
  996. return true
  997. }
  998. return (
  999. type === 'array' ||
  1000. (type !== 'function' &&
  1001. type !== 'string' &&
  1002. (length === 0 ||
  1003. (typeof length === 'number' && length > 0 && length - 1 in obj)))
  1004. )
  1005. }
  1006. function Widget(uploader) {
  1007. this.owner = uploader
  1008. this.options = uploader.options
  1009. }
  1010. $.extend(Widget.prototype, {
  1011. init: Base.noop,
  1012. // 类Backbone的事件监听声明,监听uploader实例上的事件
  1013. // widget直接无法监听事件,事件只能通过uploader来传递
  1014. invoke: function (apiName, args) {
  1015. /*
  1016. {
  1017. 'make-thumb': 'makeThumb'
  1018. }
  1019. */
  1020. var map = this.responseMap
  1021. // 如果无API响应声明则忽略
  1022. if (
  1023. !map ||
  1024. !(apiName in map) ||
  1025. !(map[apiName] in this) ||
  1026. !$.isFunction(this[map[apiName]])
  1027. ) {
  1028. return IGNORE
  1029. }
  1030. return this[map[apiName]].apply(this, args)
  1031. },
  1032. /**
  1033. * 发送命令。当传入`callback`或者`handler`中返回`promise`时。返回一个当所有`handler`中的promise都完成后完成的新`promise`。
  1034. * @method request
  1035. * @grammar request( command, args ) => * | Promise
  1036. * @grammar request( command, args, callback ) => Promise
  1037. * @for Uploader
  1038. */
  1039. request: function () {
  1040. return this.owner.request.apply(this.owner, arguments)
  1041. }
  1042. })
  1043. // 扩展Uploader.
  1044. $.extend(Uploader.prototype, {
  1045. // 覆写_init用来初始化widgets
  1046. _init: function () {
  1047. var me = this,
  1048. widgets = (me._widgets = [])
  1049. $.each(widgetClass, function (_, klass) {
  1050. widgets.push(new klass(me))
  1051. })
  1052. return _init.apply(me, arguments)
  1053. },
  1054. request: function (apiName, args, callback) {
  1055. var i = 0,
  1056. widgets = this._widgets,
  1057. len = widgets.length,
  1058. rlts = [],
  1059. dfds = [],
  1060. widget,
  1061. rlt,
  1062. promise,
  1063. key
  1064. args = isArrayLike(args) ? args : [args]
  1065. for (; i < len; i++) {
  1066. widget = widgets[i]
  1067. rlt = widget.invoke(apiName, args)
  1068. if (rlt !== IGNORE) {
  1069. // Deferred对象
  1070. if (Base.isPromise(rlt)) {
  1071. dfds.push(rlt)
  1072. } else {
  1073. rlts.push(rlt)
  1074. }
  1075. }
  1076. }
  1077. // 如果有callback,则用异步方式。
  1078. if (callback || dfds.length) {
  1079. promise = Base.when.apply(Base, dfds)
  1080. key = promise.pipe ? 'pipe' : 'then'
  1081. // 很重要不能删除。删除了会死循环。
  1082. // 保证执行顺序。让callback总是在下一个tick中执行。
  1083. return promise[key](function () {
  1084. var deferred = Base.Deferred(),
  1085. args = arguments
  1086. setTimeout(function () {
  1087. deferred.resolve.apply(deferred, args)
  1088. }, 1)
  1089. return deferred.promise()
  1090. })[key](callback || Base.noop)
  1091. } else {
  1092. return rlts[0]
  1093. }
  1094. }
  1095. })
  1096. /**
  1097. * 添加组件
  1098. * @param {object} widgetProto 组件原型,构造函数通过constructor属性定义
  1099. * @param {object} responseMap API名称与函数实现的映射
  1100. * @example
  1101. * Uploader.register( {
  1102. * init: function( options ) {},
  1103. * makeThumb: function() {}
  1104. * }, {
  1105. * 'make-thumb': 'makeThumb'
  1106. * } );
  1107. */
  1108. Uploader.register = Widget.register = function (responseMap, widgetProto) {
  1109. var map = { init: 'init' },
  1110. klass
  1111. if (arguments.length === 1) {
  1112. widgetProto = responseMap
  1113. widgetProto.responseMap = map
  1114. } else {
  1115. widgetProto.responseMap = $.extend(map, responseMap)
  1116. }
  1117. klass = Base.inherits(Widget, widgetProto)
  1118. widgetClass.push(klass)
  1119. return klass
  1120. }
  1121. return Widget
  1122. })
  1123. /**
  1124. * @fileOverview DragAndDrop Widget。
  1125. */
  1126. define('widgets/filednd', [
  1127. 'base',
  1128. 'uploader',
  1129. 'lib/dnd',
  1130. 'widgets/widget'
  1131. ], function (Base, Uploader, Dnd) {
  1132. var $ = Base.$
  1133. Uploader.options.dnd = ''
  1134. /**
  1135. * @property {Selector} [dnd=undefined] 指定Drag And Drop拖拽的容器,如果不指定,则不启动。
  1136. * @namespace options
  1137. * @for Uploader
  1138. */
  1139. /**
  1140. * @event dndAccept
  1141. * @param {DataTransferItemList} items DataTransferItem
  1142. * @description 阻止此事件可以拒绝某些类型的文件拖入进来。目前只有 chrome 提供这样的 API,且只能通过 mime-type 验证。
  1143. * @for Uploader
  1144. */
  1145. return Uploader.register({
  1146. init: function (opts) {
  1147. if (!opts.dnd || this.request('predict-runtime-type') !== 'html5') {
  1148. return
  1149. }
  1150. var me = this,
  1151. deferred = Base.Deferred(),
  1152. options = $.extend(
  1153. {},
  1154. {
  1155. disableGlobalDnd: opts.disableGlobalDnd,
  1156. container: opts.dnd,
  1157. accept: opts.accept
  1158. }
  1159. ),
  1160. dnd
  1161. dnd = new Dnd(options)
  1162. dnd.once('ready', deferred.resolve)
  1163. dnd.on('drop', function (files) {
  1164. me.request('add-file', [files])
  1165. })
  1166. // 检测文件是否全部允许添加。
  1167. dnd.on('accept', function (items) {
  1168. return me.owner.trigger('dndAccept', items)
  1169. })
  1170. dnd.init()
  1171. return deferred.promise()
  1172. }
  1173. })
  1174. })
  1175. /**
  1176. * @fileOverview 错误信息
  1177. */
  1178. define('lib/filepaste', [
  1179. 'base',
  1180. 'mediator',
  1181. 'runtime/client'
  1182. ], function (Base, Mediator, RuntimeClent) {
  1183. var $ = Base.$
  1184. function FilePaste(opts) {
  1185. opts = this.options = $.extend({}, opts)
  1186. opts.container = $(opts.container || document.body)
  1187. RuntimeClent.call(this, 'FilePaste')
  1188. }
  1189. Base.inherits(RuntimeClent, {
  1190. constructor: FilePaste,
  1191. init: function () {
  1192. var me = this
  1193. me.connectRuntime(me.options, function () {
  1194. me.exec('init')
  1195. me.trigger('ready')
  1196. })
  1197. },
  1198. destroy: function () {
  1199. this.exec('destroy')
  1200. this.disconnectRuntime()
  1201. this.off()
  1202. }
  1203. })
  1204. Mediator.installTo(FilePaste.prototype)
  1205. return FilePaste
  1206. })
  1207. /**
  1208. * @fileOverview 组件基类。
  1209. */
  1210. define('widgets/filepaste', [
  1211. 'base',
  1212. 'uploader',
  1213. 'lib/filepaste',
  1214. 'widgets/widget'
  1215. ], function (Base, Uploader, FilePaste) {
  1216. var $ = Base.$
  1217. /**
  1218. * @property {Selector} [paste=undefined] 指定监听paste事件的容器,如果不指定,不启用此功能。此功能为通过粘贴来添加截屏的图片。建议设置为`document.body`.
  1219. * @namespace options
  1220. * @for Uploader
  1221. */
  1222. return Uploader.register({
  1223. init: function (opts) {
  1224. if (!opts.paste || this.request('predict-runtime-type') !== 'html5') {
  1225. return
  1226. }
  1227. var me = this,
  1228. deferred = Base.Deferred(),
  1229. options = $.extend(
  1230. {},
  1231. {
  1232. container: opts.paste,
  1233. accept: opts.accept
  1234. }
  1235. ),
  1236. paste
  1237. paste = new FilePaste(options)
  1238. paste.once('ready', deferred.resolve)
  1239. paste.on('paste', function (files) {
  1240. me.owner.request('add-file', [files])
  1241. })
  1242. paste.init()
  1243. return deferred.promise()
  1244. }
  1245. })
  1246. })
  1247. /**
  1248. * @fileOverview Blob
  1249. */
  1250. define('lib/blob', [
  1251. 'base',
  1252. 'runtime/client'
  1253. ], function (Base, RuntimeClient) {
  1254. function Blob(ruid, source) {
  1255. var me = this
  1256. me.source = source
  1257. me.ruid = ruid
  1258. RuntimeClient.call(me, 'Blob')
  1259. this.uid = source.uid || this.uid
  1260. this.type = source.type || ''
  1261. this.size = source.size || 0
  1262. if (ruid) {
  1263. me.connectRuntime(ruid)
  1264. }
  1265. }
  1266. Base.inherits(RuntimeClient, {
  1267. constructor: Blob,
  1268. slice: function (start, end) {
  1269. return this.exec('slice', start, end)
  1270. },
  1271. getSource: function () {
  1272. return this.source
  1273. }
  1274. })
  1275. return Blob
  1276. })
  1277. /**
  1278. * 为了统一化Flash的File和HTML5的File而存在。
  1279. * 以至于要调用Flash里面的File,也可以像调用HTML5版本的File一下。
  1280. * @fileOverview File
  1281. */
  1282. define('lib/file', ['base', 'lib/blob'], function (Base, Blob) {
  1283. var uid = 1,
  1284. rExt = /\.([^.]+)$/
  1285. function File(ruid, file) {
  1286. var ext
  1287. Blob.apply(this, arguments)
  1288. this.name = file.name || 'untitled' + uid++
  1289. ext = rExt.exec(file.name) ? RegExp.$1.toLowerCase() : ''
  1290. // todo 支持其他类型文件的转换。
  1291. // 如果有mimetype, 但是文件名里面没有找出后缀规律
  1292. if (!ext && this.type) {
  1293. ext = /\/(jpg|jpeg|png|gif|bmp)$/i.exec(this.type)
  1294. ? RegExp.$1.toLowerCase()
  1295. : ''
  1296. this.name += '.' + ext
  1297. }
  1298. // 如果没有指定mimetype, 但是知道文件后缀。
  1299. if (!this.type && ~'jpg,jpeg,png,gif,bmp'.indexOf(ext)) {
  1300. this.type = 'image/' + (ext === 'jpg' ? 'jpeg' : ext)
  1301. }
  1302. this.ext = ext
  1303. this.lastModifiedDate =
  1304. file.lastModifiedDate || new Date().toLocaleString()
  1305. }
  1306. return Base.inherits(Blob, File)
  1307. })
  1308. /**
  1309. * @fileOverview 错误信息
  1310. */
  1311. define('lib/filepicker', [
  1312. 'base',
  1313. 'runtime/client',
  1314. 'lib/file'
  1315. ], function (Base, RuntimeClent, File) {
  1316. var $ = Base.$
  1317. function FilePicker(opts) {
  1318. opts = this.options = $.extend({}, FilePicker.options, opts)
  1319. opts.container = $(opts.id)
  1320. if (!opts.container.length) {
  1321. throw new Error('按钮指定错误')
  1322. }
  1323. opts.innerHTML =
  1324. opts.innerHTML || opts.label || opts.container.html() || ''
  1325. opts.button = $(opts.button || document.createElement('div'))
  1326. opts.button.html(opts.innerHTML)
  1327. opts.container.html(opts.button)
  1328. RuntimeClent.call(this, 'FilePicker', true)
  1329. }
  1330. FilePicker.options = {
  1331. button: null,
  1332. container: null,
  1333. label: null,
  1334. innerHTML: null,
  1335. multiple: true,
  1336. accept: null,
  1337. name: 'file'
  1338. }
  1339. Base.inherits(RuntimeClent, {
  1340. constructor: FilePicker,
  1341. init: function () {
  1342. var me = this,
  1343. opts = me.options,
  1344. button = opts.button
  1345. button.addClass('webuploader-pick')
  1346. me.on('all', function (type) {
  1347. var files
  1348. switch (type) {
  1349. case 'mouseenter':
  1350. button.addClass('webuploader-pick-hover')
  1351. break
  1352. case 'mouseleave':
  1353. button.removeClass('webuploader-pick-hover')
  1354. break
  1355. case 'change':
  1356. files = me.exec('getFiles')
  1357. me.trigger(
  1358. 'select',
  1359. $.map(files, function (file) {
  1360. file = new File(me.getRuid(), file)
  1361. // 记录来源。
  1362. file._refer = opts.container
  1363. return file
  1364. }),
  1365. opts.container
  1366. )
  1367. break
  1368. }
  1369. })
  1370. me.connectRuntime(opts, function () {
  1371. me.refresh()
  1372. me.exec('init', opts)
  1373. me.trigger('ready')
  1374. })
  1375. $(window).on('resize', function () {
  1376. me.refresh()
  1377. })
  1378. },
  1379. refresh: function () {
  1380. var shimContainer = this.getRuntime().getContainer(),
  1381. button = this.options.button,
  1382. width = button.outerWidth ? button.outerWidth() : button.width(),
  1383. height = button.outerHeight ? button.outerHeight() : button.height(),
  1384. pos = button.offset()
  1385. width &&
  1386. height &&
  1387. shimContainer
  1388. .css({
  1389. bottom: 'auto',
  1390. right: 'auto',
  1391. width: width + 'px',
  1392. height: height + 'px'
  1393. })
  1394. .offset(pos)
  1395. },
  1396. enable: function () {
  1397. var btn = this.options.button
  1398. btn.removeClass('webuploader-pick-disable')
  1399. this.refresh()
  1400. },
  1401. disable: function () {
  1402. var btn = this.options.button
  1403. this.getRuntime().getContainer().css({
  1404. top: '-99999px'
  1405. })
  1406. btn.addClass('webuploader-pick-disable')
  1407. },
  1408. destroy: function () {
  1409. if (this.runtime) {
  1410. this.exec('destroy')
  1411. this.disconnectRuntime()
  1412. }
  1413. }
  1414. })
  1415. return FilePicker
  1416. })
  1417. /**
  1418. * @fileOverview 文件选择相关
  1419. */
  1420. define('widgets/filepicker', [
  1421. 'base',
  1422. 'uploader',
  1423. 'lib/filepicker',
  1424. 'widgets/widget'
  1425. ], function (Base, Uploader, FilePicker) {
  1426. var $ = Base.$
  1427. $.extend(Uploader.options, {
  1428. /**
  1429. * @property {Selector | Object} [pick=undefined]
  1430. * @namespace options
  1431. * @for Uploader
  1432. * @description 指定选择文件的按钮容器,不指定则不创建按钮。
  1433. *
  1434. * * `id` {Seletor} 指定选择文件的按钮容器,不指定则不创建按钮。
  1435. * * `label` {String} 请采用 `innerHTML` 代替
  1436. * * `innerHTML` {String} 指定按钮文字。不指定时优先从指定的容器中看是否自带文字。
  1437. * * `multiple` {Boolean} 是否开起同时选择多个文件能力。
  1438. */
  1439. pick: null,
  1440. /**
  1441. * @property {Arroy} [accept=null]
  1442. * @namespace options
  1443. * @for Uploader
  1444. * @description 指定接受哪些类型的文件。 由于目前还有ext转mimeType表,所以这里需要分开指定。
  1445. *
  1446. * * `title` {String} 文字描述
  1447. * * `extensions` {String} 允许的文件后缀,不带点,多个用逗号分割。
  1448. * * `mimeTypes` {String} 多个用逗号分割。
  1449. *
  1450. * 如:
  1451. *
  1452. * ```
  1453. * {
  1454. * title: 'Images',
  1455. * extensions: 'gif,jpg,jpeg,bmp,png',
  1456. * mimeTypes: 'image/*'
  1457. * }
  1458. * ```
  1459. */
  1460. accept: null /*{
  1461. title: 'Images',
  1462. extensions: 'gif,jpg,jpeg,bmp,png',
  1463. mimeTypes: 'image/*'
  1464. }*/
  1465. })
  1466. return Uploader.register(
  1467. {
  1468. 'add-btn': 'addButton',
  1469. refresh: 'refresh',
  1470. disable: 'disable',
  1471. enable: 'enable'
  1472. },
  1473. {
  1474. init: function (opts) {
  1475. this.pickers = []
  1476. return opts.pick && this.addButton(opts.pick)
  1477. },
  1478. refresh: function () {
  1479. $.each(this.pickers, function () {
  1480. this.refresh()
  1481. })
  1482. },
  1483. /**
  1484. * @method addButton
  1485. * @for Uploader
  1486. * @grammar addButton( pick ) => Promise
  1487. * @description
  1488. * 添加文件选择按钮,如果一个按钮不够,需要调用此方法来添加。参数跟[options.pick](#WebUploader:Uploader:options)一致。
  1489. * @example
  1490. * uploader.addButton({
  1491. * id: '#btnContainer',
  1492. * innerHTML: '选择文件'
  1493. * });
  1494. */
  1495. addButton: function (pick) {
  1496. var me = this,
  1497. opts = me.options,
  1498. accept = opts.accept,
  1499. options,
  1500. picker,
  1501. deferred
  1502. if (!pick) {
  1503. return
  1504. }
  1505. deferred = Base.Deferred()
  1506. $.isPlainObject(pick) ||
  1507. (pick = {
  1508. id: pick
  1509. })
  1510. options = $.extend({}, pick, {
  1511. accept: $.isPlainObject(accept) ? [accept] : accept,
  1512. swf: opts.swf,
  1513. runtimeOrder: opts.runtimeOrder
  1514. })
  1515. picker = new FilePicker(options)
  1516. picker.once('ready', deferred.resolve)
  1517. picker.on('select', function (files) {
  1518. me.owner.request('add-file', [files])
  1519. })
  1520. picker.init()
  1521. this.pickers.push(picker)
  1522. return deferred.promise()
  1523. },
  1524. disable: function () {
  1525. $.each(this.pickers, function () {
  1526. this.disable()
  1527. })
  1528. },
  1529. enable: function () {
  1530. $.each(this.pickers, function () {
  1531. this.enable()
  1532. })
  1533. }
  1534. }
  1535. )
  1536. })
  1537. /**
  1538. * @fileOverview Image
  1539. */
  1540. define('lib/image', [
  1541. 'base',
  1542. 'runtime/client',
  1543. 'lib/blob'
  1544. ], function (Base, RuntimeClient, Blob) {
  1545. var $ = Base.$
  1546. // 构造器。
  1547. function Image(opts) {
  1548. this.options = $.extend({}, Image.options, opts)
  1549. RuntimeClient.call(this, 'Image')
  1550. this.on('load', function () {
  1551. this._info = this.exec('info')
  1552. this._meta = this.exec('meta')
  1553. })
  1554. }
  1555. // 默认选项。
  1556. Image.options = {
  1557. // 默认的图片处理质量
  1558. quality: 90,
  1559. // 是否裁剪
  1560. crop: false,
  1561. // 是否保留头部信息
  1562. preserveHeaders: true,
  1563. // 是否允许放大。
  1564. allowMagnify: true
  1565. }
  1566. // 继承RuntimeClient.
  1567. Base.inherits(RuntimeClient, {
  1568. constructor: Image,
  1569. info: function (val) {
  1570. // setter
  1571. if (val) {
  1572. this._info = val
  1573. return this
  1574. }
  1575. // getter
  1576. return this._info
  1577. },
  1578. meta: function (val) {
  1579. // setter
  1580. if (val) {
  1581. this._meta = val
  1582. return this
  1583. }
  1584. // getter
  1585. return this._meta
  1586. },
  1587. loadFromBlob: function (blob) {
  1588. var me = this,
  1589. ruid = blob.getRuid()
  1590. this.connectRuntime(ruid, function () {
  1591. me.exec('init', me.options)
  1592. me.exec('loadFromBlob', blob)
  1593. })
  1594. },
  1595. resize: function () {
  1596. var args = Base.slice(arguments)
  1597. return this.exec.apply(this, ['resize'].concat(args))
  1598. },
  1599. getAsDataUrl: function (type) {
  1600. return this.exec('getAsDataUrl', type)
  1601. },
  1602. getAsBlob: function (type) {
  1603. var blob = this.exec('getAsBlob', type)
  1604. return new Blob(this.getRuid(), blob)
  1605. }
  1606. })
  1607. return Image
  1608. })
  1609. /**
  1610. * @fileOverview 图片操作, 负责预览图片和上传前压缩图片
  1611. */
  1612. define('widgets/image', [
  1613. 'base',
  1614. 'uploader',
  1615. 'lib/image',
  1616. 'widgets/widget'
  1617. ], function (Base, Uploader, Image) {
  1618. var $ = Base.$,
  1619. throttle
  1620. // 根据要处理的文件大小来节流,一次不能处理太多,会卡。
  1621. throttle = (function (max) {
  1622. var occupied = 0,
  1623. waiting = [],
  1624. tick = function () {
  1625. var item
  1626. while (waiting.length && occupied < max) {
  1627. item = waiting.shift()
  1628. occupied += item[0]
  1629. item[1]()
  1630. }
  1631. }
  1632. return function (emiter, size, cb) {
  1633. waiting.push([size, cb])
  1634. emiter.once('destroy', function () {
  1635. occupied -= size
  1636. setTimeout(tick, 1)
  1637. })
  1638. setTimeout(tick, 1)
  1639. }
  1640. })(5 * 1024 * 1024)
  1641. $.extend(Uploader.options, {
  1642. /**
  1643. * @property {Object} [thumb]
  1644. * @namespace options
  1645. * @for Uploader
  1646. * @description 配置生成缩略图的选项。
  1647. *
  1648. * 默认为:
  1649. *
  1650. * ```javascript
  1651. * {
  1652. * width: 110,
  1653. * height: 110,
  1654. *
  1655. * // 图片质量,只有type为`image/jpeg`的时候才有效。
  1656. * quality: 70,
  1657. *
  1658. * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
  1659. * allowMagnify: true,
  1660. *
  1661. * // 是否允许裁剪。
  1662. * crop: true,
  1663. *
  1664. * // 是否保留头部meta信息。
  1665. * preserveHeaders: false,
  1666. *
  1667. * // 为空的话则保留原有图片格式。
  1668. * // 否则强制转换成指定的类型。
  1669. * type: 'image/jpeg'
  1670. * }
  1671. * ```
  1672. */
  1673. thumb: {
  1674. width: 110,
  1675. height: 110,
  1676. quality: 70,
  1677. allowMagnify: true,
  1678. crop: true,
  1679. preserveHeaders: false,
  1680. // 为空的话则保留原有图片格式。
  1681. // 否则强制转换成指定的类型。
  1682. // IE 8下面 base64 大小不能超过 32K 否则预览失败,而非 jpeg 编码的图片很可
  1683. // 能会超过 32k, 所以这里设置成预览的时候都是 image/jpeg
  1684. type: 'image/jpeg'
  1685. },
  1686. /**
  1687. * @property {Object} [compress]
  1688. * @namespace options
  1689. * @for Uploader
  1690. * @description 配置压缩的图片的选项。如果此选项为`false`, 则图片在上传前不进行压缩。
  1691. *
  1692. * 默认为:
  1693. *
  1694. * ```javascript
  1695. * {
  1696. * width: 1600,
  1697. * height: 1600,
  1698. *
  1699. * // 图片质量,只有type为`image/jpeg`的时候才有效。
  1700. * quality: 90,
  1701. *
  1702. * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
  1703. * allowMagnify: false,
  1704. *
  1705. * // 是否允许裁剪。
  1706. * crop: false,
  1707. *
  1708. * // 是否保留头部meta信息。
  1709. * preserveHeaders: true
  1710. * }
  1711. * ```
  1712. */
  1713. compress: {
  1714. width: 1600,
  1715. height: 1600,
  1716. quality: 90,
  1717. allowMagnify: false,
  1718. crop: false,
  1719. preserveHeaders: true
  1720. }
  1721. })
  1722. return Uploader.register(
  1723. {
  1724. 'make-thumb': 'makeThumb',
  1725. 'before-send-file': 'compressImage'
  1726. },
  1727. {
  1728. /**
  1729. * 生成缩略图,此过程为异步,所以需要传入`callback`。
  1730. * 通常情况在图片加入队里后调用此方法来生成预览图以增强交互效果。
  1731. *
  1732. * `callback`中可以接收到两个参数。
  1733. * * 第一个为error,如果生成缩略图有错误,此error将为真。
  1734. * * 第二个为ret, 缩略图的Data URL值。
  1735. *
  1736. * **注意**
  1737. * Date URL在IE6/7中不支持,所以不用调用此方法了,直接显示一张暂不支持预览图片好了。
  1738. *
  1739. *
  1740. * @method makeThumb
  1741. * @grammar makeThumb( file, callback ) => undefined
  1742. * @grammar makeThumb( file, callback, width, height ) => undefined
  1743. * @for Uploader
  1744. * @example
  1745. *
  1746. * uploader.on( 'fileQueued', function( file ) {
  1747. * var $li = ...;
  1748. *
  1749. * uploader.makeThumb( file, function( error, ret ) {
  1750. * if ( error ) {
  1751. * $li.text('预览错误');
  1752. * } else {
  1753. * $li.append('<img alt="" src="' + ret + '" />');
  1754. * }
  1755. * });
  1756. *
  1757. * });
  1758. */
  1759. makeThumb: function (file, cb, width, height) {
  1760. var opts, image
  1761. file = this.request('get-file', file)
  1762. // 只预览图片格式。
  1763. if (!file.type.match(/^image/)) {
  1764. cb(true)
  1765. return
  1766. }
  1767. opts = $.extend({}, this.options.thumb)
  1768. // 如果传入的是object.
  1769. if ($.isPlainObject(width)) {
  1770. opts = $.extend(opts, width)
  1771. width = null
  1772. }
  1773. width = width || opts.width
  1774. height = height || opts.height
  1775. image = new Image(opts)
  1776. image.once('load', function () {
  1777. file._info = file._info || image.info()
  1778. file._meta = file._meta || image.meta()
  1779. image.resize(width, height)
  1780. })
  1781. image.once('complete', function () {
  1782. cb(false, image.getAsDataUrl(opts.type))
  1783. image.destroy()
  1784. })
  1785. image.once('error', function () {
  1786. cb(true)
  1787. image.destroy()
  1788. })
  1789. throttle(image, file.source.size, function () {
  1790. file._info && image.info(file._info)
  1791. file._meta && image.meta(file._meta)
  1792. image.loadFromBlob(file.source)
  1793. })
  1794. },
  1795. compressImage: function (file) {
  1796. var opts = this.options.compress || this.options.resize,
  1797. compressSize = (opts && opts.compressSize) || 300 * 1024,
  1798. image,
  1799. deferred
  1800. file = this.request('get-file', file)
  1801. // 只预览图片格式。
  1802. if (
  1803. !opts ||
  1804. !~'image/jpeg,image/jpg'.indexOf(file.type) ||
  1805. file.size < compressSize ||
  1806. file._compressed
  1807. ) {
  1808. return
  1809. }
  1810. opts = $.extend({}, opts)
  1811. deferred = Base.Deferred()
  1812. image = new Image(opts)
  1813. deferred.always(function () {
  1814. image.destroy()
  1815. image = null
  1816. })
  1817. image.once('error', deferred.reject)
  1818. image.once('load', function () {
  1819. file._info = file._info || image.info()
  1820. file._meta = file._meta || image.meta()
  1821. image.resize(opts.width, opts.height)
  1822. })
  1823. image.once('complete', function () {
  1824. var blob, size
  1825. // 移动端 UC / qq 浏览器的无图模式下
  1826. // ctx.getImageData 处理大图的时候会报 Exception
  1827. // INDEX_SIZE_ERR: DOM Exception 1
  1828. try {
  1829. blob = image.getAsBlob(opts.type)
  1830. size = file.size
  1831. // 如果压缩后,比原来还大则不用压缩后的。
  1832. if (blob.size < size) {
  1833. // file.source.destroy && file.source.destroy();
  1834. file.source = blob
  1835. file.size = blob.size
  1836. file.trigger('resize', blob.size, size)
  1837. }
  1838. // 标记,避免重复压缩。
  1839. file._compressed = true
  1840. deferred.resolve()
  1841. } catch (e) {
  1842. // 出错了直接继续,让其上传原始图片
  1843. deferred.resolve()
  1844. }
  1845. })
  1846. file._info && image.info(file._info)
  1847. file._meta && image.meta(file._meta)
  1848. image.loadFromBlob(file.source)
  1849. return deferred.promise()
  1850. }
  1851. }
  1852. )
  1853. })
  1854. /**
  1855. * @fileOverview 文件属性封装
  1856. */
  1857. define('file', ['base', 'mediator'], function (Base, Mediator) {
  1858. var $ = Base.$,
  1859. idPrefix = 'WU_FILE_',
  1860. idSuffix = 0,
  1861. rExt = /\.([^.]+)$/,
  1862. statusMap = {}
  1863. function gid() {
  1864. return idPrefix + idSuffix++
  1865. }
  1866. /**
  1867. * 文件类
  1868. * @class File
  1869. * @constructor 构造函数
  1870. * @grammar new File( source ) => File
  1871. * @param {Lib.File} source [lib.File](#Lib.File)实例, 此source对象是带有Runtime信息的。
  1872. */
  1873. function WUFile(source) {
  1874. /**
  1875. * 文件名,包括扩展名(后缀)
  1876. * @property name
  1877. * @type {string}
  1878. */
  1879. this.name = source.name || 'Untitled'
  1880. /**
  1881. * 文件体积(字节)
  1882. * @property size
  1883. * @type {uint}
  1884. * @default 0
  1885. */
  1886. this.size = source.size || 0
  1887. /**
  1888. * 文件MIMETYPE类型,与文件类型的对应关系请参考[http://t.cn/z8ZnFny](http://t.cn/z8ZnFny)
  1889. * @property type
  1890. * @type {string}
  1891. * @default 'application'
  1892. */
  1893. this.type = source.type || 'application'
  1894. /**
  1895. * 文件最后修改日期
  1896. * @property lastModifiedDate
  1897. * @type {int}
  1898. * @default 当前时间戳
  1899. */
  1900. this.lastModifiedDate = source.lastModifiedDate || new Date() * 1
  1901. /**
  1902. * 文件ID,每个对象具有唯一ID,与文件名无关
  1903. * @property id
  1904. * @type {string}
  1905. */
  1906. this.id = gid()
  1907. /**
  1908. * 文件扩展名,通过文件名获取,例如test.png的扩展名为png
  1909. * @property ext
  1910. * @type {string}
  1911. */
  1912. this.ext = rExt.exec(this.name) ? RegExp.$1 : ''
  1913. /**
  1914. * 状态文字说明。在不同的status语境下有不同的用途。
  1915. * @property statusText
  1916. * @type {string}
  1917. */
  1918. this.statusText = ''
  1919. // 存储文件状态,防止通过属性直接修改
  1920. statusMap[this.id] = WUFile.Status.INITED
  1921. this.source = source
  1922. this.loaded = 0
  1923. this.on('error', function (msg) {
  1924. this.setStatus(WUFile.Status.ERROR, msg)
  1925. })
  1926. }
  1927. $.extend(WUFile.prototype, {
  1928. /**
  1929. * 设置状态,状态变化时会触发`change`事件。
  1930. * @method setStatus
  1931. * @grammar setStatus( status[, statusText] );
  1932. * @param {File.Status|String} status [文件状态值](#WebUploader:File:File.Status)
  1933. * @param {String} [statusText=''] 状态说明,常在error时使用,用http, abort,server等来标记是由于什么原因导致文件错误。
  1934. */
  1935. setStatus: function (status, text) {
  1936. var prevStatus = statusMap[this.id]
  1937. typeof text !== 'undefined' && (this.statusText = text)
  1938. if (status !== prevStatus) {
  1939. statusMap[this.id] = status
  1940. /**
  1941. * 文件状态变化
  1942. * @event statuschange
  1943. */
  1944. this.trigger('statuschange', status, prevStatus)
  1945. }
  1946. },
  1947. /**
  1948. * 获取文件状态
  1949. * @return {File.Status}
  1950. * @example
  1951. 文件状态具体包括以下几种类型:
  1952. {
  1953. // 初始化
  1954. INITED: 0,
  1955. // 已入队列
  1956. QUEUED: 1,
  1957. // 正在上传
  1958. PROGRESS: 2,
  1959. // 上传出错
  1960. ERROR: 3,
  1961. // 上传成功
  1962. COMPLETE: 4,
  1963. // 上传取消
  1964. CANCELLED: 5
  1965. }
  1966. */
  1967. getStatus: function () {
  1968. return statusMap[this.id]
  1969. },
  1970. /**
  1971. * 获取文件原始信息。
  1972. * @return {*}
  1973. */
  1974. getSource: function () {
  1975. return this.source
  1976. },
  1977. destory: function () {
  1978. delete statusMap[this.id]
  1979. }
  1980. })
  1981. Mediator.installTo(WUFile.prototype)
  1982. /**
  1983. * 文件状态值,具体包括以下几种类型:
  1984. * * `inited` 初始状态
  1985. * * `queued` 已经进入队列, 等待上传
  1986. * * `progress` 上传中
  1987. * * `complete` 上传完成。
  1988. * * `error` 上传出错,可重试
  1989. * * `interrupt` 上传中断,可续传。
  1990. * * `invalid` 文件不合格,不能重试上传。会自动从队列中移除。
  1991. * * `cancelled` 文件被移除。
  1992. * @property {Object} Status
  1993. * @namespace File
  1994. * @class File
  1995. * @static
  1996. */
  1997. WUFile.Status = {
  1998. INITED: 'inited', // 初始状态
  1999. QUEUED: 'queued', // 已经进入队列, 等待上传
  2000. PROGRESS: 'progress', // 上传中
  2001. ERROR: 'error', // 上传出错,可重试
  2002. COMPLETE: 'complete', // 上传完成。
  2003. CANCELLED: 'cancelled', // 上传取消。
  2004. INTERRUPT: 'interrupt', // 上传中断,可续传。
  2005. INVALID: 'invalid' // 文件不合格,不能重试上传。
  2006. }
  2007. return WUFile
  2008. })
  2009. /**
  2010. * @fileOverview 文件队列
  2011. */
  2012. define('queue', [
  2013. 'base',
  2014. 'mediator',
  2015. 'file'
  2016. ], function (Base, Mediator, WUFile) {
  2017. var $ = Base.$,
  2018. STATUS = WUFile.Status
  2019. /**
  2020. * 文件队列, 用来存储各个状态中的文件。
  2021. * @class Queue
  2022. * @extends Mediator
  2023. */
  2024. function Queue() {
  2025. /**
  2026. * 统计文件数。
  2027. * * `numOfQueue` 队列中的文件数。
  2028. * * `numOfSuccess` 上传成功的文件数
  2029. * * `numOfCancel` 被移除的文件数
  2030. * * `numOfProgress` 正在上传中的文件数
  2031. * * `numOfUploadFailed` 上传错误的文件数。
  2032. * * `numOfInvalid` 无效的文件数。
  2033. * @property {Object} stats
  2034. */
  2035. this.stats = {
  2036. numOfQueue: 0,
  2037. numOfSuccess: 0,
  2038. numOfCancel: 0,
  2039. numOfProgress: 0,
  2040. numOfUploadFailed: 0,
  2041. numOfInvalid: 0
  2042. }
  2043. // 上传队列,仅包括等待上传的文件
  2044. this._queue = []
  2045. // 存储所有文件
  2046. this._map = {}
  2047. }
  2048. $.extend(Queue.prototype, {
  2049. /**
  2050. * 将新文件加入对队列尾部
  2051. *
  2052. * @method append
  2053. * @param {File} file 文件对象
  2054. */
  2055. append: function (file) {
  2056. this._queue.push(file)
  2057. this._fileAdded(file)
  2058. return this
  2059. },
  2060. /**
  2061. * 将新文件加入对队列头部
  2062. *
  2063. * @method prepend
  2064. * @param {File} file 文件对象
  2065. */
  2066. prepend: function (file) {
  2067. this._queue.unshift(file)
  2068. this._fileAdded(file)
  2069. return this
  2070. },
  2071. /**
  2072. * 获取文件对象
  2073. *
  2074. * @method getFile
  2075. * @param {String} fileId 文件ID
  2076. * @return {File}
  2077. */
  2078. getFile: function (fileId) {
  2079. if (typeof fileId !== 'string') {
  2080. return fileId
  2081. }
  2082. return this._map[fileId]
  2083. },
  2084. /**
  2085. * 从队列中取出一个指定状态的文件。
  2086. * @grammar fetch( status ) => File
  2087. * @method fetch
  2088. * @param {String} status [文件状态值](#WebUploader:File:File.Status)
  2089. * @return {File} [File](#WebUploader:File)
  2090. */
  2091. fetch: function (status) {
  2092. var len = this._queue.length,
  2093. i,
  2094. file
  2095. status = status || STATUS.QUEUED
  2096. for (i = 0; i < len; i++) {
  2097. file = this._queue[i]
  2098. if (status === file.getStatus()) {
  2099. return file
  2100. }
  2101. }
  2102. return null
  2103. },
  2104. /**
  2105. * 对队列进行排序,能够控制文件上传顺序。
  2106. * @grammar sort( fn ) => undefined
  2107. * @method sort
  2108. * @param {Function} fn 排序方法
  2109. */
  2110. sort: function (fn) {
  2111. if (typeof fn === 'function') {
  2112. this._queue.sort(fn)
  2113. }
  2114. },
  2115. /**
  2116. * 获取指定类型的文件列表, 列表中每一个成员为[File](#WebUploader:File)对象。
  2117. * @grammar getFiles( [status1[, status2 ...]] ) => Array
  2118. * @method getFiles
  2119. * @param {String} [status] [文件状态值](#WebUploader:File:File.Status)
  2120. */
  2121. getFiles: function () {
  2122. var sts = [].slice.call(arguments, 0),
  2123. ret = [],
  2124. i = 0,
  2125. len = this._queue.length,
  2126. file
  2127. for (; i < len; i++) {
  2128. file = this._queue[i]
  2129. if (sts.length && !~$.inArray(file.getStatus(), sts)) {
  2130. continue
  2131. }
  2132. ret.push(file)
  2133. }
  2134. return ret
  2135. },
  2136. _fileAdded: function (file) {
  2137. var me = this,
  2138. existing = this._map[file.id]
  2139. if (!existing) {
  2140. this._map[file.id] = file
  2141. file.on('statuschange', function (cur, pre) {
  2142. me._onFileStatusChange(cur, pre)
  2143. })
  2144. }
  2145. file.setStatus(STATUS.QUEUED)
  2146. },
  2147. _onFileStatusChange: function (curStatus, preStatus) {
  2148. var stats = this.stats
  2149. switch (preStatus) {
  2150. case STATUS.PROGRESS:
  2151. stats.numOfProgress--
  2152. break
  2153. case STATUS.QUEUED:
  2154. stats.numOfQueue--
  2155. break
  2156. case STATUS.ERROR:
  2157. stats.numOfUploadFailed--
  2158. break
  2159. case STATUS.INVALID:
  2160. stats.numOfInvalid--
  2161. break
  2162. }
  2163. switch (curStatus) {
  2164. case STATUS.QUEUED:
  2165. stats.numOfQueue++
  2166. break
  2167. case STATUS.PROGRESS:
  2168. stats.numOfProgress++
  2169. break
  2170. case STATUS.ERROR:
  2171. stats.numOfUploadFailed++
  2172. break
  2173. case STATUS.COMPLETE:
  2174. stats.numOfSuccess++
  2175. break
  2176. case STATUS.CANCELLED:
  2177. stats.numOfCancel++
  2178. break
  2179. case STATUS.INVALID:
  2180. stats.numOfInvalid++
  2181. break
  2182. }
  2183. }
  2184. })
  2185. Mediator.installTo(Queue.prototype)
  2186. return Queue
  2187. })
  2188. /**
  2189. * @fileOverview 队列
  2190. */
  2191. define('widgets/queue', [
  2192. 'base',
  2193. 'uploader',
  2194. 'queue',
  2195. 'file',
  2196. 'lib/file',
  2197. 'runtime/client',
  2198. 'widgets/widget'
  2199. ], function (Base, Uploader, Queue, WUFile, File, RuntimeClient) {
  2200. var $ = Base.$,
  2201. rExt = /\.\w+$/,
  2202. Status = WUFile.Status
  2203. return Uploader.register(
  2204. {
  2205. 'sort-files': 'sortFiles',
  2206. 'add-file': 'addFiles',
  2207. 'get-file': 'getFile',
  2208. 'fetch-file': 'fetchFile',
  2209. 'get-stats': 'getStats',
  2210. 'get-files': 'getFiles',
  2211. 'remove-file': 'removeFile',
  2212. retry: 'retry',
  2213. reset: 'reset',
  2214. 'accept-file': 'acceptFile'
  2215. },
  2216. {
  2217. init: function (opts) {
  2218. var me = this,
  2219. deferred,
  2220. len,
  2221. i,
  2222. item,
  2223. arr,
  2224. accept,
  2225. runtime
  2226. if ($.isPlainObject(opts.accept)) {
  2227. opts.accept = [opts.accept]
  2228. }
  2229. // accept中的中生成匹配正则。
  2230. if (opts.accept) {
  2231. arr = []
  2232. for (i = 0, len = opts.accept.length; i < len; i++) {
  2233. item = opts.accept[i].extensions
  2234. item && arr.push(item)
  2235. }
  2236. if (arr.length) {
  2237. accept =
  2238. '\\.' +
  2239. arr.join(',').replace(/,/g, '$|\\.').replace(/\*/g, '.*') +
  2240. '$'
  2241. }
  2242. me.accept = new RegExp(accept, 'i')
  2243. }
  2244. me.queue = new Queue()
  2245. me.stats = me.queue.stats
  2246. // 如果当前不是html5运行时,那就算了。
  2247. // 不执行后续操作
  2248. if (this.request('predict-runtime-type') !== 'html5') {
  2249. return
  2250. }
  2251. // 创建一个 html5 运行时的 placeholder
  2252. // 以至于外部添加原生 File 对象的时候能正确包裹一下供 webuploader 使用。
  2253. deferred = Base.Deferred()
  2254. runtime = new RuntimeClient('Placeholder')
  2255. runtime.connectRuntime(
  2256. {
  2257. runtimeOrder: 'html5'
  2258. },
  2259. function () {
  2260. me._ruid = runtime.getRuid()
  2261. deferred.resolve()
  2262. }
  2263. )
  2264. return deferred.promise()
  2265. },
  2266. // 为了支持外部直接添加一个原生File对象。
  2267. _wrapFile: function (file) {
  2268. if (!(file instanceof WUFile)) {
  2269. if (!(file instanceof File)) {
  2270. if (!this._ruid) {
  2271. throw new Error("Can't add external files.")
  2272. }
  2273. file = new File(this._ruid, file)
  2274. }
  2275. file = new WUFile(file)
  2276. }
  2277. return file
  2278. },
  2279. // 判断文件是否可以被加入队列
  2280. acceptFile: function (file) {
  2281. var invalid =
  2282. !file ||
  2283. file.size < 6 ||
  2284. (this.accept &&
  2285. // 如果名字中有后缀,才做后缀白名单处理。
  2286. rExt.exec(file.name) &&
  2287. !this.accept.test(file.name))
  2288. return !invalid
  2289. },
  2290. /**
  2291. * @event beforeFileQueued
  2292. * @param {File} file File对象
  2293. * @description 当文件被加入队列之前触发,此事件的handler返回值为`false`,则此文件不会被添加进入队列。
  2294. * @for Uploader
  2295. */
  2296. /**
  2297. * @event fileQueued
  2298. * @param {File} file File对象
  2299. * @description 当文件被加入队列以后触发。
  2300. * @for Uploader
  2301. */
  2302. _addFile: function (file) {
  2303. var me = this
  2304. file = me._wrapFile(file)
  2305. // 不过类型判断允许不允许,先派送 `beforeFileQueued`
  2306. if (!me.owner.trigger('beforeFileQueued', file)) {
  2307. return
  2308. }
  2309. // 类型不匹配,则派送错误事件,并返回。
  2310. if (!me.acceptFile(file)) {
  2311. me.owner.trigger('error', 'Q_TYPE_DENIED', file)
  2312. return
  2313. }
  2314. me.queue.append(file)
  2315. me.owner.trigger('fileQueued', file)
  2316. return file
  2317. },
  2318. getFile: function (fileId) {
  2319. return this.queue.getFile(fileId)
  2320. },
  2321. /**
  2322. * @event filesQueued
  2323. * @param {File} files 数组,内容为原始File(lib/File)对象。
  2324. * @description 当一批文件添加进队列以后触发。
  2325. * @for Uploader
  2326. */
  2327. /**
  2328. * @method addFiles
  2329. * @grammar addFiles( file ) => undefined
  2330. * @grammar addFiles( [file1, file2 ...] ) => undefined
  2331. * @param {Array of File or File} [files] Files 对象 数组
  2332. * @description 添加文件到队列
  2333. * @for Uploader
  2334. */
  2335. addFiles: function (files) {
  2336. var me = this
  2337. if (!files.length) {
  2338. files = [files]
  2339. }
  2340. files = $.map(files, function (file) {
  2341. return me._addFile(file)
  2342. })
  2343. me.owner.trigger('filesQueued', files)
  2344. if (me.options.auto) {
  2345. me.request('start-upload')
  2346. }
  2347. },
  2348. getStats: function () {
  2349. return this.stats
  2350. },
  2351. /**
  2352. * @event fileDequeued
  2353. * @param {File} file File对象
  2354. * @description 当文件被移除队列后触发。
  2355. * @for Uploader
  2356. */
  2357. /**
  2358. * @method removeFile
  2359. * @grammar removeFile( file ) => undefined
  2360. * @grammar removeFile( id ) => undefined
  2361. * @param {File|id} file File对象或这File对象的id
  2362. * @description 移除某一文件。
  2363. * @for Uploader
  2364. * @example
  2365. *
  2366. * $li.on('click', '.remove-this', function() {
  2367. * uploader.removeFile( file );
  2368. * })
  2369. */
  2370. removeFile: function (file) {
  2371. var me = this
  2372. file = file.id ? file : me.queue.getFile(file)
  2373. file.setStatus(Status.CANCELLED)
  2374. me.owner.trigger('fileDequeued', file)
  2375. },
  2376. /**
  2377. * @method getFiles
  2378. * @grammar getFiles() => Array
  2379. * @grammar getFiles( status1, status2, status... ) => Array
  2380. * @description 返回指定状态的文件集合,不传参数将返回所有状态的文件。
  2381. * @for Uploader
  2382. * @example
  2383. * console.log( uploader.getFiles() ); // => all files
  2384. * console.log( uploader.getFiles('error') ) // => all error files.
  2385. */
  2386. getFiles: function () {
  2387. return this.queue.getFiles.apply(this.queue, arguments)
  2388. },
  2389. fetchFile: function () {
  2390. return this.queue.fetch.apply(this.queue, arguments)
  2391. },
  2392. /**
  2393. * @method retry
  2394. * @grammar retry() => undefined
  2395. * @grammar retry( file ) => undefined
  2396. * @description 重试上传,重试指定文件,或者从出错的文件开始重新上传。
  2397. * @for Uploader
  2398. * @example
  2399. * function retry() {
  2400. * uploader.retry();
  2401. * }
  2402. */
  2403. retry: function (file, noForceStart) {
  2404. var me = this,
  2405. files,
  2406. i,
  2407. len
  2408. if (file) {
  2409. file = file.id ? file : me.queue.getFile(file)
  2410. file.setStatus(Status.QUEUED)
  2411. noForceStart || me.request('start-upload')
  2412. return
  2413. }
  2414. files = me.queue.getFiles(Status.ERROR)
  2415. i = 0
  2416. len = files.length
  2417. for (; i < len; i++) {
  2418. file = files[i]
  2419. file.setStatus(Status.QUEUED)
  2420. }
  2421. me.request('start-upload')
  2422. },
  2423. /**
  2424. * @method sort
  2425. * @grammar sort( fn ) => undefined
  2426. * @description 排序队列中的文件,在上传之前调整可以控制上传顺序。
  2427. * @for Uploader
  2428. */
  2429. sortFiles: function () {
  2430. return this.queue.sort.apply(this.queue, arguments)
  2431. },
  2432. /**
  2433. * @method reset
  2434. * @grammar reset() => undefined
  2435. * @description 重置uploader。目前只重置了队列。
  2436. * @for Uploader
  2437. * @example
  2438. * uploader.reset();
  2439. */
  2440. reset: function () {
  2441. this.queue = new Queue()
  2442. this.stats = this.queue.stats
  2443. }
  2444. }
  2445. )
  2446. })
  2447. /**
  2448. * @fileOverview 添加获取Runtime相关信息的方法。
  2449. */
  2450. define('widgets/runtime', [
  2451. 'uploader',
  2452. 'runtime/runtime',
  2453. 'widgets/widget'
  2454. ], function (Uploader, Runtime) {
  2455. Uploader.support = function () {
  2456. return Runtime.hasRuntime.apply(Runtime, arguments)
  2457. }
  2458. return Uploader.register(
  2459. {
  2460. 'predict-runtime-type': 'predictRuntmeType'
  2461. },
  2462. {
  2463. init: function () {
  2464. if (!this.predictRuntmeType()) {
  2465. throw Error('Runtime Error')
  2466. }
  2467. },
  2468. /**
  2469. * 预测Uploader将采用哪个`Runtime`
  2470. * @grammar predictRuntmeType() => String
  2471. * @method predictRuntmeType
  2472. * @for Uploader
  2473. */
  2474. predictRuntmeType: function () {
  2475. var orders = this.options.runtimeOrder || Runtime.orders,
  2476. type = this.type,
  2477. i,
  2478. len
  2479. if (!type) {
  2480. orders = orders.split(/\s*,\s*/g)
  2481. for (i = 0, len = orders.length; i < len; i++) {
  2482. if (Runtime.hasRuntime(orders[i])) {
  2483. this.type = type = orders[i]
  2484. break
  2485. }
  2486. }
  2487. }
  2488. return type
  2489. }
  2490. }
  2491. )
  2492. })
  2493. /**
  2494. * @fileOverview Transport
  2495. */
  2496. define('lib/transport', [
  2497. 'base',
  2498. 'runtime/client',
  2499. 'mediator'
  2500. ], function (Base, RuntimeClient, Mediator) {
  2501. var $ = Base.$
  2502. function Transport(opts) {
  2503. var me = this
  2504. opts = me.options = $.extend(true, {}, Transport.options, opts || {})
  2505. RuntimeClient.call(this, 'Transport')
  2506. this._blob = null
  2507. this._formData = opts.formData || {}
  2508. this._headers = opts.headers || {}
  2509. this.on('progress', this._timeout)
  2510. this.on('load error', function () {
  2511. me.trigger('progress', 1)
  2512. clearTimeout(me._timer)
  2513. })
  2514. }
  2515. Transport.options = {
  2516. server: '',
  2517. method: 'POST',
  2518. // 跨域时,是否允许携带cookie, 只有html5 runtime才有效
  2519. withCredentials: false,
  2520. fileVal: 'file',
  2521. timeout: 2 * 60 * 1000, // 2分钟
  2522. formData: {},
  2523. headers: {},
  2524. sendAsBinary: false
  2525. }
  2526. $.extend(Transport.prototype, {
  2527. // 添加Blob, 只能添加一次,最后一次有效。
  2528. appendBlob: function (key, blob, filename) {
  2529. var me = this,
  2530. opts = me.options
  2531. if (me.getRuid()) {
  2532. me.disconnectRuntime()
  2533. }
  2534. // 连接到blob归属的同一个runtime.
  2535. me.connectRuntime(blob.ruid, function () {
  2536. me.exec('init')
  2537. })
  2538. me._blob = blob
  2539. opts.fileVal = key || opts.fileVal
  2540. opts.filename = filename || opts.filename
  2541. },
  2542. // 添加其他字段
  2543. append: function (key, value) {
  2544. if (typeof key === 'object') {
  2545. $.extend(this._formData, key)
  2546. } else {
  2547. this._formData[key] = value
  2548. }
  2549. },
  2550. setRequestHeader: function (key, value) {
  2551. if (typeof key === 'object') {
  2552. $.extend(this._headers, key)
  2553. } else {
  2554. this._headers[key] = value
  2555. }
  2556. },
  2557. send: function (method) {
  2558. this.exec('send', method)
  2559. this._timeout()
  2560. },
  2561. abort: function () {
  2562. clearTimeout(this._timer)
  2563. return this.exec('abort')
  2564. },
  2565. destroy: function () {
  2566. this.trigger('destroy')
  2567. this.off()
  2568. this.exec('destroy')
  2569. this.disconnectRuntime()
  2570. },
  2571. getResponse: function () {
  2572. return this.exec('getResponse')
  2573. },
  2574. getResponseAsJson: function () {
  2575. return this.exec('getResponseAsJson')
  2576. },
  2577. getStatus: function () {
  2578. return this.exec('getStatus')
  2579. },
  2580. _timeout: function () {
  2581. var me = this,
  2582. duration = me.options.timeout
  2583. if (!duration) {
  2584. return
  2585. }
  2586. clearTimeout(me._timer)
  2587. me._timer = setTimeout(function () {
  2588. me.abort()
  2589. me.trigger('error', 'timeout')
  2590. }, duration)
  2591. }
  2592. })
  2593. // 让Transport具备事件功能。
  2594. Mediator.installTo(Transport.prototype)
  2595. return Transport
  2596. })
  2597. /**
  2598. * @fileOverview 负责文件上传相关。
  2599. */
  2600. define('widgets/upload', [
  2601. 'base',
  2602. 'uploader',
  2603. 'file',
  2604. 'lib/transport',
  2605. 'widgets/widget'
  2606. ], function (Base, Uploader, WUFile, Transport) {
  2607. var $ = Base.$,
  2608. isPromise = Base.isPromise,
  2609. Status = WUFile.Status
  2610. // 添加默认配置项
  2611. $.extend(Uploader.options, {
  2612. /**
  2613. * @property {Boolean} [prepareNextFile=false]
  2614. * @namespace options
  2615. * @for Uploader
  2616. * @description 是否允许在文件传输时提前把下一个文件准备好。
  2617. * 对于一个文件的准备工作比较耗时,比如图片压缩,md5序列化。
  2618. * 如果能提前在当前文件传输期处理,可以节省总体耗时。
  2619. */
  2620. prepareNextFile: false,
  2621. /**
  2622. * @property {Boolean} [chunked=false]
  2623. * @namespace options
  2624. * @for Uploader
  2625. * @description 是否要分片处理大文件上传。
  2626. */
  2627. chunked: false,
  2628. /**
  2629. * @property {Boolean} [chunkSize=5242880]
  2630. * @namespace options
  2631. * @for Uploader
  2632. * @description 如果要分片,分多大一片? 默认大小为5M.
  2633. */
  2634. chunkSize: 5 * 1024 * 1024,
  2635. /**
  2636. * @property {Boolean} [chunkRetry=2]
  2637. * @namespace options
  2638. * @for Uploader
  2639. * @description 如果某个分片由于网络问题出错,允许自动重传多少次?
  2640. */
  2641. chunkRetry: 2,
  2642. /**
  2643. * @property {Boolean} [threads=3]
  2644. * @namespace options
  2645. * @for Uploader
  2646. * @description 上传并发数。允许同时最大上传进程数。
  2647. */
  2648. threads: 3,
  2649. /**
  2650. * @property {Object} [formData]
  2651. * @namespace options
  2652. * @for Uploader
  2653. * @description 文件上传请求的参数表,每次发送都会发送此对象中的参数。
  2654. */
  2655. formData: null
  2656. /**
  2657. * @property {Object} [fileVal='file']
  2658. * @namespace options
  2659. * @for Uploader
  2660. * @description 设置文件上传域的name。
  2661. */
  2662. /**
  2663. * @property {Object} [method='POST']
  2664. * @namespace options
  2665. * @for Uploader
  2666. * @description 文件上传方式,`POST`或者`GET`。
  2667. */
  2668. /**
  2669. * @property {Object} [sendAsBinary=false]
  2670. * @namespace options
  2671. * @for Uploader
  2672. * @description 是否已二进制的流的方式发送文件,这样整个上传内容`php://input`都为文件内容,
  2673. * 其他参数在$_GET数组中。
  2674. */
  2675. })
  2676. // 负责将文件切片。
  2677. function CuteFile(file, chunkSize) {
  2678. var pending = [],
  2679. blob = file.source,
  2680. total = blob.size,
  2681. chunks = chunkSize ? Math.ceil(total / chunkSize) : 1,
  2682. start = 0,
  2683. index = 0,
  2684. len
  2685. while (index < chunks) {
  2686. len = Math.min(chunkSize, total - start)
  2687. pending.push({
  2688. file: file,
  2689. start: start,
  2690. end: chunkSize ? start + len : total,
  2691. total: total,
  2692. chunks: chunks,
  2693. chunk: index++
  2694. })
  2695. start += len
  2696. }
  2697. file.blocks = pending.concat()
  2698. file.remaning = pending.length
  2699. return {
  2700. file: file,
  2701. has: function () {
  2702. return !!pending.length
  2703. },
  2704. fetch: function () {
  2705. return pending.shift()
  2706. }
  2707. }
  2708. }
  2709. Uploader.register(
  2710. {
  2711. 'start-upload': 'start',
  2712. 'stop-upload': 'stop',
  2713. 'skip-file': 'skipFile',
  2714. 'is-in-progress': 'isInProgress'
  2715. },
  2716. {
  2717. init: function () {
  2718. var owner = this.owner
  2719. this.runing = false
  2720. // 记录当前正在传的数据,跟threads相关
  2721. this.pool = []
  2722. // 缓存即将上传的文件。
  2723. this.pending = []
  2724. // 跟踪还有多少分片没有完成上传。
  2725. this.remaning = 0
  2726. this.__tick = Base.bindFn(this._tick, this)
  2727. owner.on('uploadComplete', function (file) {
  2728. // 把其他块取消了。
  2729. file.blocks &&
  2730. $.each(file.blocks, function (_, v) {
  2731. v.transport && (v.transport.abort(), v.transport.destroy())
  2732. delete v.transport
  2733. })
  2734. delete file.blocks
  2735. delete file.remaning
  2736. })
  2737. },
  2738. /**
  2739. * @event startUpload
  2740. * @description 当开始上传流程时触发。
  2741. * @for Uploader
  2742. */
  2743. /**
  2744. * 开始上传。此方法可以从初始状态调用开始上传流程,也可以从暂停状态调用,继续上传流程。
  2745. * @grammar upload() => undefined
  2746. * @method upload
  2747. * @for Uploader
  2748. */
  2749. start: function () {
  2750. var me = this
  2751. // 移出invalid的文件
  2752. $.each(me.request('get-files', Status.INVALID), function () {
  2753. me.request('remove-file', this)
  2754. })
  2755. if (me.runing) {
  2756. return
  2757. }
  2758. me.runing = true
  2759. // 如果有暂停的,则续传
  2760. $.each(me.pool, function (_, v) {
  2761. var file = v.file
  2762. if (file.getStatus() === Status.INTERRUPT) {
  2763. file.setStatus(Status.PROGRESS)
  2764. me._trigged = false
  2765. v.transport && v.transport.send()
  2766. }
  2767. })
  2768. me._trigged = false
  2769. me.owner.trigger('startUpload')
  2770. Base.nextTick(me.__tick)
  2771. },
  2772. /**
  2773. * @event stopUpload
  2774. * @description 当开始上传流程暂停时触发。
  2775. * @for Uploader
  2776. */
  2777. /**
  2778. * 暂停上传。第一个参数为是否中断上传当前正在上传的文件。
  2779. * @grammar stop() => undefined
  2780. * @grammar stop( true ) => undefined
  2781. * @method stop
  2782. * @for Uploader
  2783. */
  2784. stop: function (interrupt) {
  2785. var me = this
  2786. if (me.runing === false) {
  2787. return
  2788. }
  2789. me.runing = false
  2790. interrupt &&
  2791. $.each(me.pool, function (_, v) {
  2792. v.transport && v.transport.abort()
  2793. v.file.setStatus(Status.INTERRUPT)
  2794. })
  2795. me.owner.trigger('stopUpload')
  2796. },
  2797. /**
  2798. * 判断`Uplaode`r是否正在上传中。
  2799. * @grammar isInProgress() => Boolean
  2800. * @method isInProgress
  2801. * @for Uploader
  2802. */
  2803. isInProgress: function () {
  2804. return !!this.runing
  2805. },
  2806. getStats: function () {
  2807. return this.request('get-stats')
  2808. },
  2809. /**
  2810. * 掉过一个文件上传,直接标记指定文件为已上传状态。
  2811. * @grammar skipFile( file ) => undefined
  2812. * @method skipFile
  2813. * @for Uploader
  2814. */
  2815. skipFile: function (file, status) {
  2816. file = this.request('get-file', file)
  2817. file.setStatus(status || Status.COMPLETE)
  2818. file.skipped = true
  2819. // 如果正在上传。
  2820. file.blocks &&
  2821. $.each(file.blocks, function (_, v) {
  2822. var _tr = v.transport
  2823. if (_tr) {
  2824. _tr.abort()
  2825. _tr.destroy()
  2826. delete v.transport
  2827. }
  2828. })
  2829. this.owner.trigger('uploadSkip', file)
  2830. },
  2831. /**
  2832. * @event uploadFinished
  2833. * @description 当所有文件上传结束时触发。
  2834. * @for Uploader
  2835. */
  2836. _tick: function () {
  2837. var me = this,
  2838. opts = me.options,
  2839. fn,
  2840. val
  2841. // 上一个promise还没有结束,则等待完成后再执行。
  2842. if (me._promise) {
  2843. return me._promise.always(me.__tick)
  2844. }
  2845. // 还有位置,且还有文件要处理的话。
  2846. if (me.pool.length < opts.threads && (val = me._nextBlock())) {
  2847. me._trigged = false
  2848. fn = function (val) {
  2849. me._promise = null
  2850. // 有可能是reject过来的,所以要检测val的类型。
  2851. val && val.file && me._startSend(val)
  2852. Base.nextTick(me.__tick)
  2853. }
  2854. me._promise = isPromise(val) ? val.always(fn) : fn(val)
  2855. // 没有要上传的了,且没有正在传输的了。
  2856. } else if (!me.remaning && !me.getStats().numOfQueue) {
  2857. me.runing = false
  2858. me._trigged ||
  2859. Base.nextTick(function () {
  2860. me.owner.trigger('uploadFinished')
  2861. })
  2862. me._trigged = true
  2863. }
  2864. },
  2865. _nextBlock: function () {
  2866. var me = this,
  2867. act = me._act,
  2868. opts = me.options,
  2869. next,
  2870. done
  2871. // 如果当前文件还有没有需要传输的,则直接返回剩下的。
  2872. if (act && act.has() && act.file.getStatus() === Status.PROGRESS) {
  2873. // 是否提前准备下一个文件
  2874. if (opts.prepareNextFile && !me.pending.length) {
  2875. me._prepareNextFile()
  2876. }
  2877. return act.fetch()
  2878. // 否则,如果正在运行,则准备下一个文件,并等待完成后返回下个分片。
  2879. } else if (me.runing) {
  2880. // 如果缓存中有,则直接在缓存中取,没有则去queue中取。
  2881. if (!me.pending.length && me.getStats().numOfQueue) {
  2882. me._prepareNextFile()
  2883. }
  2884. next = me.pending.shift()
  2885. done = function (file) {
  2886. if (!file) {
  2887. return null
  2888. }
  2889. act = CuteFile(file, opts.chunked ? opts.chunkSize : 0)
  2890. me._act = act
  2891. return act.fetch()
  2892. }
  2893. // 文件可能还在prepare中,也有可能已经完全准备好了。
  2894. return isPromise(next)
  2895. ? next[next.pipe ? 'pipe' : 'then'](done)
  2896. : done(next)
  2897. }
  2898. },
  2899. /**
  2900. * @event uploadStart
  2901. * @param {File} file File对象
  2902. * @description 某个文件开始上传前触发,一个文件只会触发一次。
  2903. * @for Uploader
  2904. */
  2905. _prepareNextFile: function () {
  2906. var me = this,
  2907. file = me.request('fetch-file'),
  2908. pending = me.pending,
  2909. promise
  2910. if (file) {
  2911. promise = me.request('before-send-file', file, function () {
  2912. // 有可能文件被skip掉了。文件被skip掉后,状态坑定不是Queued.
  2913. if (file.getStatus() === Status.QUEUED) {
  2914. me.owner.trigger('uploadStart', file)
  2915. file.setStatus(Status.PROGRESS)
  2916. return file
  2917. }
  2918. return me._finishFile(file)
  2919. })
  2920. // 如果还在pending中,则替换成文件本身。
  2921. promise.done(function () {
  2922. var idx = $.inArray(promise, pending)
  2923. ~idx && pending.splice(idx, 1, file)
  2924. })
  2925. // befeore-send-file的钩子就有错误发生。
  2926. promise.fail(function (reason) {
  2927. file.setStatus(Status.ERROR, reason)
  2928. me.owner.trigger('uploadError', file, reason)
  2929. me.owner.trigger('uploadComplete', file)
  2930. })
  2931. pending.push(promise)
  2932. }
  2933. },
  2934. // 让出位置了,可以让其他分片开始上传
  2935. _popBlock: function (block) {
  2936. var idx = $.inArray(block, this.pool)
  2937. this.pool.splice(idx, 1)
  2938. block.file.remaning--
  2939. this.remaning--
  2940. },
  2941. // 开始上传,可以被掉过。如果promise被reject了,则表示跳过此分片。
  2942. _startSend: function (block) {
  2943. var me = this,
  2944. file = block.file,
  2945. promise
  2946. me.pool.push(block)
  2947. me.remaning++
  2948. // 如果没有分片,则直接使用原始的。
  2949. // 不会丢失content-type信息。
  2950. block.blob =
  2951. block.chunks === 1
  2952. ? file.source
  2953. : file.source.slice(block.start, block.end)
  2954. // hook, 每个分片发送之前可能要做些异步的事情。
  2955. promise = me.request('before-send', block, function () {
  2956. // 有可能文件已经上传出错了,所以不需要再传输了。
  2957. if (file.getStatus() === Status.PROGRESS) {
  2958. me._doSend(block)
  2959. } else {
  2960. me._popBlock(block)
  2961. Base.nextTick(me.__tick)
  2962. }
  2963. })
  2964. // 如果为fail了,则跳过此分片。
  2965. promise.fail(function () {
  2966. if (file.remaning === 1) {
  2967. me._finishFile(file).always(function () {
  2968. block.percentage = 1
  2969. me._popBlock(block)
  2970. me.owner.trigger('uploadComplete', file)
  2971. Base.nextTick(me.__tick)
  2972. })
  2973. } else {
  2974. block.percentage = 1
  2975. me._popBlock(block)
  2976. Base.nextTick(me.__tick)
  2977. }
  2978. })
  2979. },
  2980. /**
  2981. * @event uploadBeforeSend
  2982. * @param {Object} object
  2983. * @param {Object} data 默认的上传参数,可以扩展此对象来控制上传参数。
  2984. * @description 当某个文件的分块在发送前触发,主要用来询问是否要添加附带参数,大文件在开起分片上传的前提下此事件可能会触发多次。
  2985. * @for Uploader
  2986. */
  2987. /**
  2988. * @event uploadAccept
  2989. * @param {Object} object
  2990. * @param {Object} ret 服务端的返回数据,json格式,如果服务端不是json格式,从ret._raw中取数据,自行解析。
  2991. * @description 当某个文件上传到服务端响应后,会派送此事件来询问服务端响应是否有效。如果此事件handler返回值为`false`, 则此文件将派送`server`类型的`uploadError`事件。
  2992. * @for Uploader
  2993. */
  2994. /**
  2995. * @event uploadProgress
  2996. * @param {File} file File对象
  2997. * @param {Number} percentage 上传进度
  2998. * @description 上传过程中触发,携带上传进度。
  2999. * @for Uploader
  3000. */
  3001. /**
  3002. * @event uploadError
  3003. * @param {File} file File对象
  3004. * @param {String} reason 出错的code
  3005. * @description 当文件上传出错时触发。
  3006. * @for Uploader
  3007. */
  3008. /**
  3009. * @event uploadSuccess
  3010. * @param {File} file File对象
  3011. * @param {Object} response 服务端返回的数据
  3012. * @description 当文件上传成功时触发。
  3013. * @for Uploader
  3014. */
  3015. /**
  3016. * @event uploadComplete
  3017. * @param {File} [file] File对象
  3018. * @description 不管成功或者失败,文件上传完成时触发。
  3019. * @for Uploader
  3020. */
  3021. // 做上传操作。
  3022. _doSend: function (block) {
  3023. var me = this,
  3024. owner = me.owner,
  3025. opts = me.options,
  3026. file = block.file,
  3027. tr = new Transport(opts),
  3028. data = $.extend({}, opts.formData),
  3029. headers = $.extend({}, opts.headers),
  3030. requestAccept,
  3031. ret
  3032. block.transport = tr
  3033. tr.on('destroy', function () {
  3034. delete block.transport
  3035. me._popBlock(block)
  3036. Base.nextTick(me.__tick)
  3037. })
  3038. // 广播上传进度。以文件为单位。
  3039. tr.on('progress', function (percentage) {
  3040. var totalPercent = 0,
  3041. uploaded = 0
  3042. // 可能没有abort掉,progress还是执行进来了。
  3043. // if ( !file.blocks ) {
  3044. // return;
  3045. // }
  3046. totalPercent = block.percentage = percentage
  3047. if (block.chunks > 1) {
  3048. // 计算文件的整体速度。
  3049. $.each(file.blocks, function (_, v) {
  3050. uploaded += (v.percentage || 0) * (v.end - v.start)
  3051. })
  3052. totalPercent = uploaded / file.size
  3053. }
  3054. owner.trigger('uploadProgress', file, totalPercent || 0)
  3055. })
  3056. // 用来询问,是否返回的结果是有错误的。
  3057. requestAccept = function (reject) {
  3058. console.log('来标记错误', reject)
  3059. var fn
  3060. ret = tr.getResponseAsJson() || {}
  3061. ret._raw = tr.getResponse()
  3062. fn = function (value) {
  3063. reject = value
  3064. }
  3065. // 服务端响应了,不代表成功了,询问是否响应正确。
  3066. if (!owner.trigger('uploadAccept', block, ret, fn)) {
  3067. reject = reject || 'server'
  3068. }
  3069. return reject
  3070. }
  3071. // 尝试重试,然后广播文件上传出错。
  3072. tr.on('error', function (type, flag) {
  3073. block.retried = block.retried || 0
  3074. // 自动重试
  3075. if (
  3076. block.chunks > 1 &&
  3077. ~'http,abort'.indexOf(type) &&
  3078. block.retried < opts.chunkRetry
  3079. ) {
  3080. block.retried++
  3081. tr.send()
  3082. } else {
  3083. // http status 500 ~ 600
  3084. if (!flag && type === 'server') {
  3085. type = requestAccept(type)
  3086. }
  3087. file.setStatus(Status.ERROR, type)
  3088. owner.trigger('uploadError', file, type)
  3089. owner.trigger('uploadComplete', file)
  3090. }
  3091. })
  3092. // 上传成功
  3093. tr.on('load', function () {
  3094. var reason
  3095. // 如果非预期,转向上传出错。
  3096. if ((reason = requestAccept())) {
  3097. tr.trigger('error', reason, true)
  3098. return
  3099. }
  3100. // 全部上传完成。
  3101. if (file.remaning === 1) {
  3102. me._finishFile(file, ret)
  3103. } else {
  3104. tr.destroy()
  3105. }
  3106. })
  3107. // 配置默认的上传字段。
  3108. data = $.extend(data, {
  3109. id: file.id,
  3110. name: file.name,
  3111. type: file.type,
  3112. lastModifiedDate: file.lastModifiedDate,
  3113. size: file.size
  3114. })
  3115. // data = $.extend(data, {
  3116. // file: file.source
  3117. // })
  3118. block.chunks > 1 &&
  3119. $.extend(data, {
  3120. chunks: block.chunks,
  3121. chunk: block.chunk
  3122. })
  3123. // 在发送之间可以添加字段什么的。。。
  3124. // 如果默认的字段不够使用,可以通过监听此事件来扩展
  3125. owner.trigger('uploadBeforeSend', block, data, headers)
  3126. // 开始发送。
  3127. tr.appendBlob(opts.fileVal, block.blob, file.name)
  3128. tr.append(data)
  3129. tr.setRequestHeader(headers)
  3130. tr.send()
  3131. },
  3132. // 完成上传。
  3133. _finishFile: function (file, ret, hds) {
  3134. var owner = this.owner
  3135. return owner
  3136. .request('after-send-file', arguments, function () {
  3137. console.log(
  3138. arguments,
  3139. 'arguments',
  3140. 'Status.COMPLETE',
  3141. Status.COMPLETE,
  3142. ret,
  3143. hds
  3144. )
  3145. file.setStatus(Status.COMPLETE)
  3146. owner.trigger('uploadSuccess', file, ret, hds)
  3147. })
  3148. .fail(function (reason) {
  3149. // 如果外部已经标记为invalid什么的,不再改状态。
  3150. if (file.getStatus() === Status.PROGRESS) {
  3151. file.setStatus(Status.ERROR, reason)
  3152. }
  3153. owner.trigger('uploadError', file, reason)
  3154. })
  3155. .always(function () {
  3156. owner.trigger('uploadComplete', file)
  3157. })
  3158. }
  3159. }
  3160. )
  3161. })
  3162. /**
  3163. * @fileOverview 各种验证,包括文件总大小是否超出、单文件是否超出和文件是否重复。
  3164. */
  3165. define('widgets/validator', [
  3166. 'base',
  3167. 'uploader',
  3168. 'file',
  3169. 'widgets/widget'
  3170. ], function (Base, Uploader, WUFile) {
  3171. var $ = Base.$,
  3172. validators = {},
  3173. api
  3174. /**
  3175. * @event error
  3176. * @param {String} type 错误类型。
  3177. * @description 当validate不通过时,会以派送错误事件的形式通知调用者。通过`upload.on('error', handler)`可以捕获到此类错误,目前有以下错误会在特定的情况下派送错来。
  3178. *
  3179. * * `Q_EXCEED_NUM_LIMIT` 在设置了`fileNumLimit`且尝试给`uploader`添加的文件数量超出这个值时派送。
  3180. * * `Q_EXCEED_SIZE_LIMIT` 在设置了`Q_EXCEED_SIZE_LIMIT`且尝试给`uploader`添加的文件总大小超出这个值时派送。
  3181. * @for Uploader
  3182. */
  3183. // 暴露给外面的api
  3184. api = {
  3185. // 添加验证器
  3186. addValidator: function (type, cb) {
  3187. validators[type] = cb
  3188. },
  3189. // 移除验证器
  3190. removeValidator: function (type) {
  3191. delete validators[type]
  3192. }
  3193. }
  3194. // 在Uploader初始化的时候启动Validators的初始化
  3195. Uploader.register({
  3196. init: function () {
  3197. var me = this
  3198. $.each(validators, function () {
  3199. this.call(me.owner)
  3200. })
  3201. }
  3202. })
  3203. /**
  3204. * @property {int} [fileNumLimit=undefined]
  3205. * @namespace options
  3206. * @for Uploader
  3207. * @description 验证文件总数量, 超出则不允许加入队列。
  3208. */
  3209. api.addValidator('fileNumLimit', function () {
  3210. var uploader = this,
  3211. opts = uploader.options,
  3212. count = 0,
  3213. max = opts.fileNumLimit >> 0,
  3214. flag = true
  3215. if (!max) {
  3216. return
  3217. }
  3218. uploader.on('beforeFileQueued', function (file) {
  3219. if (count >= max && flag) {
  3220. flag = false
  3221. this.trigger('error', 'Q_EXCEED_NUM_LIMIT', max, file)
  3222. setTimeout(function () {
  3223. flag = true
  3224. }, 1)
  3225. }
  3226. return count >= max ? false : true
  3227. })
  3228. uploader.on('fileQueued', function () {
  3229. count++
  3230. })
  3231. uploader.on('fileDequeued', function () {
  3232. count--
  3233. })
  3234. uploader.on('uploadFinished', function () {
  3235. count = 0
  3236. })
  3237. })
  3238. /**
  3239. * @property {int} [fileSizeLimit=undefined]
  3240. * @namespace options
  3241. * @for Uploader
  3242. * @description 验证文件总大小是否超出限制, 超出则不允许加入队列。
  3243. */
  3244. api.addValidator('fileSizeLimit', function () {
  3245. var uploader = this,
  3246. opts = uploader.options,
  3247. count = 0,
  3248. max = opts.fileSizeLimit >> 0,
  3249. flag = true
  3250. if (!max) {
  3251. return
  3252. }
  3253. uploader.on('beforeFileQueued', function (file) {
  3254. var invalid = count + file.size > max
  3255. if (invalid && flag) {
  3256. flag = false
  3257. this.trigger('error', 'Q_EXCEED_SIZE_LIMIT', max, file)
  3258. setTimeout(function () {
  3259. flag = true
  3260. }, 1)
  3261. }
  3262. return invalid ? false : true
  3263. })
  3264. uploader.on('fileQueued', function (file) {
  3265. count += file.size
  3266. })
  3267. uploader.on('fileDequeued', function (file) {
  3268. count -= file.size
  3269. })
  3270. uploader.on('uploadFinished', function () {
  3271. count = 0
  3272. })
  3273. })
  3274. /**
  3275. * @property {int} [fileSingleSizeLimit=undefined]
  3276. * @namespace options
  3277. * @for Uploader
  3278. * @description 验证单个文件大小是否超出限制, 超出则不允许加入队列。
  3279. */
  3280. api.addValidator('fileSingleSizeLimit', function () {
  3281. var uploader = this,
  3282. opts = uploader.options,
  3283. max = opts.fileSingleSizeLimit
  3284. if (!max) {
  3285. return
  3286. }
  3287. uploader.on('beforeFileQueued', function (file) {
  3288. if (file.size > max) {
  3289. file.setStatus(WUFile.Status.INVALID, 'exceed_size')
  3290. this.trigger('error', 'F_EXCEED_SIZE', file)
  3291. return false
  3292. }
  3293. })
  3294. })
  3295. /**
  3296. * @property {int} [duplicate=undefined]
  3297. * @namespace options
  3298. * @for Uploader
  3299. * @description 去重, 根据文件名字、文件大小和最后修改时间来生成hash Key.
  3300. */
  3301. api.addValidator('duplicate', function () {
  3302. var uploader = this,
  3303. opts = uploader.options,
  3304. mapping = {}
  3305. if (opts.duplicate) {
  3306. return
  3307. }
  3308. function hashString(str) {
  3309. var hash = 0,
  3310. i = 0,
  3311. len = str.length,
  3312. _char
  3313. for (; i < len; i++) {
  3314. _char = str.charCodeAt(i)
  3315. hash = _char + (hash << 6) + (hash << 16) - hash
  3316. }
  3317. return hash
  3318. }
  3319. uploader.on('beforeFileQueued', function (file) {
  3320. var hash =
  3321. file.__hash ||
  3322. (file.__hash = hashString(
  3323. file.name + file.size + file.lastModifiedDate
  3324. ))
  3325. // 已经重复了
  3326. if (mapping[hash]) {
  3327. this.trigger('error', 'F_DUPLICATE', file)
  3328. return false
  3329. }
  3330. })
  3331. uploader.on('fileQueued', function (file) {
  3332. var hash = file.__hash
  3333. hash && (mapping[hash] = true)
  3334. })
  3335. uploader.on('fileDequeued', function (file) {
  3336. var hash = file.__hash
  3337. hash && delete mapping[hash]
  3338. })
  3339. })
  3340. return api
  3341. })
  3342. /**
  3343. * @fileOverview Runtime管理器,负责Runtime的选择, 连接
  3344. */
  3345. define('runtime/compbase', [], function () {
  3346. function CompBase(owner, runtime) {
  3347. this.owner = owner
  3348. this.options = owner.options
  3349. this.getRuntime = function () {
  3350. return runtime
  3351. }
  3352. this.getRuid = function () {
  3353. return runtime.uid
  3354. }
  3355. this.trigger = function () {
  3356. return owner.trigger.apply(owner, arguments)
  3357. }
  3358. }
  3359. return CompBase
  3360. })
  3361. /**
  3362. * @fileOverview Html5Runtime
  3363. */
  3364. define('runtime/html5/runtime', [
  3365. 'base',
  3366. 'runtime/runtime',
  3367. 'runtime/compbase'
  3368. ], function (Base, Runtime, CompBase) {
  3369. var type = 'html5',
  3370. components = {}
  3371. function Html5Runtime() {
  3372. var pool = {},
  3373. me = this,
  3374. destory = this.destory
  3375. Runtime.apply(me, arguments)
  3376. me.type = type
  3377. // 这个方法的调用者,实际上是RuntimeClient
  3378. me.exec = function (comp, fn /*, args...*/) {
  3379. var client = this,
  3380. uid = client.uid,
  3381. args = Base.slice(arguments, 2),
  3382. instance
  3383. if (components[comp]) {
  3384. instance = pool[uid] = pool[uid] || new components[comp](client, me)
  3385. if (instance[fn]) {
  3386. return instance[fn].apply(instance, args)
  3387. }
  3388. }
  3389. }
  3390. me.destory = function () {
  3391. // @todo 删除池子中的所有实例
  3392. return destory && destory.apply(this, arguments)
  3393. }
  3394. }
  3395. Base.inherits(Runtime, {
  3396. constructor: Html5Runtime,
  3397. // 不需要连接其他程序,直接执行callback
  3398. init: function () {
  3399. var me = this
  3400. setTimeout(function () {
  3401. me.trigger('ready')
  3402. }, 1)
  3403. }
  3404. })
  3405. // 注册Components
  3406. Html5Runtime.register = function (name, component) {
  3407. var klass = (components[name] = Base.inherits(CompBase, component))
  3408. return klass
  3409. }
  3410. // 注册html5运行时。
  3411. // 只有在支持的前提下注册。
  3412. if (window.Blob && window.FileReader && window.DataView) {
  3413. Runtime.addRuntime(type, Html5Runtime)
  3414. }
  3415. return Html5Runtime
  3416. })
  3417. /**
  3418. * @fileOverview Blob Html实现
  3419. */
  3420. define('runtime/html5/blob', [
  3421. 'runtime/html5/runtime',
  3422. 'lib/blob'
  3423. ], function (Html5Runtime, Blob) {
  3424. return Html5Runtime.register('Blob', {
  3425. slice: function (start, end) {
  3426. var blob = this.owner.source,
  3427. slice = blob.slice || blob.webkitSlice || blob.mozSlice
  3428. blob = slice.call(blob, start, end)
  3429. return new Blob(this.getRuid(), blob)
  3430. }
  3431. })
  3432. })
  3433. /**
  3434. * @fileOverview FilePaste
  3435. */
  3436. define('runtime/html5/dnd', [
  3437. 'base',
  3438. 'runtime/html5/runtime',
  3439. 'lib/file'
  3440. ], function (Base, Html5Runtime, File) {
  3441. var $ = Base.$,
  3442. prefix = 'webuploader-dnd-'
  3443. return Html5Runtime.register('DragAndDrop', {
  3444. init: function () {
  3445. var elem = (this.elem = this.options.container)
  3446. this.dragEnterHandler = Base.bindFn(this._dragEnterHandler, this)
  3447. this.dragOverHandler = Base.bindFn(this._dragOverHandler, this)
  3448. this.dragLeaveHandler = Base.bindFn(this._dragLeaveHandler, this)
  3449. this.dropHandler = Base.bindFn(this._dropHandler, this)
  3450. this.dndOver = false
  3451. elem.on('dragenter', this.dragEnterHandler)
  3452. elem.on('dragover', this.dragOverHandler)
  3453. elem.on('dragleave', this.dragLeaveHandler)
  3454. elem.on('drop', this.dropHandler)
  3455. if (this.options.disableGlobalDnd) {
  3456. $(document).on('dragover', this.dragOverHandler)
  3457. $(document).on('drop', this.dropHandler)
  3458. }
  3459. },
  3460. _dragEnterHandler: function (e) {
  3461. var me = this,
  3462. denied = me._denied || false,
  3463. items
  3464. e = e.originalEvent || e
  3465. if (!me.dndOver) {
  3466. me.dndOver = true
  3467. // 注意只有 chrome 支持。
  3468. items = e.dataTransfer.items
  3469. if (items && items.length) {
  3470. me._denied = denied = !me.trigger('accept', items)
  3471. }
  3472. me.elem.addClass(prefix + 'over')
  3473. me.elem[denied ? 'addClass' : 'removeClass'](prefix + 'denied')
  3474. }
  3475. e.dataTransfer.dropEffect = denied ? 'none' : 'copy'
  3476. return false
  3477. },
  3478. _dragOverHandler: function (e) {
  3479. // 只处理框内的。
  3480. var parentElem = this.elem.parent().get(0)
  3481. if (parentElem && !$.contains(parentElem, e.currentTarget)) {
  3482. return false
  3483. }
  3484. clearTimeout(this._leaveTimer)
  3485. this._dragEnterHandler.call(this, e)
  3486. return false
  3487. },
  3488. _dragLeaveHandler: function () {
  3489. var me = this,
  3490. handler
  3491. handler = function () {
  3492. me.dndOver = false
  3493. me.elem.removeClass(prefix + 'over ' + prefix + 'denied')
  3494. }
  3495. clearTimeout(me._leaveTimer)
  3496. me._leaveTimer = setTimeout(handler, 100)
  3497. return false
  3498. },
  3499. _dropHandler: function (e) {
  3500. var me = this,
  3501. ruid = me.getRuid(),
  3502. parentElem = me.elem.parent().get(0)
  3503. // 只处理框内的。
  3504. if (parentElem && !$.contains(parentElem, e.currentTarget)) {
  3505. return false
  3506. }
  3507. me._getTansferFiles(e, function (results) {
  3508. me.trigger(
  3509. 'drop',
  3510. $.map(results, function (file) {
  3511. return new File(ruid, file)
  3512. })
  3513. )
  3514. })
  3515. me.dndOver = false
  3516. me.elem.removeClass(prefix + 'over')
  3517. return false
  3518. },
  3519. // 如果传入 callback 则去查看文件夹,否则只管当前文件夹。
  3520. _getTansferFiles: function (e, callback) {
  3521. var results = [],
  3522. promises = [],
  3523. items,
  3524. files,
  3525. dataTransfer,
  3526. file,
  3527. item,
  3528. i,
  3529. len,
  3530. canAccessFolder
  3531. e = e.originalEvent || e
  3532. dataTransfer = e.dataTransfer
  3533. items = dataTransfer.items
  3534. files = dataTransfer.files
  3535. canAccessFolder = !!(items && items[0].webkitGetAsEntry)
  3536. for (i = 0, len = files.length; i < len; i++) {
  3537. file = files[i]
  3538. item = items && items[i]
  3539. if (canAccessFolder && item.webkitGetAsEntry().isDirectory) {
  3540. promises.push(
  3541. this._traverseDirectoryTree(item.webkitGetAsEntry(), results)
  3542. )
  3543. } else {
  3544. results.push(file)
  3545. }
  3546. }
  3547. Base.when.apply(Base, promises).done(function () {
  3548. if (!results.length) {
  3549. return
  3550. }
  3551. callback(results)
  3552. })
  3553. },
  3554. _traverseDirectoryTree: function (entry, results) {
  3555. var deferred = Base.Deferred(),
  3556. me = this
  3557. if (entry.isFile) {
  3558. entry.file(function (file) {
  3559. results.push(file)
  3560. deferred.resolve()
  3561. })
  3562. } else if (entry.isDirectory) {
  3563. entry.createReader().readEntries(function (entries) {
  3564. var len = entries.length,
  3565. promises = [],
  3566. arr = [], // 为了保证顺序。
  3567. i
  3568. for (i = 0; i < len; i++) {
  3569. promises.push(me._traverseDirectoryTree(entries[i], arr))
  3570. }
  3571. Base.when.apply(Base, promises).then(function () {
  3572. results.push.apply(results, arr)
  3573. deferred.resolve()
  3574. }, deferred.reject)
  3575. })
  3576. }
  3577. return deferred.promise()
  3578. },
  3579. destroy: function () {
  3580. var elem = this.elem
  3581. elem.off('dragenter', this.dragEnterHandler)
  3582. elem.off('dragover', this.dragEnterHandler)
  3583. elem.off('dragleave', this.dragLeaveHandler)
  3584. elem.off('drop', this.dropHandler)
  3585. if (this.options.disableGlobalDnd) {
  3586. $(document).off('dragover', this.dragOverHandler)
  3587. $(document).off('drop', this.dropHandler)
  3588. }
  3589. }
  3590. })
  3591. })
  3592. /**
  3593. * @fileOverview FilePaste
  3594. */
  3595. define('runtime/html5/filepaste', [
  3596. 'base',
  3597. 'runtime/html5/runtime',
  3598. 'lib/file'
  3599. ], function (Base, Html5Runtime, File) {
  3600. return Html5Runtime.register('FilePaste', {
  3601. init: function () {
  3602. var opts = this.options,
  3603. elem = (this.elem = opts.container),
  3604. accept = '.*',
  3605. arr,
  3606. i,
  3607. len,
  3608. item
  3609. // accetp的mimeTypes中生成匹配正则。
  3610. if (opts.accept) {
  3611. arr = []
  3612. for (i = 0, len = opts.accept.length; i < len; i++) {
  3613. item = opts.accept[i].mimeTypes
  3614. item && arr.push(item)
  3615. }
  3616. if (arr.length) {
  3617. accept = arr.join(',')
  3618. accept = accept.replace(/,/g, '|').replace(/\*/g, '.*')
  3619. }
  3620. }
  3621. this.accept = accept = new RegExp(accept, 'i')
  3622. this.hander = Base.bindFn(this._pasteHander, this)
  3623. elem.on('paste', this.hander)
  3624. },
  3625. _pasteHander: function (e) {
  3626. var allowed = [],
  3627. ruid = this.getRuid(),
  3628. items,
  3629. item,
  3630. blob,
  3631. i,
  3632. len
  3633. e = e.originalEvent || e
  3634. items = e.clipboardData.items
  3635. for (i = 0, len = items.length; i < len; i++) {
  3636. item = items[i]
  3637. if (item.kind !== 'file' || !(blob = item.getAsFile())) {
  3638. continue
  3639. }
  3640. allowed.push(new File(ruid, blob))
  3641. }
  3642. if (allowed.length) {
  3643. // 不阻止非文件粘贴(文字粘贴)的事件冒泡
  3644. e.preventDefault()
  3645. e.stopPropagation()
  3646. this.trigger('paste', allowed)
  3647. }
  3648. },
  3649. destroy: function () {
  3650. this.elem.off('paste', this.hander)
  3651. }
  3652. })
  3653. })
  3654. /**
  3655. * @fileOverview FilePicker
  3656. */
  3657. define('runtime/html5/filepicker', [
  3658. 'base',
  3659. 'runtime/html5/runtime'
  3660. ], function (Base, Html5Runtime) {
  3661. var $ = Base.$
  3662. return Html5Runtime.register('FilePicker', {
  3663. init: function () {
  3664. var container = this.getRuntime().getContainer(),
  3665. me = this,
  3666. owner = me.owner,
  3667. opts = me.options,
  3668. lable = $(document.createElement('label')),
  3669. input = $(document.createElement('input')),
  3670. arr,
  3671. i,
  3672. len,
  3673. mouseHandler
  3674. input.attr('type', 'file')
  3675. input.attr('name', opts.name)
  3676. input.addClass('webuploader-element-invisible')
  3677. lable.on('click', function () {
  3678. input.trigger('click')
  3679. })
  3680. lable.css({
  3681. opacity: 0,
  3682. width: '100%',
  3683. height: '100%',
  3684. display: 'block',
  3685. cursor: 'pointer',
  3686. background: '#ffffff'
  3687. })
  3688. if (opts.multiple) {
  3689. input.attr('multiple', 'multiple')
  3690. }
  3691. // @todo Firefox不支持单独指定后缀
  3692. if (opts.accept && opts.accept.length > 0) {
  3693. arr = []
  3694. for (i = 0, len = opts.accept.length; i < len; i++) {
  3695. arr.push(opts.accept[i].mimeTypes)
  3696. }
  3697. input.attr('accept', arr.join(','))
  3698. }
  3699. container.append(input)
  3700. container.append(lable)
  3701. mouseHandler = function (e) {
  3702. owner.trigger(e.type)
  3703. }
  3704. input.on('change', function (e) {
  3705. var fn = arguments.callee,
  3706. clone
  3707. me.files = e.target.files
  3708. // reset input
  3709. clone = this.cloneNode(true)
  3710. this.parentNode.replaceChild(clone, this)
  3711. input.off()
  3712. input = $(clone)
  3713. .on('change', fn)
  3714. .on('mouseenter mouseleave', mouseHandler)
  3715. owner.trigger('change')
  3716. })
  3717. lable.on('mouseenter mouseleave', mouseHandler)
  3718. },
  3719. getFiles: function () {
  3720. return this.files
  3721. },
  3722. destroy: function () {
  3723. // todo
  3724. }
  3725. })
  3726. })
  3727. /**
  3728. * Terms:
  3729. *
  3730. * Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
  3731. * @fileOverview Image控件
  3732. */
  3733. define('runtime/html5/util', ['base'], function (Base) {
  3734. var urlAPI =
  3735. (window.createObjectURL && window) ||
  3736. (window.URL && URL.revokeObjectURL && URL) ||
  3737. window.webkitURL,
  3738. createObjectURL = Base.noop,
  3739. revokeObjectURL = createObjectURL
  3740. if (urlAPI) {
  3741. // 更安全的方式调用,比如android里面就能把context改成其他的对象。
  3742. createObjectURL = function () {
  3743. return urlAPI.createObjectURL.apply(urlAPI, arguments)
  3744. }
  3745. revokeObjectURL = function () {
  3746. return urlAPI.revokeObjectURL.apply(urlAPI, arguments)
  3747. }
  3748. }
  3749. return {
  3750. createObjectURL: createObjectURL,
  3751. revokeObjectURL: revokeObjectURL,
  3752. dataURL2Blob: function (dataURI) {
  3753. var byteStr, intArray, ab, i, mimetype, parts
  3754. parts = dataURI.split(',')
  3755. if (~parts[0].indexOf('base64')) {
  3756. byteStr = atob(parts[1])
  3757. } else {
  3758. byteStr = decodeURIComponent(parts[1])
  3759. }
  3760. ab = new ArrayBuffer(byteStr.length)
  3761. intArray = new Uint8Array(ab)
  3762. for (i = 0; i < byteStr.length; i++) {
  3763. intArray[i] = byteStr.charCodeAt(i)
  3764. }
  3765. mimetype = parts[0].split(':')[1].split(';')[0]
  3766. return this.arrayBufferToBlob(ab, mimetype)
  3767. },
  3768. dataURL2ArrayBuffer: function (dataURI) {
  3769. var byteStr, intArray, i, parts
  3770. parts = dataURI.split(',')
  3771. if (~parts[0].indexOf('base64')) {
  3772. byteStr = atob(parts[1])
  3773. } else {
  3774. byteStr = decodeURIComponent(parts[1])
  3775. }
  3776. intArray = new Uint8Array(byteStr.length)
  3777. for (i = 0; i < byteStr.length; i++) {
  3778. intArray[i] = byteStr.charCodeAt(i)
  3779. }
  3780. return intArray.buffer
  3781. },
  3782. arrayBufferToBlob: function (buffer, type) {
  3783. var builder = window.BlobBuilder || window.WebKitBlobBuilder,
  3784. bb
  3785. // android不支持直接new Blob, 只能借助blobbuilder.
  3786. if (builder) {
  3787. bb = new builder()
  3788. bb.append(buffer)
  3789. return bb.getBlob(type)
  3790. }
  3791. return new Blob([buffer], type ? { type: type } : {})
  3792. },
  3793. // 抽出来主要是为了解决android下面canvas.toDataUrl不支持jpeg.
  3794. // 你得到的结果是png.
  3795. canvasToDataUrl: function (canvas, type, quality) {
  3796. return canvas.toDataURL(type, quality / 100)
  3797. },
  3798. // imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
  3799. parseMeta: function (blob, callback) {
  3800. callback(false, {})
  3801. },
  3802. // imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
  3803. updateImageHead: function (data) {
  3804. return data
  3805. }
  3806. }
  3807. })
  3808. /**
  3809. * Terms:
  3810. *
  3811. * Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
  3812. * @fileOverview Image控件
  3813. */
  3814. define('runtime/html5/imagemeta', ['runtime/html5/util'], function (Util) {
  3815. var api
  3816. api = {
  3817. parsers: {
  3818. 0xffe1: []
  3819. },
  3820. maxMetaDataSize: 262144,
  3821. parse: function (blob, cb) {
  3822. var me = this,
  3823. fr = new FileReader()
  3824. fr.onload = function () {
  3825. cb(false, me._parse(this.result))
  3826. fr = fr.onload = fr.onerror = null
  3827. }
  3828. fr.onerror = function (e) {
  3829. cb(e.message)
  3830. fr = fr.onload = fr.onerror = null
  3831. }
  3832. blob = blob.slice(0, me.maxMetaDataSize)
  3833. fr.readAsArrayBuffer(blob.getSource())
  3834. },
  3835. _parse: function (buffer, noParse) {
  3836. if (buffer.byteLength < 6) {
  3837. return
  3838. }
  3839. var dataview = new DataView(buffer),
  3840. offset = 2,
  3841. maxOffset = dataview.byteLength - 4,
  3842. headLength = offset,
  3843. ret = {},
  3844. markerBytes,
  3845. markerLength,
  3846. parsers,
  3847. i
  3848. if (dataview.getUint16(0) === 0xffd8) {
  3849. while (offset < maxOffset) {
  3850. markerBytes = dataview.getUint16(offset)
  3851. if (
  3852. (markerBytes >= 0xffe0 && markerBytes <= 0xffef) ||
  3853. markerBytes === 0xfffe
  3854. ) {
  3855. markerLength = dataview.getUint16(offset + 2) + 2
  3856. if (offset + markerLength > dataview.byteLength) {
  3857. break
  3858. }
  3859. parsers = api.parsers[markerBytes]
  3860. if (!noParse && parsers) {
  3861. for (i = 0; i < parsers.length; i += 1) {
  3862. parsers[i].call(api, dataview, offset, markerLength, ret)
  3863. }
  3864. }
  3865. offset += markerLength
  3866. headLength = offset
  3867. } else {
  3868. break
  3869. }
  3870. }
  3871. if (headLength > 6) {
  3872. if (buffer.slice) {
  3873. ret.imageHead = buffer.slice(2, headLength)
  3874. } else {
  3875. // Workaround for IE10, which does not yet
  3876. // support ArrayBuffer.slice:
  3877. ret.imageHead = new Uint8Array(buffer).subarray(2, headLength)
  3878. }
  3879. }
  3880. }
  3881. return ret
  3882. },
  3883. updateImageHead: function (buffer, head) {
  3884. var data = this._parse(buffer, true),
  3885. buf1,
  3886. buf2,
  3887. bodyoffset
  3888. bodyoffset = 2
  3889. if (data.imageHead) {
  3890. bodyoffset = 2 + data.imageHead.byteLength
  3891. }
  3892. if (buffer.slice) {
  3893. buf2 = buffer.slice(bodyoffset)
  3894. } else {
  3895. buf2 = new Uint8Array(buffer).subarray(bodyoffset)
  3896. }
  3897. buf1 = new Uint8Array(head.byteLength + 2 + buf2.byteLength)
  3898. buf1[0] = 0xff
  3899. buf1[1] = 0xd8
  3900. buf1.set(new Uint8Array(head), 2)
  3901. buf1.set(new Uint8Array(buf2), head.byteLength + 2)
  3902. return buf1.buffer
  3903. }
  3904. }
  3905. Util.parseMeta = function () {
  3906. return api.parse.apply(api, arguments)
  3907. }
  3908. Util.updateImageHead = function () {
  3909. return api.updateImageHead.apply(api, arguments)
  3910. }
  3911. return api
  3912. })
  3913. /**
  3914. * 代码来自于:https://github.com/blueimp/JavaScript-Load-Image
  3915. * 暂时项目中只用了orientation.
  3916. *
  3917. * 去除了 Exif Sub IFD Pointer, GPS Info IFD Pointer, Exif Thumbnail.
  3918. * @fileOverview EXIF解析
  3919. */
  3920. // Sample
  3921. // ====================================
  3922. // Make : Apple
  3923. // Model : iPhone 4S
  3924. // Orientation : 1
  3925. // XResolution : 72 [72/1]
  3926. // YResolution : 72 [72/1]
  3927. // ResolutionUnit : 2
  3928. // Software : QuickTime 7.7.1
  3929. // DateTime : 2013:09:01 22:53:55
  3930. // ExifIFDPointer : 190
  3931. // ExposureTime : 0.058823529411764705 [1/17]
  3932. // FNumber : 2.4 [12/5]
  3933. // ExposureProgram : Normal program
  3934. // ISOSpeedRatings : 800
  3935. // ExifVersion : 0220
  3936. // DateTimeOriginal : 2013:09:01 22:52:51
  3937. // DateTimeDigitized : 2013:09:01 22:52:51
  3938. // ComponentsConfiguration : YCbCr
  3939. // ShutterSpeedValue : 4.058893515764426
  3940. // ApertureValue : 2.5260688216892597 [4845/1918]
  3941. // BrightnessValue : -0.3126686601998395
  3942. // MeteringMode : Pattern
  3943. // Flash : Flash did not fire, compulsory flash mode
  3944. // FocalLength : 4.28 [107/25]
  3945. // SubjectArea : [4 values]
  3946. // FlashpixVersion : 0100
  3947. // ColorSpace : 1
  3948. // PixelXDimension : 2448
  3949. // PixelYDimension : 3264
  3950. // SensingMethod : One-chip color area sensor
  3951. // ExposureMode : 0
  3952. // WhiteBalance : Auto white balance
  3953. // FocalLengthIn35mmFilm : 35
  3954. // SceneCaptureType : Standard
  3955. define('runtime/html5/imagemeta/exif', [
  3956. 'base',
  3957. 'runtime/html5/imagemeta'
  3958. ], function (Base, ImageMeta) {
  3959. var EXIF = {}
  3960. EXIF.ExifMap = function () {
  3961. return this
  3962. }
  3963. EXIF.ExifMap.prototype.map = {
  3964. Orientation: 0x0112
  3965. }
  3966. EXIF.ExifMap.prototype.get = function (id) {
  3967. return this[id] || this[this.map[id]]
  3968. }
  3969. EXIF.exifTagTypes = {
  3970. // byte, 8-bit unsigned int:
  3971. 1: {
  3972. getValue: function (dataView, dataOffset) {
  3973. return dataView.getUint8(dataOffset)
  3974. },
  3975. size: 1
  3976. },
  3977. // ascii, 8-bit byte:
  3978. 2: {
  3979. getValue: function (dataView, dataOffset) {
  3980. return String.fromCharCode(dataView.getUint8(dataOffset))
  3981. },
  3982. size: 1,
  3983. ascii: true
  3984. },
  3985. // short, 16 bit int:
  3986. 3: {
  3987. getValue: function (dataView, dataOffset, littleEndian) {
  3988. return dataView.getUint16(dataOffset, littleEndian)
  3989. },
  3990. size: 2
  3991. },
  3992. // long, 32 bit int:
  3993. 4: {
  3994. getValue: function (dataView, dataOffset, littleEndian) {
  3995. return dataView.getUint32(dataOffset, littleEndian)
  3996. },
  3997. size: 4
  3998. },
  3999. // rational = two long values,
  4000. // first is numerator, second is denominator:
  4001. 5: {
  4002. getValue: function (dataView, dataOffset, littleEndian) {
  4003. return (
  4004. dataView.getUint32(dataOffset, littleEndian) /
  4005. dataView.getUint32(dataOffset + 4, littleEndian)
  4006. )
  4007. },
  4008. size: 8
  4009. },
  4010. // slong, 32 bit signed int:
  4011. 9: {
  4012. getValue: function (dataView, dataOffset, littleEndian) {
  4013. return dataView.getInt32(dataOffset, littleEndian)
  4014. },
  4015. size: 4
  4016. },
  4017. // srational, two slongs, first is numerator, second is denominator:
  4018. 10: {
  4019. getValue: function (dataView, dataOffset, littleEndian) {
  4020. return (
  4021. dataView.getInt32(dataOffset, littleEndian) /
  4022. dataView.getInt32(dataOffset + 4, littleEndian)
  4023. )
  4024. },
  4025. size: 8
  4026. }
  4027. }
  4028. // undefined, 8-bit byte, value depending on field:
  4029. EXIF.exifTagTypes[7] = EXIF.exifTagTypes[1]
  4030. EXIF.getExifValue = function (
  4031. dataView,
  4032. tiffOffset,
  4033. offset,
  4034. type,
  4035. length,
  4036. littleEndian
  4037. ) {
  4038. var tagType = EXIF.exifTagTypes[type],
  4039. tagSize,
  4040. dataOffset,
  4041. values,
  4042. i,
  4043. str,
  4044. c
  4045. if (!tagType) {
  4046. Base.log('Invalid Exif data: Invalid tag type.')
  4047. return
  4048. }
  4049. tagSize = tagType.size * length
  4050. // Determine if the value is contained in the dataOffset bytes,
  4051. // or if the value at the dataOffset is a pointer to the actual data:
  4052. dataOffset =
  4053. tagSize > 4
  4054. ? tiffOffset + dataView.getUint32(offset + 8, littleEndian)
  4055. : offset + 8
  4056. if (dataOffset + tagSize > dataView.byteLength) {
  4057. Base.log('Invalid Exif data: Invalid data offset.')
  4058. return
  4059. }
  4060. if (length === 1) {
  4061. return tagType.getValue(dataView, dataOffset, littleEndian)
  4062. }
  4063. values = []
  4064. for (i = 0; i < length; i += 1) {
  4065. values[i] = tagType.getValue(
  4066. dataView,
  4067. dataOffset + i * tagType.size,
  4068. littleEndian
  4069. )
  4070. }
  4071. if (tagType.ascii) {
  4072. str = ''
  4073. // Concatenate the chars:
  4074. for (i = 0; i < values.length; i += 1) {
  4075. c = values[i]
  4076. // Ignore the terminating NULL byte(s):
  4077. if (c === '\u0000') {
  4078. break
  4079. }
  4080. str += c
  4081. }
  4082. return str
  4083. }
  4084. return values
  4085. }
  4086. EXIF.parseExifTag = function (
  4087. dataView,
  4088. tiffOffset,
  4089. offset,
  4090. littleEndian,
  4091. data
  4092. ) {
  4093. var tag = dataView.getUint16(offset, littleEndian)
  4094. data.exif[tag] = EXIF.getExifValue(
  4095. dataView,
  4096. tiffOffset,
  4097. offset,
  4098. dataView.getUint16(offset + 2, littleEndian), // tag type
  4099. dataView.getUint32(offset + 4, littleEndian), // tag length
  4100. littleEndian
  4101. )
  4102. }
  4103. EXIF.parseExifTags = function (
  4104. dataView,
  4105. tiffOffset,
  4106. dirOffset,
  4107. littleEndian,
  4108. data
  4109. ) {
  4110. var tagsNumber, dirEndOffset, i
  4111. if (dirOffset + 6 > dataView.byteLength) {
  4112. Base.log('Invalid Exif data: Invalid directory offset.')
  4113. return
  4114. }
  4115. tagsNumber = dataView.getUint16(dirOffset, littleEndian)
  4116. dirEndOffset = dirOffset + 2 + 12 * tagsNumber
  4117. if (dirEndOffset + 4 > dataView.byteLength) {
  4118. Base.log('Invalid Exif data: Invalid directory size.')
  4119. return
  4120. }
  4121. for (i = 0; i < tagsNumber; i += 1) {
  4122. this.parseExifTag(
  4123. dataView,
  4124. tiffOffset,
  4125. dirOffset + 2 + 12 * i, // tag offset
  4126. littleEndian,
  4127. data
  4128. )
  4129. }
  4130. // Return the offset to the next directory:
  4131. return dataView.getUint32(dirEndOffset, littleEndian)
  4132. }
  4133. // EXIF.getExifThumbnail = function(dataView, offset, length) {
  4134. // var hexData,
  4135. // i,
  4136. // b;
  4137. // if (!length || offset + length > dataView.byteLength) {
  4138. // Base.log('Invalid Exif data: Invalid thumbnail data.');
  4139. // return;
  4140. // }
  4141. // hexData = [];
  4142. // for (i = 0; i < length; i += 1) {
  4143. // b = dataView.getUint8(offset + i);
  4144. // hexData.push((b < 16 ? '0' : '') + b.toString(16));
  4145. // }
  4146. // return 'data:image/jpeg,%' + hexData.join('%');
  4147. // };
  4148. EXIF.parseExifData = function (dataView, offset, length, data) {
  4149. var tiffOffset = offset + 10,
  4150. littleEndian,
  4151. dirOffset
  4152. // Check for the ASCII code for "Exif" (0x45786966):
  4153. if (dataView.getUint32(offset + 4) !== 0x45786966) {
  4154. // No Exif data, might be XMP data instead
  4155. return
  4156. }
  4157. if (tiffOffset + 8 > dataView.byteLength) {
  4158. Base.log('Invalid Exif data: Invalid segment size.')
  4159. return
  4160. }
  4161. // Check for the two null bytes:
  4162. if (dataView.getUint16(offset + 8) !== 0x0000) {
  4163. Base.log('Invalid Exif data: Missing byte alignment offset.')
  4164. return
  4165. }
  4166. // Check the byte alignment:
  4167. switch (dataView.getUint16(tiffOffset)) {
  4168. case 0x4949:
  4169. littleEndian = true
  4170. break
  4171. case 0x4d4d:
  4172. littleEndian = false
  4173. break
  4174. default:
  4175. Base.log('Invalid Exif data: Invalid byte alignment marker.')
  4176. return
  4177. }
  4178. // Check for the TIFF tag marker (0x002A):
  4179. if (dataView.getUint16(tiffOffset + 2, littleEndian) !== 0x002a) {
  4180. Base.log('Invalid Exif data: Missing TIFF marker.')
  4181. return
  4182. }
  4183. // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
  4184. dirOffset = dataView.getUint32(tiffOffset + 4, littleEndian)
  4185. // Create the exif object to store the tags:
  4186. data.exif = new EXIF.ExifMap()
  4187. // Parse the tags of the main image directory and retrieve the
  4188. // offset to the next directory, usually the thumbnail directory:
  4189. dirOffset = EXIF.parseExifTags(
  4190. dataView,
  4191. tiffOffset,
  4192. tiffOffset + dirOffset,
  4193. littleEndian,
  4194. data
  4195. )
  4196. // 尝试读取缩略图
  4197. // if ( dirOffset ) {
  4198. // thumbnailData = {exif: {}};
  4199. // dirOffset = EXIF.parseExifTags(
  4200. // dataView,
  4201. // tiffOffset,
  4202. // tiffOffset + dirOffset,
  4203. // littleEndian,
  4204. // thumbnailData
  4205. // );
  4206. // // Check for JPEG Thumbnail offset:
  4207. // if (thumbnailData.exif[0x0201]) {
  4208. // data.exif.Thumbnail = EXIF.getExifThumbnail(
  4209. // dataView,
  4210. // tiffOffset + thumbnailData.exif[0x0201],
  4211. // thumbnailData.exif[0x0202] // Thumbnail data length
  4212. // );
  4213. // }
  4214. // }
  4215. }
  4216. ImageMeta.parsers[0xffe1].push(EXIF.parseExifData)
  4217. return EXIF
  4218. })
  4219. /**
  4220. * 这个方式性能不行,但是可以解决android里面的toDataUrl的bug
  4221. * android里面toDataUrl('image/jpege')得到的结果却是png.
  4222. *
  4223. * 所以这里没辙,只能借助这个工具
  4224. * @fileOverview jpeg encoder
  4225. */
  4226. define('runtime/html5/jpegencoder', [], function (require, exports, module) {
  4227. /*
  4228. Copyright (c) 2008, Adobe Systems Incorporated
  4229. All rights reserved.
  4230. Redistribution and use in source and binary forms, with or without
  4231. modification, are permitted provided that the following conditions are
  4232. met:
  4233. * Redistributions of source code must retain the above copyright notice,
  4234. this list of conditions and the following disclaimer.
  4235. * Redistributions in binary form must reproduce the above copyright
  4236. notice, this list of conditions and the following disclaimer in the
  4237. documentation and/or other materials provided with the distribution.
  4238. * Neither the name of Adobe Systems Incorporated nor the names of its
  4239. contributors may be used to endorse or promote products derived from
  4240. this software without specific prior written permission.
  4241. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  4242. IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  4243. THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  4244. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  4245. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  4246. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  4247. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  4248. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  4249. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  4250. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  4251. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  4252. */
  4253. /*
  4254. JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009
  4255. Basic GUI blocking jpeg encoder
  4256. */
  4257. function JPEGEncoder(quality) {
  4258. var self = this
  4259. var fround = Math.round
  4260. var ffloor = Math.floor
  4261. var YTable = new Array(64)
  4262. var UVTable = new Array(64)
  4263. var fdtbl_Y = new Array(64)
  4264. var fdtbl_UV = new Array(64)
  4265. var YDC_HT
  4266. var UVDC_HT
  4267. var YAC_HT
  4268. var UVAC_HT
  4269. var bitcode = new Array(65535)
  4270. var category = new Array(65535)
  4271. var outputfDCTQuant = new Array(64)
  4272. var DU = new Array(64)
  4273. var byteout = []
  4274. var bytenew = 0
  4275. var bytepos = 7
  4276. var YDU = new Array(64)
  4277. var UDU = new Array(64)
  4278. var VDU = new Array(64)
  4279. var clt = new Array(256)
  4280. var RGB_YUV_TABLE = new Array(2048)
  4281. var currentQuality
  4282. var ZigZag = [
  4283. 0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17,
  4284. 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45,
  4285. 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61,
  4286. 35, 36, 48, 49, 57, 58, 62, 63
  4287. ]
  4288. var std_dc_luminance_nrcodes = [
  4289. 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0
  4290. ]
  4291. var std_dc_luminance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
  4292. var std_ac_luminance_nrcodes = [
  4293. 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d
  4294. ]
  4295. var std_ac_luminance_values = [
  4296. 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06,
  4297. 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  4298. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72,
  4299. 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  4300. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45,
  4301. 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  4302. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75,
  4303. 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  4304. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3,
  4305. 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  4306. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9,
  4307. 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  4308. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4,
  4309. 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa
  4310. ]
  4311. var std_dc_chrominance_nrcodes = [
  4312. 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0
  4313. ]
  4314. var std_dc_chrominance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
  4315. var std_ac_chrominance_nrcodes = [
  4316. 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77
  4317. ]
  4318. var std_ac_chrominance_values = [
  4319. 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41,
  4320. 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  4321. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1,
  4322. 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  4323. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44,
  4324. 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  4325. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74,
  4326. 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  4327. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a,
  4328. 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  4329. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
  4330. 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  4331. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4,
  4332. 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa
  4333. ]
  4334. function initQuantTables(sf) {
  4335. var YQT = [
  4336. 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14,
  4337. 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22,
  4338. 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64,
  4339. 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99
  4340. ]
  4341. for (var i = 0; i < 64; i++) {
  4342. var t = ffloor((YQT[i] * sf + 50) / 100)
  4343. if (t < 1) {
  4344. t = 1
  4345. } else if (t > 255) {
  4346. t = 255
  4347. }
  4348. YTable[ZigZag[i]] = t
  4349. }
  4350. var UVQT = [
  4351. 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24,
  4352. 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, 99, 99,
  4353. 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
  4354. 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99
  4355. ]
  4356. for (var j = 0; j < 64; j++) {
  4357. var u = ffloor((UVQT[j] * sf + 50) / 100)
  4358. if (u < 1) {
  4359. u = 1
  4360. } else if (u > 255) {
  4361. u = 255
  4362. }
  4363. UVTable[ZigZag[j]] = u
  4364. }
  4365. var aasf = [
  4366. 1.0, 1.387039845, 1.306562965, 1.175875602, 1.0, 0.785694958,
  4367. 0.5411961, 0.275899379
  4368. ]
  4369. var k = 0
  4370. for (var row = 0; row < 8; row++) {
  4371. for (var col = 0; col < 8; col++) {
  4372. fdtbl_Y[k] = 1.0 / (YTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0)
  4373. fdtbl_UV[k] =
  4374. 1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0)
  4375. k++
  4376. }
  4377. }
  4378. }
  4379. function computeHuffmanTbl(nrcodes, std_table) {
  4380. var codevalue = 0
  4381. var pos_in_table = 0
  4382. var HT = new Array()
  4383. for (var k = 1; k <= 16; k++) {
  4384. for (var j = 1; j <= nrcodes[k]; j++) {
  4385. HT[std_table[pos_in_table]] = []
  4386. HT[std_table[pos_in_table]][0] = codevalue
  4387. HT[std_table[pos_in_table]][1] = k
  4388. pos_in_table++
  4389. codevalue++
  4390. }
  4391. codevalue *= 2
  4392. }
  4393. return HT
  4394. }
  4395. function initHuffmanTbl() {
  4396. YDC_HT = computeHuffmanTbl(
  4397. std_dc_luminance_nrcodes,
  4398. std_dc_luminance_values
  4399. )
  4400. UVDC_HT = computeHuffmanTbl(
  4401. std_dc_chrominance_nrcodes,
  4402. std_dc_chrominance_values
  4403. )
  4404. YAC_HT = computeHuffmanTbl(
  4405. std_ac_luminance_nrcodes,
  4406. std_ac_luminance_values
  4407. )
  4408. UVAC_HT = computeHuffmanTbl(
  4409. std_ac_chrominance_nrcodes,
  4410. std_ac_chrominance_values
  4411. )
  4412. }
  4413. function initCategoryNumber() {
  4414. var nrlower = 1
  4415. var nrupper = 2
  4416. for (var cat = 1; cat <= 15; cat++) {
  4417. //Positive numbers
  4418. for (var nr = nrlower; nr < nrupper; nr++) {
  4419. category[32767 + nr] = cat
  4420. bitcode[32767 + nr] = []
  4421. bitcode[32767 + nr][1] = cat
  4422. bitcode[32767 + nr][0] = nr
  4423. }
  4424. //Negative numbers
  4425. for (var nrneg = -(nrupper - 1); nrneg <= -nrlower; nrneg++) {
  4426. category[32767 + nrneg] = cat
  4427. bitcode[32767 + nrneg] = []
  4428. bitcode[32767 + nrneg][1] = cat
  4429. bitcode[32767 + nrneg][0] = nrupper - 1 + nrneg
  4430. }
  4431. nrlower <<= 1
  4432. nrupper <<= 1
  4433. }
  4434. }
  4435. function initRGBYUVTable() {
  4436. for (var i = 0; i < 256; i++) {
  4437. RGB_YUV_TABLE[i] = 19595 * i
  4438. RGB_YUV_TABLE[(i + 256) >> 0] = 38470 * i
  4439. RGB_YUV_TABLE[(i + 512) >> 0] = 7471 * i + 0x8000
  4440. RGB_YUV_TABLE[(i + 768) >> 0] = -11059 * i
  4441. RGB_YUV_TABLE[(i + 1024) >> 0] = -21709 * i
  4442. RGB_YUV_TABLE[(i + 1280) >> 0] = 32768 * i + 0x807fff
  4443. RGB_YUV_TABLE[(i + 1536) >> 0] = -27439 * i
  4444. RGB_YUV_TABLE[(i + 1792) >> 0] = -5329 * i
  4445. }
  4446. }
  4447. // IO functions
  4448. function writeBits(bs) {
  4449. var value = bs[0]
  4450. var posval = bs[1] - 1
  4451. while (posval >= 0) {
  4452. if (value & (1 << posval)) {
  4453. bytenew |= 1 << bytepos
  4454. }
  4455. posval--
  4456. bytepos--
  4457. if (bytepos < 0) {
  4458. if (bytenew == 0xff) {
  4459. writeByte(0xff)
  4460. writeByte(0)
  4461. } else {
  4462. writeByte(bytenew)
  4463. }
  4464. bytepos = 7
  4465. bytenew = 0
  4466. }
  4467. }
  4468. }
  4469. function writeByte(value) {
  4470. byteout.push(clt[value]) // write char directly instead of converting later
  4471. }
  4472. function writeWord(value) {
  4473. writeByte((value >> 8) & 0xff)
  4474. writeByte(value & 0xff)
  4475. }
  4476. // DCT & quantization core
  4477. function fDCTQuant(data, fdtbl) {
  4478. var d0, d1, d2, d3, d4, d5, d6, d7
  4479. /* Pass 1: process rows. */
  4480. var dataOff = 0
  4481. var i
  4482. var I8 = 8
  4483. var I64 = 64
  4484. for (i = 0; i < I8; ++i) {
  4485. d0 = data[dataOff]
  4486. d1 = data[dataOff + 1]
  4487. d2 = data[dataOff + 2]
  4488. d3 = data[dataOff + 3]
  4489. d4 = data[dataOff + 4]
  4490. d5 = data[dataOff + 5]
  4491. d6 = data[dataOff + 6]
  4492. d7 = data[dataOff + 7]
  4493. var tmp0 = d0 + d7
  4494. var tmp7 = d0 - d7
  4495. var tmp1 = d1 + d6
  4496. var tmp6 = d1 - d6
  4497. var tmp2 = d2 + d5
  4498. var tmp5 = d2 - d5
  4499. var tmp3 = d3 + d4
  4500. var tmp4 = d3 - d4
  4501. /* Even part */
  4502. var tmp10 = tmp0 + tmp3 /* phase 2 */
  4503. var tmp13 = tmp0 - tmp3
  4504. var tmp11 = tmp1 + tmp2
  4505. var tmp12 = tmp1 - tmp2
  4506. data[dataOff] = tmp10 + tmp11 /* phase 3 */
  4507. data[dataOff + 4] = tmp10 - tmp11
  4508. var z1 = (tmp12 + tmp13) * 0.707106781 /* c4 */
  4509. data[dataOff + 2] = tmp13 + z1 /* phase 5 */
  4510. data[dataOff + 6] = tmp13 - z1
  4511. /* Odd part */
  4512. tmp10 = tmp4 + tmp5 /* phase 2 */
  4513. tmp11 = tmp5 + tmp6
  4514. tmp12 = tmp6 + tmp7
  4515. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  4516. var z5 = (tmp10 - tmp12) * 0.382683433 /* c6 */
  4517. var z2 = 0.5411961 * tmp10 + z5 /* c2-c6 */
  4518. var z4 = 1.306562965 * tmp12 + z5 /* c2+c6 */
  4519. var z3 = tmp11 * 0.707106781 /* c4 */
  4520. var z11 = tmp7 + z3 /* phase 5 */
  4521. var z13 = tmp7 - z3
  4522. data[dataOff + 5] = z13 + z2 /* phase 6 */
  4523. data[dataOff + 3] = z13 - z2
  4524. data[dataOff + 1] = z11 + z4
  4525. data[dataOff + 7] = z11 - z4
  4526. dataOff += 8 /* advance pointer to next row */
  4527. }
  4528. /* Pass 2: process columns. */
  4529. dataOff = 0
  4530. for (i = 0; i < I8; ++i) {
  4531. d0 = data[dataOff]
  4532. d1 = data[dataOff + 8]
  4533. d2 = data[dataOff + 16]
  4534. d3 = data[dataOff + 24]
  4535. d4 = data[dataOff + 32]
  4536. d5 = data[dataOff + 40]
  4537. d6 = data[dataOff + 48]
  4538. d7 = data[dataOff + 56]
  4539. var tmp0p2 = d0 + d7
  4540. var tmp7p2 = d0 - d7
  4541. var tmp1p2 = d1 + d6
  4542. var tmp6p2 = d1 - d6
  4543. var tmp2p2 = d2 + d5
  4544. var tmp5p2 = d2 - d5
  4545. var tmp3p2 = d3 + d4
  4546. var tmp4p2 = d3 - d4
  4547. /* Even part */
  4548. var tmp10p2 = tmp0p2 + tmp3p2 /* phase 2 */
  4549. var tmp13p2 = tmp0p2 - tmp3p2
  4550. var tmp11p2 = tmp1p2 + tmp2p2
  4551. var tmp12p2 = tmp1p2 - tmp2p2
  4552. data[dataOff] = tmp10p2 + tmp11p2 /* phase 3 */
  4553. data[dataOff + 32] = tmp10p2 - tmp11p2
  4554. var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781 /* c4 */
  4555. data[dataOff + 16] = tmp13p2 + z1p2 /* phase 5 */
  4556. data[dataOff + 48] = tmp13p2 - z1p2
  4557. /* Odd part */
  4558. tmp10p2 = tmp4p2 + tmp5p2 /* phase 2 */
  4559. tmp11p2 = tmp5p2 + tmp6p2
  4560. tmp12p2 = tmp6p2 + tmp7p2
  4561. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  4562. var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433 /* c6 */
  4563. var z2p2 = 0.5411961 * tmp10p2 + z5p2 /* c2-c6 */
  4564. var z4p2 = 1.306562965 * tmp12p2 + z5p2 /* c2+c6 */
  4565. var z3p2 = tmp11p2 * 0.707106781 /* c4 */
  4566. var z11p2 = tmp7p2 + z3p2 /* phase 5 */
  4567. var z13p2 = tmp7p2 - z3p2
  4568. data[dataOff + 40] = z13p2 + z2p2 /* phase 6 */
  4569. data[dataOff + 24] = z13p2 - z2p2
  4570. data[dataOff + 8] = z11p2 + z4p2
  4571. data[dataOff + 56] = z11p2 - z4p2
  4572. dataOff++ /* advance pointer to next column */
  4573. }
  4574. // Quantize/descale the coefficients
  4575. var fDCTQuant
  4576. for (i = 0; i < I64; ++i) {
  4577. // Apply the quantization and scaling factor & Round to nearest integer
  4578. fDCTQuant = data[i] * fdtbl[i]
  4579. outputfDCTQuant[i] =
  4580. fDCTQuant > 0.0 ? (fDCTQuant + 0.5) | 0 : (fDCTQuant - 0.5) | 0
  4581. //outputfDCTQuant[i] = fround(fDCTQuant);
  4582. }
  4583. return outputfDCTQuant
  4584. }
  4585. function writeAPP0() {
  4586. writeWord(0xffe0) // marker
  4587. writeWord(16) // length
  4588. writeByte(0x4a) // J
  4589. writeByte(0x46) // F
  4590. writeByte(0x49) // I
  4591. writeByte(0x46) // F
  4592. writeByte(0) // = "JFIF",'\0'
  4593. writeByte(1) // versionhi
  4594. writeByte(1) // versionlo
  4595. writeByte(0) // xyunits
  4596. writeWord(1) // xdensity
  4597. writeWord(1) // ydensity
  4598. writeByte(0) // thumbnwidth
  4599. writeByte(0) // thumbnheight
  4600. }
  4601. function writeSOF0(width, height) {
  4602. writeWord(0xffc0) // marker
  4603. writeWord(17) // length, truecolor YUV JPG
  4604. writeByte(8) // precision
  4605. writeWord(height)
  4606. writeWord(width)
  4607. writeByte(3) // nrofcomponents
  4608. writeByte(1) // IdY
  4609. writeByte(0x11) // HVY
  4610. writeByte(0) // QTY
  4611. writeByte(2) // IdU
  4612. writeByte(0x11) // HVU
  4613. writeByte(1) // QTU
  4614. writeByte(3) // IdV
  4615. writeByte(0x11) // HVV
  4616. writeByte(1) // QTV
  4617. }
  4618. function writeDQT() {
  4619. writeWord(0xffdb) // marker
  4620. writeWord(132) // length
  4621. writeByte(0)
  4622. for (var i = 0; i < 64; i++) {
  4623. writeByte(YTable[i])
  4624. }
  4625. writeByte(1)
  4626. for (var j = 0; j < 64; j++) {
  4627. writeByte(UVTable[j])
  4628. }
  4629. }
  4630. function writeDHT() {
  4631. writeWord(0xffc4) // marker
  4632. writeWord(0x01a2) // length
  4633. writeByte(0) // HTYDCinfo
  4634. for (var i = 0; i < 16; i++) {
  4635. writeByte(std_dc_luminance_nrcodes[i + 1])
  4636. }
  4637. for (var j = 0; j <= 11; j++) {
  4638. writeByte(std_dc_luminance_values[j])
  4639. }
  4640. writeByte(0x10) // HTYACinfo
  4641. for (var k = 0; k < 16; k++) {
  4642. writeByte(std_ac_luminance_nrcodes[k + 1])
  4643. }
  4644. for (var l = 0; l <= 161; l++) {
  4645. writeByte(std_ac_luminance_values[l])
  4646. }
  4647. writeByte(1) // HTUDCinfo
  4648. for (var m = 0; m < 16; m++) {
  4649. writeByte(std_dc_chrominance_nrcodes[m + 1])
  4650. }
  4651. for (var n = 0; n <= 11; n++) {
  4652. writeByte(std_dc_chrominance_values[n])
  4653. }
  4654. writeByte(0x11) // HTUACinfo
  4655. for (var o = 0; o < 16; o++) {
  4656. writeByte(std_ac_chrominance_nrcodes[o + 1])
  4657. }
  4658. for (var p = 0; p <= 161; p++) {
  4659. writeByte(std_ac_chrominance_values[p])
  4660. }
  4661. }
  4662. function writeSOS() {
  4663. writeWord(0xffda) // marker
  4664. writeWord(12) // length
  4665. writeByte(3) // nrofcomponents
  4666. writeByte(1) // IdY
  4667. writeByte(0) // HTY
  4668. writeByte(2) // IdU
  4669. writeByte(0x11) // HTU
  4670. writeByte(3) // IdV
  4671. writeByte(0x11) // HTV
  4672. writeByte(0) // Ss
  4673. writeByte(0x3f) // Se
  4674. writeByte(0) // Bf
  4675. }
  4676. function processDU(CDU, fdtbl, DC, HTDC, HTAC) {
  4677. var EOB = HTAC[0x00]
  4678. var M16zeroes = HTAC[0xf0]
  4679. var pos
  4680. var I16 = 16
  4681. var I63 = 63
  4682. var I64 = 64
  4683. var DU_DCT = fDCTQuant(CDU, fdtbl)
  4684. //ZigZag reorder
  4685. for (var j = 0; j < I64; ++j) {
  4686. DU[ZigZag[j]] = DU_DCT[j]
  4687. }
  4688. var Diff = DU[0] - DC
  4689. DC = DU[0]
  4690. //Encode DC
  4691. if (Diff == 0) {
  4692. writeBits(HTDC[0]) // Diff might be 0
  4693. } else {
  4694. pos = 32767 + Diff
  4695. writeBits(HTDC[category[pos]])
  4696. writeBits(bitcode[pos])
  4697. }
  4698. //Encode ACs
  4699. var end0pos = 63 // was const... which is crazy
  4700. for (; end0pos > 0 && DU[end0pos] == 0; end0pos--) {}
  4701. //end0pos = first element in reverse order !=0
  4702. if (end0pos == 0) {
  4703. writeBits(EOB)
  4704. return DC
  4705. }
  4706. var i = 1
  4707. var lng
  4708. while (i <= end0pos) {
  4709. var startpos = i
  4710. for (; DU[i] == 0 && i <= end0pos; ++i) {}
  4711. var nrzeroes = i - startpos
  4712. if (nrzeroes >= I16) {
  4713. lng = nrzeroes >> 4
  4714. for (var nrmarker = 1; nrmarker <= lng; ++nrmarker)
  4715. writeBits(M16zeroes)
  4716. nrzeroes = nrzeroes & 0xf
  4717. }
  4718. pos = 32767 + DU[i]
  4719. writeBits(HTAC[(nrzeroes << 4) + category[pos]])
  4720. writeBits(bitcode[pos])
  4721. i++
  4722. }
  4723. if (end0pos != I63) {
  4724. writeBits(EOB)
  4725. }
  4726. return DC
  4727. }
  4728. function initCharLookupTable() {
  4729. var sfcc = String.fromCharCode
  4730. for (var i = 0; i < 256; i++) {
  4731. ///// ACHTUNG // 255
  4732. clt[i] = sfcc(i)
  4733. }
  4734. }
  4735. this.encode = function (
  4736. image,
  4737. quality // image data object
  4738. ) {
  4739. // var time_start = new Date().getTime();
  4740. if (quality) setQuality(quality)
  4741. // Initialize bit writer
  4742. byteout = new Array()
  4743. bytenew = 0
  4744. bytepos = 7
  4745. // Add JPEG headers
  4746. writeWord(0xffd8) // SOI
  4747. writeAPP0()
  4748. writeDQT()
  4749. writeSOF0(image.width, image.height)
  4750. writeDHT()
  4751. writeSOS()
  4752. // Encode 8x8 macroblocks
  4753. var DCY = 0
  4754. var DCU = 0
  4755. var DCV = 0
  4756. bytenew = 0
  4757. bytepos = 7
  4758. this.encode.displayName = '_encode_'
  4759. var imageData = image.data
  4760. var width = image.width
  4761. var height = image.height
  4762. var quadWidth = width * 4
  4763. var tripleWidth = width * 3
  4764. var x,
  4765. y = 0
  4766. var r, g, b
  4767. var start, p, col, row, pos
  4768. while (y < height) {
  4769. x = 0
  4770. while (x < quadWidth) {
  4771. start = quadWidth * y + x
  4772. p = start
  4773. col = -1
  4774. row = 0
  4775. for (pos = 0; pos < 64; pos++) {
  4776. row = pos >> 3 // /8
  4777. col = (pos & 7) * 4 // %8
  4778. p = start + row * quadWidth + col
  4779. if (y + row >= height) {
  4780. // padding bottom
  4781. p -= quadWidth * (y + 1 + row - height)
  4782. }
  4783. if (x + col >= quadWidth) {
  4784. // padding right
  4785. p -= x + col - quadWidth + 4
  4786. }
  4787. r = imageData[p++]
  4788. g = imageData[p++]
  4789. b = imageData[p++]
  4790. /* // calculate YUV values dynamically
  4791. YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80
  4792. UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));
  4793. VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));
  4794. */
  4795. // use lookup table (slightly faster)
  4796. YDU[pos] =
  4797. ((RGB_YUV_TABLE[r] +
  4798. RGB_YUV_TABLE[(g + 256) >> 0] +
  4799. RGB_YUV_TABLE[(b + 512) >> 0]) >>
  4800. 16) -
  4801. 128
  4802. UDU[pos] =
  4803. ((RGB_YUV_TABLE[(r + 768) >> 0] +
  4804. RGB_YUV_TABLE[(g + 1024) >> 0] +
  4805. RGB_YUV_TABLE[(b + 1280) >> 0]) >>
  4806. 16) -
  4807. 128
  4808. VDU[pos] =
  4809. ((RGB_YUV_TABLE[(r + 1280) >> 0] +
  4810. RGB_YUV_TABLE[(g + 1536) >> 0] +
  4811. RGB_YUV_TABLE[(b + 1792) >> 0]) >>
  4812. 16) -
  4813. 128
  4814. }
  4815. DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT)
  4816. DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT)
  4817. DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT)
  4818. x += 32
  4819. }
  4820. y += 8
  4821. }
  4822. ////////////////////////////////////////////////////////////////
  4823. // Do the bit alignment of the EOI marker
  4824. if (bytepos >= 0) {
  4825. var fillbits = []
  4826. fillbits[1] = bytepos + 1
  4827. fillbits[0] = (1 << (bytepos + 1)) - 1
  4828. writeBits(fillbits)
  4829. }
  4830. writeWord(0xffd9) //EOI
  4831. var jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join(''))
  4832. byteout = []
  4833. // benchmarking
  4834. // var duration = new Date().getTime() - time_start;
  4835. // console.log('Encoding time: '+ currentQuality + 'ms');
  4836. //
  4837. return jpegDataUri
  4838. }
  4839. function setQuality(quality) {
  4840. if (quality <= 0) {
  4841. quality = 1
  4842. }
  4843. if (quality > 100) {
  4844. quality = 100
  4845. }
  4846. if (currentQuality == quality) return // don't recalc if unchanged
  4847. var sf = 0
  4848. if (quality < 50) {
  4849. sf = Math.floor(5000 / quality)
  4850. } else {
  4851. sf = Math.floor(200 - quality * 2)
  4852. }
  4853. initQuantTables(sf)
  4854. currentQuality = quality
  4855. // console.log('Quality set to: '+quality +'%');
  4856. }
  4857. function init() {
  4858. // var time_start = new Date().getTime();
  4859. if (!quality) quality = 50
  4860. // Create tables
  4861. initCharLookupTable()
  4862. initHuffmanTbl()
  4863. initCategoryNumber()
  4864. initRGBYUVTable()
  4865. setQuality(quality)
  4866. // var duration = new Date().getTime() - time_start;
  4867. // console.log('Initialization '+ duration + 'ms');
  4868. }
  4869. init()
  4870. }
  4871. JPEGEncoder.encode = function (data, quality) {
  4872. var encoder = new JPEGEncoder(quality)
  4873. return encoder.encode(data)
  4874. }
  4875. return JPEGEncoder
  4876. })
  4877. /**
  4878. * @fileOverview Fix android canvas.toDataUrl bug.
  4879. */
  4880. define('runtime/html5/androidpatch', [
  4881. 'runtime/html5/util',
  4882. 'runtime/html5/jpegencoder',
  4883. 'base'
  4884. ], function (Util, encoder, Base) {
  4885. var origin = Util.canvasToDataUrl,
  4886. supportJpeg
  4887. Util.canvasToDataUrl = function (canvas, type, quality) {
  4888. var ctx, w, h, fragement, parts
  4889. // 非android手机直接跳过。
  4890. if (!Base.os.android) {
  4891. return origin.apply(null, arguments)
  4892. }
  4893. // 检测是否canvas支持jpeg导出,根据数据格式来判断。
  4894. // JPEG 前两位分别是:255, 216
  4895. if (type === 'image/jpeg' && typeof supportJpeg === 'undefined') {
  4896. fragement = origin.apply(null, arguments)
  4897. parts = fragement.split(',')
  4898. if (~parts[0].indexOf('base64')) {
  4899. fragement = atob(parts[1])
  4900. } else {
  4901. fragement = decodeURIComponent(parts[1])
  4902. }
  4903. fragement = fragement.substring(0, 2)
  4904. supportJpeg =
  4905. fragement.charCodeAt(0) === 255 && fragement.charCodeAt(1) === 216
  4906. }
  4907. // 只有在android环境下才修复
  4908. if (type === 'image/jpeg' && !supportJpeg) {
  4909. w = canvas.width
  4910. h = canvas.height
  4911. ctx = canvas.getContext('2d')
  4912. return encoder.encode(ctx.getImageData(0, 0, w, h), quality)
  4913. }
  4914. return origin.apply(null, arguments)
  4915. }
  4916. })
  4917. /**
  4918. * @fileOverview Image
  4919. */
  4920. define('runtime/html5/image', [
  4921. 'base',
  4922. 'runtime/html5/runtime',
  4923. 'runtime/html5/util'
  4924. ], function (Base, Html5Runtime, Util) {
  4925. var BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D'
  4926. return Html5Runtime.register('Image', {
  4927. // flag: 标记是否被修改过。
  4928. modified: false,
  4929. init: function () {
  4930. var me = this,
  4931. img = new Image()
  4932. img.onload = function () {
  4933. me._info = {
  4934. type: me.type,
  4935. width: this.width,
  4936. height: this.height
  4937. }
  4938. // 读取meta信息。
  4939. if (!me._metas && 'image/jpeg' === me.type) {
  4940. Util.parseMeta(me._blob, function (error, ret) {
  4941. me._metas = ret
  4942. me.owner.trigger('load')
  4943. })
  4944. } else {
  4945. me.owner.trigger('load')
  4946. }
  4947. }
  4948. img.onerror = function () {
  4949. me.owner.trigger('error')
  4950. }
  4951. me._img = img
  4952. },
  4953. loadFromBlob: function (blob) {
  4954. var me = this,
  4955. img = me._img
  4956. me._blob = blob
  4957. me.type = blob.type
  4958. img.src = Util.createObjectURL(blob.getSource())
  4959. me.owner.once('load', function () {
  4960. Util.revokeObjectURL(img.src)
  4961. })
  4962. },
  4963. resize: function (width, height) {
  4964. var canvas =
  4965. this._canvas || (this._canvas = document.createElement('canvas'))
  4966. this._resize(this._img, canvas, width, height)
  4967. this._blob = null // 没用了,可以删掉了。
  4968. this.modified = true
  4969. this.owner.trigger('complete')
  4970. },
  4971. getAsBlob: function (type) {
  4972. var blob = this._blob,
  4973. opts = this.options,
  4974. canvas
  4975. type = type || this.type
  4976. // blob需要重新生成。
  4977. if (this.modified || this.type !== type) {
  4978. canvas = this._canvas
  4979. if (type === 'image/jpeg') {
  4980. blob = Util.canvasToDataUrl(canvas, 'image/jpeg', opts.quality)
  4981. if (opts.preserveHeaders && this._metas && this._metas.imageHead) {
  4982. blob = Util.dataURL2ArrayBuffer(blob)
  4983. blob = Util.updateImageHead(blob, this._metas.imageHead)
  4984. blob = Util.arrayBufferToBlob(blob, type)
  4985. return blob
  4986. }
  4987. } else {
  4988. blob = Util.canvasToDataUrl(canvas, type)
  4989. }
  4990. blob = Util.dataURL2Blob(blob)
  4991. }
  4992. return blob
  4993. },
  4994. getAsDataUrl: function (type) {
  4995. var opts = this.options
  4996. type = type || this.type
  4997. if (type === 'image/jpeg') {
  4998. return Util.canvasToDataUrl(this._canvas, type, opts.quality)
  4999. } else {
  5000. return this._canvas.toDataURL(type)
  5001. }
  5002. },
  5003. getOrientation: function () {
  5004. return (
  5005. (this._metas &&
  5006. this._metas.exif &&
  5007. this._metas.exif.get('Orientation')) ||
  5008. 1
  5009. )
  5010. },
  5011. info: function (val) {
  5012. // setter
  5013. if (val) {
  5014. this._info = val
  5015. return this
  5016. }
  5017. // getter
  5018. return this._info
  5019. },
  5020. meta: function (val) {
  5021. // setter
  5022. if (val) {
  5023. this._meta = val
  5024. return this
  5025. }
  5026. // getter
  5027. return this._meta
  5028. },
  5029. destroy: function () {
  5030. var canvas = this._canvas
  5031. this._img.onload = null
  5032. if (canvas) {
  5033. canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height)
  5034. canvas.width = canvas.height = 0
  5035. this._canvas = null
  5036. }
  5037. // 释放内存。非常重要,否则释放不了image的内存。
  5038. this._img.src = BLANK
  5039. this._img = this._blob = null
  5040. },
  5041. _resize: function (img, cvs, width, height) {
  5042. var opts = this.options,
  5043. naturalWidth = img.width,
  5044. naturalHeight = img.height,
  5045. orientation = this.getOrientation(),
  5046. scale,
  5047. w,
  5048. h,
  5049. x,
  5050. y
  5051. // values that require 90 degree rotation
  5052. if (~[5, 6, 7, 8].indexOf(orientation)) {
  5053. // 交换width, height的值。
  5054. width ^= height
  5055. height ^= width
  5056. width ^= height
  5057. }
  5058. scale = Math[opts.crop ? 'max' : 'min'](
  5059. width / naturalWidth,
  5060. height / naturalHeight
  5061. )
  5062. // 不允许放大。
  5063. opts.allowMagnify || (scale = Math.min(1, scale))
  5064. w = naturalWidth * scale
  5065. h = naturalHeight * scale
  5066. if (opts.crop) {
  5067. cvs.width = width
  5068. cvs.height = height
  5069. } else {
  5070. cvs.width = w
  5071. cvs.height = h
  5072. }
  5073. x = (cvs.width - w) / 2
  5074. y = (cvs.height - h) / 2
  5075. opts.preserveHeaders || this._rotate2Orientaion(cvs, orientation)
  5076. this._renderImageToCanvas(cvs, img, x, y, w, h)
  5077. },
  5078. _rotate2Orientaion: function (canvas, orientation) {
  5079. var width = canvas.width,
  5080. height = canvas.height,
  5081. ctx = canvas.getContext('2d')
  5082. switch (orientation) {
  5083. case 5:
  5084. case 6:
  5085. case 7:
  5086. case 8:
  5087. canvas.width = height
  5088. canvas.height = width
  5089. break
  5090. }
  5091. switch (orientation) {
  5092. case 2: // horizontal flip
  5093. ctx.translate(width, 0)
  5094. ctx.scale(-1, 1)
  5095. break
  5096. case 3: // 180 rotate left
  5097. ctx.translate(width, height)
  5098. ctx.rotate(Math.PI)
  5099. break
  5100. case 4: // vertical flip
  5101. ctx.translate(0, height)
  5102. ctx.scale(1, -1)
  5103. break
  5104. case 5: // vertical flip + 90 rotate right
  5105. ctx.rotate(0.5 * Math.PI)
  5106. ctx.scale(1, -1)
  5107. break
  5108. case 6: // 90 rotate right
  5109. ctx.rotate(0.5 * Math.PI)
  5110. ctx.translate(0, -height)
  5111. break
  5112. case 7: // horizontal flip + 90 rotate right
  5113. ctx.rotate(0.5 * Math.PI)
  5114. ctx.translate(width, -height)
  5115. ctx.scale(-1, 1)
  5116. break
  5117. case 8: // 90 rotate left
  5118. ctx.rotate(-0.5 * Math.PI)
  5119. ctx.translate(-width, 0)
  5120. break
  5121. }
  5122. },
  5123. // https://github.com/stomita/ios-imagefile-megapixel/
  5124. // blob/master/src/megapix-image.js
  5125. _renderImageToCanvas: (function () {
  5126. // 如果不是ios, 不需要这么复杂!
  5127. if (!Base.os.ios) {
  5128. return function (canvas, img, x, y, w, h) {
  5129. canvas.getContext('2d').drawImage(img, x, y, w, h)
  5130. }
  5131. }
  5132. /**
  5133. * Detecting vertical squash in loaded image.
  5134. * Fixes a bug which squash image vertically while drawing into
  5135. * canvas for some images.
  5136. */
  5137. function detectVerticalSquash(img, iw, ih) {
  5138. var canvas = document.createElement('canvas'),
  5139. ctx = canvas.getContext('2d'),
  5140. sy = 0,
  5141. ey = ih,
  5142. py = ih,
  5143. data,
  5144. alpha,
  5145. ratio
  5146. canvas.width = 1
  5147. canvas.height = ih
  5148. ctx.drawImage(img, 0, 0)
  5149. data = ctx.getImageData(0, 0, 1, ih).data
  5150. // search image edge pixel position in case
  5151. // it is squashed vertically.
  5152. while (py > sy) {
  5153. alpha = data[(py - 1) * 4 + 3]
  5154. if (alpha === 0) {
  5155. ey = py
  5156. } else {
  5157. sy = py
  5158. }
  5159. py = (ey + sy) >> 1
  5160. }
  5161. ratio = py / ih
  5162. return ratio === 0 ? 1 : ratio
  5163. }
  5164. // fix ie7 bug
  5165. // http://stackoverflow.com/questions/11929099/
  5166. // html5-canvas-drawimage-ratio-bug-ios
  5167. if (Base.os.ios >= 7) {
  5168. return function (canvas, img, x, y, w, h) {
  5169. var iw = img.naturalWidth,
  5170. ih = img.naturalHeight,
  5171. vertSquashRatio = detectVerticalSquash(img, iw, ih)
  5172. return canvas
  5173. .getContext('2d')
  5174. .drawImage(
  5175. img,
  5176. 0,
  5177. 0,
  5178. iw * vertSquashRatio,
  5179. ih * vertSquashRatio,
  5180. x,
  5181. y,
  5182. w,
  5183. h
  5184. )
  5185. }
  5186. }
  5187. /**
  5188. * Detect subsampling in loaded image.
  5189. * In iOS, larger images than 2M pixels may be
  5190. * subsampled in rendering.
  5191. */
  5192. function detectSubsampling(img) {
  5193. var iw = img.naturalWidth,
  5194. ih = img.naturalHeight,
  5195. canvas,
  5196. ctx
  5197. // subsampling may happen overmegapixel image
  5198. if (iw * ih > 1024 * 1024) {
  5199. canvas = document.createElement('canvas')
  5200. canvas.width = canvas.height = 1
  5201. ctx = canvas.getContext('2d')
  5202. ctx.drawImage(img, -iw + 1, 0)
  5203. // subsampled image becomes half smaller in rendering size.
  5204. // check alpha channel value to confirm image is covering
  5205. // edge pixel or not. if alpha value is 0
  5206. // image is not covering, hence subsampled.
  5207. return ctx.getImageData(0, 0, 1, 1).data[3] === 0
  5208. } else {
  5209. return false
  5210. }
  5211. }
  5212. return function (canvas, img, x, y, width, height) {
  5213. var iw = img.naturalWidth,
  5214. ih = img.naturalHeight,
  5215. ctx = canvas.getContext('2d'),
  5216. subsampled = detectSubsampling(img),
  5217. doSquash = this.type === 'image/jpeg',
  5218. d = 1024,
  5219. sy = 0,
  5220. dy = 0,
  5221. tmpCanvas,
  5222. tmpCtx,
  5223. vertSquashRatio,
  5224. dw,
  5225. dh,
  5226. sx,
  5227. dx
  5228. if (subsampled) {
  5229. iw /= 2
  5230. ih /= 2
  5231. }
  5232. ctx.save()
  5233. tmpCanvas = document.createElement('canvas')
  5234. tmpCanvas.width = tmpCanvas.height = d
  5235. tmpCtx = tmpCanvas.getContext('2d')
  5236. vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1
  5237. dw = Math.ceil((d * width) / iw)
  5238. dh = Math.ceil((d * height) / ih / vertSquashRatio)
  5239. while (sy < ih) {
  5240. sx = 0
  5241. dx = 0
  5242. while (sx < iw) {
  5243. tmpCtx.clearRect(0, 0, d, d)
  5244. tmpCtx.drawImage(img, -sx, -sy)
  5245. ctx.drawImage(tmpCanvas, 0, 0, d, d, x + dx, y + dy, dw, dh)
  5246. sx += d
  5247. dx += dw
  5248. }
  5249. sy += d
  5250. dy += dh
  5251. }
  5252. ctx.restore()
  5253. tmpCanvas = tmpCtx = null
  5254. }
  5255. })()
  5256. })
  5257. })
  5258. /**
  5259. * @fileOverview Transport
  5260. * @todo 支持chunked传输,优势:
  5261. * 可以将大文件分成小块,挨个传输,可以提高大文件成功率,当失败的时候,也只需要重传那小部分,
  5262. * 而不需要重头再传一次。另外断点续传也需要用chunked方式。
  5263. */
  5264. define('runtime/html5/transport', [
  5265. 'base',
  5266. 'runtime/html5/runtime'
  5267. ], function (Base, Html5Runtime) {
  5268. var noop = Base.noop,
  5269. $ = Base.$
  5270. return Html5Runtime.register('Transport', {
  5271. init: function () {
  5272. this._status = 0
  5273. this._response = null
  5274. },
  5275. send: function () {
  5276. var owner = this.owner,
  5277. opts = this.options,
  5278. xhr = this._initAjax(),
  5279. blob = owner._blob,
  5280. server = opts.server,
  5281. formData,
  5282. binary,
  5283. fr
  5284. if (opts.sendAsBinary) {
  5285. server += (/\?/.test(server) ? '&' : '?') + $.param(owner._formData)
  5286. binary = blob.getSource()
  5287. } else {
  5288. formData = new FormData()
  5289. $.each(owner._formData, function (k, v) {
  5290. formData.append(k, v)
  5291. })
  5292. formData.append(
  5293. opts.fileVal,
  5294. blob.getSource(),
  5295. opts.filename || owner._formData.name || ''
  5296. )
  5297. }
  5298. if (opts.withCredentials && 'withCredentials' in xhr) {
  5299. xhr.open(opts.method, server, true)
  5300. xhr.withCredentials = true
  5301. } else {
  5302. xhr.open(opts.method, server)
  5303. }
  5304. this._setRequestHeader(xhr, opts.headers)
  5305. if (binary) {
  5306. xhr.overrideMimeType('application/octet-stream')
  5307. // android直接发送blob会导致服务端接收到的是空文件。
  5308. // bug详情。
  5309. // https://code.google.com/p/android/issues/detail?id=39882
  5310. // 所以先用fileReader读取出来再通过arraybuffer的方式发送。
  5311. if (Base.os.android) {
  5312. fr = new FileReader()
  5313. fr.onload = function () {
  5314. xhr.send(this.result)
  5315. fr = fr.onload = null
  5316. }
  5317. fr.readAsArrayBuffer(binary)
  5318. } else {
  5319. xhr.send(binary)
  5320. }
  5321. } else {
  5322. xhr.send(formData)
  5323. }
  5324. },
  5325. getResponse: function () {
  5326. return this._response
  5327. },
  5328. getResponseAsJson: function () {
  5329. return this._parseJson(this._response)
  5330. },
  5331. getStatus: function () {
  5332. return this._status
  5333. },
  5334. abort: function () {
  5335. var xhr = this._xhr
  5336. if (xhr) {
  5337. xhr.upload.onprogress = noop
  5338. xhr.onreadystatechange = noop
  5339. xhr.abort()
  5340. this._xhr = xhr = null
  5341. }
  5342. },
  5343. destroy: function () {
  5344. this.abort()
  5345. },
  5346. _initAjax: function () {
  5347. var me = this,
  5348. xhr = new XMLHttpRequest(),
  5349. opts = this.options
  5350. if (
  5351. opts.withCredentials &&
  5352. !('withCredentials' in xhr) &&
  5353. typeof XDomainRequest !== 'undefined'
  5354. ) {
  5355. xhr = new XDomainRequest()
  5356. }
  5357. xhr.upload.onprogress = function (e) {
  5358. var percentage = 0
  5359. if (e.lengthComputable) {
  5360. percentage = e.loaded / e.total
  5361. }
  5362. return me.trigger('progress', percentage)
  5363. }
  5364. xhr.onreadystatechange = function () {
  5365. if (xhr.readyState !== 4) {
  5366. return
  5367. }
  5368. xhr.upload.onprogress = noop
  5369. xhr.onreadystatechange = noop
  5370. me._xhr = null
  5371. me._status = xhr.status
  5372. if (xhr.status >= 200 && xhr.status < 300) {
  5373. me._response = xhr.responseText
  5374. return me.trigger('load')
  5375. } else if (xhr.status >= 500 && xhr.status < 600) {
  5376. me._response = xhr.responseText
  5377. return me.trigger('error', 'server')
  5378. }
  5379. return me.trigger('error', me._status ? 'http' : 'abort')
  5380. }
  5381. me._xhr = xhr
  5382. return xhr
  5383. },
  5384. _setRequestHeader: function (xhr, headers) {
  5385. $.each(headers, function (key, val) {
  5386. xhr.setRequestHeader(key, val)
  5387. })
  5388. },
  5389. _parseJson: function (str) {
  5390. var json
  5391. try {
  5392. json = JSON.parse(str)
  5393. } catch (ex) {
  5394. json = {}
  5395. }
  5396. return json
  5397. }
  5398. })
  5399. })
  5400. /**
  5401. * @fileOverview FlashRuntime
  5402. */
  5403. define('runtime/flash/runtime', [
  5404. 'base',
  5405. 'runtime/runtime',
  5406. 'runtime/compbase'
  5407. ], function (Base, Runtime, CompBase) {
  5408. var $ = Base.$,
  5409. type = 'flash',
  5410. components = {}
  5411. function getFlashVersion() {
  5412. var version
  5413. try {
  5414. version = navigator.plugins['Shockwave Flash']
  5415. version = version.description
  5416. } catch (ex) {
  5417. try {
  5418. version = new ActiveXObject(
  5419. 'ShockwaveFlash.ShockwaveFlash'
  5420. ).GetVariable('$version')
  5421. } catch (ex2) {
  5422. version = '0.0'
  5423. }
  5424. }
  5425. version = version.match(/\d+/g)
  5426. return parseFloat(version[0] + '.' + version[1], 10)
  5427. }
  5428. function FlashRuntime() {
  5429. var pool = {},
  5430. clients = {},
  5431. destory = this.destory,
  5432. me = this,
  5433. jsreciver = Base.guid('webuploader_')
  5434. Runtime.apply(me, arguments)
  5435. me.type = type
  5436. // 这个方法的调用者,实际上是RuntimeClient
  5437. me.exec = function (comp, fn /*, args...*/) {
  5438. var client = this,
  5439. uid = client.uid,
  5440. args = Base.slice(arguments, 2),
  5441. instance
  5442. clients[uid] = client
  5443. if (components[comp]) {
  5444. if (!pool[uid]) {
  5445. pool[uid] = new components[comp](client, me)
  5446. }
  5447. instance = pool[uid]
  5448. if (instance[fn]) {
  5449. return instance[fn].apply(instance, args)
  5450. }
  5451. }
  5452. return me.flashExec.apply(client, arguments)
  5453. }
  5454. function handler(evt, obj) {
  5455. var type = evt.type || evt,
  5456. parts,
  5457. uid
  5458. parts = type.split('::')
  5459. uid = parts[0]
  5460. type = parts[1]
  5461. // console.log.apply( console, arguments );
  5462. if (type === 'Ready' && uid === me.uid) {
  5463. me.trigger('ready')
  5464. } else if (clients[uid]) {
  5465. clients[uid].trigger(type.toLowerCase(), evt, obj)
  5466. }
  5467. // Base.log( evt, obj );
  5468. }
  5469. // flash的接受器。
  5470. window[jsreciver] = function () {
  5471. var args = arguments
  5472. // 为了能捕获得到。
  5473. setTimeout(function () {
  5474. handler.apply(null, args)
  5475. }, 1)
  5476. }
  5477. this.jsreciver = jsreciver
  5478. this.destory = function () {
  5479. // @todo 删除池子中的所有实例
  5480. return destory && destory.apply(this, arguments)
  5481. }
  5482. this.flashExec = function (comp, fn) {
  5483. var flash = me.getFlash(),
  5484. args = Base.slice(arguments, 2)
  5485. return flash.exec(this.uid, comp, fn, args)
  5486. }
  5487. // @todo
  5488. }
  5489. Base.inherits(Runtime, {
  5490. constructor: FlashRuntime,
  5491. init: function () {
  5492. var container = this.getContainer(),
  5493. opts = this.options,
  5494. html
  5495. // if not the minimal height, shims are not initialized
  5496. // in older browsers (e.g FF3.6, IE6,7,8, Safari 4.0,5.0, etc)
  5497. container.css({
  5498. position: 'absolute',
  5499. top: '-8px',
  5500. left: '-8px',
  5501. width: '9px',
  5502. height: '9px',
  5503. overflow: 'hidden'
  5504. })
  5505. // insert flash object
  5506. html =
  5507. '<object id="' +
  5508. this.uid +
  5509. '" type="application/' +
  5510. 'x-shockwave-flash" data="' +
  5511. opts.swf +
  5512. '" '
  5513. if (Base.browser.ie) {
  5514. html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '
  5515. }
  5516. html +=
  5517. 'width="100%" height="100%" style="outline:0">' +
  5518. '<param name="movie" value="' +
  5519. opts.swf +
  5520. '" />' +
  5521. '<param name="flashvars" value="uid=' +
  5522. this.uid +
  5523. '&jsreciver=' +
  5524. this.jsreciver +
  5525. '" />' +
  5526. '<param name="wmode" value="transparent" />' +
  5527. '<param name="allowscriptaccess" value="always" />' +
  5528. '</object>'
  5529. container.html(html)
  5530. },
  5531. getFlash: function () {
  5532. if (this._flash) {
  5533. return this._flash
  5534. }
  5535. this._flash = $('#' + this.uid).get(0)
  5536. return this._flash
  5537. }
  5538. })
  5539. FlashRuntime.register = function (name, component) {
  5540. component = components[name] = Base.inherits(
  5541. CompBase,
  5542. $.extend(
  5543. {
  5544. // @todo fix this later
  5545. flashExec: function () {
  5546. var owner = this.owner,
  5547. runtime = this.getRuntime()
  5548. return runtime.flashExec.apply(owner, arguments)
  5549. }
  5550. },
  5551. component
  5552. )
  5553. )
  5554. return component
  5555. }
  5556. if (getFlashVersion() >= 11.4) {
  5557. Runtime.addRuntime(type, FlashRuntime)
  5558. }
  5559. return FlashRuntime
  5560. })
  5561. /**
  5562. * @fileOverview FilePicker
  5563. */
  5564. define('runtime/flash/filepicker', [
  5565. 'base',
  5566. 'runtime/flash/runtime'
  5567. ], function (Base, FlashRuntime) {
  5568. var $ = Base.$
  5569. return FlashRuntime.register('FilePicker', {
  5570. init: function (opts) {
  5571. var copy = $.extend({}, opts),
  5572. len,
  5573. i
  5574. // 修复Flash再没有设置title的情况下无法弹出flash文件选择框的bug.
  5575. len = copy.accept && copy.accept.length
  5576. for (i = 0; i < len; i++) {
  5577. if (!copy.accept[i].title) {
  5578. copy.accept[i].title = 'Files'
  5579. }
  5580. }
  5581. delete copy.button
  5582. delete copy.container
  5583. this.flashExec('FilePicker', 'init', copy)
  5584. },
  5585. destroy: function () {
  5586. // todo
  5587. }
  5588. })
  5589. })
  5590. /**
  5591. * @fileOverview 图片压缩
  5592. */
  5593. define('runtime/flash/image', [
  5594. 'runtime/flash/runtime'
  5595. ], function (FlashRuntime) {
  5596. return FlashRuntime.register('Image', {
  5597. // init: function( options ) {
  5598. // var owner = this.owner;
  5599. // this.flashExec( 'Image', 'init', options );
  5600. // owner.on( 'load', function() {
  5601. // debugger;
  5602. // });
  5603. // },
  5604. loadFromBlob: function (blob) {
  5605. var owner = this.owner
  5606. owner.info() && this.flashExec('Image', 'info', owner.info())
  5607. owner.meta() && this.flashExec('Image', 'meta', owner.meta())
  5608. this.flashExec('Image', 'loadFromBlob', blob.uid)
  5609. }
  5610. })
  5611. })
  5612. /**
  5613. * @fileOverview Transport flash实现
  5614. */
  5615. define('runtime/flash/transport', [
  5616. 'base',
  5617. 'runtime/flash/runtime',
  5618. 'runtime/client'
  5619. ], function (Base, FlashRuntime, RuntimeClient) {
  5620. var $ = Base.$
  5621. return FlashRuntime.register('Transport', {
  5622. init: function () {
  5623. this._status = 0
  5624. this._response = null
  5625. this._responseJson = null
  5626. },
  5627. send: function () {
  5628. var owner = this.owner,
  5629. opts = this.options,
  5630. xhr = this._initAjax(),
  5631. blob = owner._blob,
  5632. server = opts.server,
  5633. binary
  5634. xhr.connectRuntime(blob.ruid)
  5635. if (opts.sendAsBinary) {
  5636. server += (/\?/.test(server) ? '&' : '?') + $.param(owner._formData)
  5637. binary = blob.uid
  5638. } else {
  5639. $.each(owner._formData, function (k, v) {
  5640. xhr.exec('append', k, v)
  5641. })
  5642. xhr.exec(
  5643. 'appendBlob',
  5644. opts.fileVal,
  5645. blob.uid,
  5646. opts.filename || owner._formData.name || ''
  5647. )
  5648. }
  5649. this._setRequestHeader(xhr, opts.headers)
  5650. xhr.exec(
  5651. 'send',
  5652. {
  5653. method: opts.method,
  5654. url: server
  5655. },
  5656. binary
  5657. )
  5658. },
  5659. getStatus: function () {
  5660. return this._status
  5661. },
  5662. getResponse: function () {
  5663. return this._response
  5664. },
  5665. getResponseAsJson: function () {
  5666. return this._responseJson
  5667. },
  5668. abort: function () {
  5669. var xhr = this._xhr
  5670. if (xhr) {
  5671. xhr.exec('abort')
  5672. xhr.destroy()
  5673. this._xhr = xhr = null
  5674. }
  5675. },
  5676. destroy: function () {
  5677. this.abort()
  5678. },
  5679. _initAjax: function () {
  5680. var me = this,
  5681. xhr = new RuntimeClient('XMLHttpRequest')
  5682. xhr.on('uploadprogress progress', function (e) {
  5683. return me.trigger('progress', e.loaded / e.total)
  5684. })
  5685. xhr.on('load', function () {
  5686. var status = xhr.exec('getStatus'),
  5687. err = ''
  5688. xhr.off()
  5689. me._xhr = null
  5690. if (status >= 200 && status < 300) {
  5691. me._response = xhr.exec('getResponse')
  5692. me._responseJson = xhr.exec('getResponseAsJson')
  5693. } else if (status >= 500 && status < 600) {
  5694. me._response = xhr.exec('getResponse')
  5695. me._responseJson = xhr.exec('getResponseAsJson')
  5696. err = 'server'
  5697. } else {
  5698. err = 'http'
  5699. }
  5700. xhr.destroy()
  5701. xhr = null
  5702. return err ? me.trigger('error', err) : me.trigger('load')
  5703. })
  5704. xhr.on('error', function () {
  5705. xhr.off()
  5706. me._xhr = null
  5707. me.trigger('error', 'http')
  5708. })
  5709. me._xhr = xhr
  5710. return xhr
  5711. },
  5712. _setRequestHeader: function (xhr, headers) {
  5713. $.each(headers, function (key, val) {
  5714. xhr.exec('setRequestHeader', key, val)
  5715. })
  5716. }
  5717. })
  5718. })
  5719. /**
  5720. * @fileOverview 完全版本。
  5721. */
  5722. define('preset/all', [
  5723. 'base',
  5724. // widgets
  5725. 'widgets/filednd',
  5726. 'widgets/filepaste',
  5727. 'widgets/filepicker',
  5728. 'widgets/image',
  5729. 'widgets/queue',
  5730. 'widgets/runtime',
  5731. 'widgets/upload',
  5732. 'widgets/validator',
  5733. // runtimes
  5734. // html5
  5735. 'runtime/html5/blob',
  5736. 'runtime/html5/dnd',
  5737. 'runtime/html5/filepaste',
  5738. 'runtime/html5/filepicker',
  5739. 'runtime/html5/imagemeta/exif',
  5740. 'runtime/html5/androidpatch',
  5741. 'runtime/html5/image',
  5742. 'runtime/html5/transport',
  5743. // flash
  5744. 'runtime/flash/filepicker',
  5745. 'runtime/flash/image',
  5746. 'runtime/flash/transport'
  5747. ], function (Base) {
  5748. return Base
  5749. })
  5750. define('webuploader', ['preset/all'], function (preset) {
  5751. return preset
  5752. })
  5753. return require('webuploader')
  5754. })