webuploader.html5only.js 193 KB

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