sso

webuploader.js 226KB

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