Aucune description

webuploader.html5nodepend.js 222KB

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