webuploader.custom.js 220 KB

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