webuploader.html5nodepend.js 220 KB

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