webuploader.custom.js 216 KB

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