血透系统PC前端

webuploader.js 227KB

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