webuploader.fis.js 273 KB

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