webuploader.custom.js 194KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671
  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 Blob
  951. */
  952. define('lib/blob',[
  953. 'base',
  954. 'runtime/client'
  955. ], function( Base, RuntimeClient ) {
  956. function Blob( ruid, source ) {
  957. var me = this;
  958. me.source = source;
  959. me.ruid = ruid;
  960. RuntimeClient.call( me, 'Blob' );
  961. this.uid = source.uid || this.uid;
  962. this.type = source.type || '';
  963. this.size = source.size || 0;
  964. if ( ruid ) {
  965. me.connectRuntime( ruid );
  966. }
  967. }
  968. Base.inherits( RuntimeClient, {
  969. constructor: Blob,
  970. slice: function( start, end ) {
  971. return this.exec( 'slice', start, end );
  972. },
  973. getSource: function() {
  974. return this.source;
  975. }
  976. });
  977. return Blob;
  978. });
  979. /**
  980. * 为了统一化Flash的File和HTML5的File而存在。
  981. * 以至于要调用Flash里面的File,也可以像调用HTML5版本的File一下。
  982. * @fileOverview File
  983. */
  984. define('lib/file',[
  985. 'base',
  986. 'lib/blob'
  987. ], function( Base, Blob ) {
  988. var uid = 1,
  989. rExt = /\.([^.]+)$/;
  990. function File( ruid, file ) {
  991. var ext;
  992. Blob.apply( this, arguments );
  993. this.name = file.name || ('untitled' + uid++);
  994. ext = rExt.exec( file.name ) ? RegExp.$1.toLowerCase() : '';
  995. // todo 支持其他类型文件的转换。
  996. // 如果有mimetype, 但是文件名里面没有找出后缀规律
  997. if ( !ext && this.type ) {
  998. ext = /\/(jpg|jpeg|png|gif|bmp)$/i.exec( this.type ) ?
  999. RegExp.$1.toLowerCase() : '';
  1000. this.name += '.' + ext;
  1001. }
  1002. // 如果没有指定mimetype, 但是知道文件后缀。
  1003. if ( !this.type && ~'jpg,jpeg,png,gif,bmp'.indexOf( ext ) ) {
  1004. this.type = 'image/' + (ext === 'jpg' ? 'jpeg' : ext);
  1005. }
  1006. this.ext = ext;
  1007. this.lastModifiedDate = file.lastModifiedDate ||
  1008. (new Date()).toLocaleString();
  1009. }
  1010. return Base.inherits( Blob, File );
  1011. });
  1012. /**
  1013. * @fileOverview 错误信息
  1014. */
  1015. define('lib/filepicker',[
  1016. 'base',
  1017. 'runtime/client',
  1018. 'lib/file'
  1019. ], function( Base, RuntimeClent, File ) {
  1020. var $ = Base.$;
  1021. function FilePicker( opts ) {
  1022. opts = this.options = $.extend({}, FilePicker.options, opts );
  1023. opts.container = $( opts.id );
  1024. if ( !opts.container.length ) {
  1025. throw new Error('按钮指定错误');
  1026. }
  1027. opts.innerHTML = opts.innerHTML || opts.label ||
  1028. opts.container.html() || '';
  1029. opts.button = $( opts.button || document.createElement('div') );
  1030. opts.button.html( opts.innerHTML );
  1031. opts.container.html( opts.button );
  1032. RuntimeClent.call( this, 'FilePicker', true );
  1033. }
  1034. FilePicker.options = {
  1035. button: null,
  1036. container: null,
  1037. label: null,
  1038. innerHTML: null,
  1039. multiple: true,
  1040. accept: null,
  1041. name: 'file'
  1042. };
  1043. Base.inherits( RuntimeClent, {
  1044. constructor: FilePicker,
  1045. init: function() {
  1046. var me = this,
  1047. opts = me.options,
  1048. button = opts.button;
  1049. button.addClass('webuploader-pick');
  1050. me.on( 'all', function( type ) {
  1051. var files;
  1052. switch ( type ) {
  1053. case 'mouseenter':
  1054. button.addClass('webuploader-pick-hover');
  1055. break;
  1056. case 'mouseleave':
  1057. button.removeClass('webuploader-pick-hover');
  1058. break;
  1059. case 'change':
  1060. files = me.exec('getFiles');
  1061. me.trigger( 'select', $.map( files, function( file ) {
  1062. file = new File( me.getRuid(), file );
  1063. // 记录来源。
  1064. file._refer = opts.container;
  1065. return file;
  1066. }), opts.container );
  1067. break;
  1068. }
  1069. });
  1070. me.connectRuntime( opts, function() {
  1071. me.refresh();
  1072. me.exec( 'init', opts );
  1073. me.trigger('ready');
  1074. });
  1075. $( window ).on( 'resize', function() {
  1076. me.refresh();
  1077. });
  1078. },
  1079. refresh: function() {
  1080. var shimContainer = this.getRuntime().getContainer(),
  1081. button = this.options.button,
  1082. width = button.outerWidth ?
  1083. button.outerWidth() : button.width(),
  1084. height = button.outerHeight ?
  1085. button.outerHeight() : button.height(),
  1086. pos = button.offset();
  1087. width && height && shimContainer.css({
  1088. bottom: 'auto',
  1089. right: 'auto',
  1090. width: width + 'px',
  1091. height: height + 'px'
  1092. }).offset( pos );
  1093. },
  1094. enable: function() {
  1095. var btn = this.options.button;
  1096. btn.removeClass('webuploader-pick-disable');
  1097. this.refresh();
  1098. },
  1099. disable: function() {
  1100. var btn = this.options.button;
  1101. this.getRuntime().getContainer().css({
  1102. top: '-99999px'
  1103. });
  1104. btn.addClass('webuploader-pick-disable');
  1105. },
  1106. destroy: function() {
  1107. if ( this.runtime ) {
  1108. this.exec('destroy');
  1109. this.disconnectRuntime();
  1110. }
  1111. }
  1112. });
  1113. return FilePicker;
  1114. });
  1115. /**
  1116. * @fileOverview 组件基类。
  1117. */
  1118. define('widgets/widget',[
  1119. 'base',
  1120. 'uploader'
  1121. ], function( Base, Uploader ) {
  1122. var $ = Base.$,
  1123. _init = Uploader.prototype._init,
  1124. IGNORE = {},
  1125. widgetClass = [];
  1126. function isArrayLike( obj ) {
  1127. if ( !obj ) {
  1128. return false;
  1129. }
  1130. var length = obj.length,
  1131. type = $.type( obj );
  1132. if ( obj.nodeType === 1 && length ) {
  1133. return true;
  1134. }
  1135. return type === 'array' || type !== 'function' && type !== 'string' &&
  1136. (length === 0 || typeof length === 'number' && length > 0 &&
  1137. (length - 1) in obj);
  1138. }
  1139. function Widget( uploader ) {
  1140. this.owner = uploader;
  1141. this.options = uploader.options;
  1142. }
  1143. $.extend( Widget.prototype, {
  1144. init: Base.noop,
  1145. // 类Backbone的事件监听声明,监听uploader实例上的事件
  1146. // widget直接无法监听事件,事件只能通过uploader来传递
  1147. invoke: function( apiName, args ) {
  1148. /*
  1149. {
  1150. 'make-thumb': 'makeThumb'
  1151. }
  1152. */
  1153. var map = this.responseMap;
  1154. // 如果无API响应声明则忽略
  1155. if ( !map || !(apiName in map) || !(map[ apiName ] in this) ||
  1156. !$.isFunction( this[ map[ apiName ] ] ) ) {
  1157. return IGNORE;
  1158. }
  1159. return this[ map[ apiName ] ].apply( this, args );
  1160. },
  1161. /**
  1162. * 发送命令。当传入`callback`或者`handler`中返回`promise`时。返回一个当所有`handler`中的promise都完成后完成的新`promise`。
  1163. * @method request
  1164. * @grammar request( command, args ) => * | Promise
  1165. * @grammar request( command, args, callback ) => Promise
  1166. * @for Uploader
  1167. */
  1168. request: function() {
  1169. return this.owner.request.apply( this.owner, arguments );
  1170. }
  1171. });
  1172. // 扩展Uploader.
  1173. $.extend( Uploader.prototype, {
  1174. // 覆写_init用来初始化widgets
  1175. _init: function() {
  1176. var me = this,
  1177. widgets = me._widgets = [];
  1178. $.each( widgetClass, function( _, klass ) {
  1179. widgets.push( new klass( me ) );
  1180. });
  1181. return _init.apply( me, arguments );
  1182. },
  1183. request: function( apiName, args, callback ) {
  1184. var i = 0,
  1185. widgets = this._widgets,
  1186. len = widgets.length,
  1187. rlts = [],
  1188. dfds = [],
  1189. widget, rlt, promise, key;
  1190. args = isArrayLike( args ) ? args : [ args ];
  1191. for ( ; i < len; i++ ) {
  1192. widget = widgets[ i ];
  1193. rlt = widget.invoke( apiName, args );
  1194. if ( rlt !== IGNORE ) {
  1195. // Deferred对象
  1196. if ( Base.isPromise( rlt ) ) {
  1197. dfds.push( rlt );
  1198. } else {
  1199. rlts.push( rlt );
  1200. }
  1201. }
  1202. }
  1203. // 如果有callback,则用异步方式。
  1204. if ( callback || dfds.length ) {
  1205. promise = Base.when.apply( Base, dfds );
  1206. key = promise.pipe ? 'pipe' : 'then';
  1207. // 很重要不能删除。删除了会死循环。
  1208. // 保证执行顺序。让callback总是在下一个tick中执行。
  1209. return promise[ key ](function() {
  1210. var deferred = Base.Deferred(),
  1211. args = arguments;
  1212. setTimeout(function() {
  1213. deferred.resolve.apply( deferred, args );
  1214. }, 1 );
  1215. return deferred.promise();
  1216. })[ key ]( callback || Base.noop );
  1217. } else {
  1218. return rlts[ 0 ];
  1219. }
  1220. }
  1221. });
  1222. /**
  1223. * 添加组件
  1224. * @param {object} widgetProto 组件原型,构造函数通过constructor属性定义
  1225. * @param {object} responseMap API名称与函数实现的映射
  1226. * @example
  1227. * Uploader.register( {
  1228. * init: function( options ) {},
  1229. * makeThumb: function() {}
  1230. * }, {
  1231. * 'make-thumb': 'makeThumb'
  1232. * } );
  1233. */
  1234. Uploader.register = Widget.register = function( responseMap, widgetProto ) {
  1235. var map = { init: 'init' },
  1236. klass;
  1237. if ( arguments.length === 1 ) {
  1238. widgetProto = responseMap;
  1239. widgetProto.responseMap = map;
  1240. } else {
  1241. widgetProto.responseMap = $.extend( map, responseMap );
  1242. }
  1243. klass = Base.inherits( Widget, widgetProto );
  1244. widgetClass.push( klass );
  1245. return klass;
  1246. };
  1247. return Widget;
  1248. });
  1249. /**
  1250. * @fileOverview 文件选择相关
  1251. */
  1252. define('widgets/filepicker',[
  1253. 'base',
  1254. 'uploader',
  1255. 'lib/filepicker',
  1256. 'widgets/widget'
  1257. ], function( Base, Uploader, FilePicker ) {
  1258. var $ = Base.$;
  1259. $.extend( Uploader.options, {
  1260. /**
  1261. * @property {Selector | Object} [pick=undefined]
  1262. * @namespace options
  1263. * @for Uploader
  1264. * @description 指定选择文件的按钮容器,不指定则不创建按钮。
  1265. *
  1266. * * `id` {Seletor} 指定选择文件的按钮容器,不指定则不创建按钮。
  1267. * * `label` {String} 请采用 `innerHTML` 代替
  1268. * * `innerHTML` {String} 指定按钮文字。不指定时优先从指定的容器中看是否自带文字。
  1269. * * `multiple` {Boolean} 是否开起同时选择多个文件能力。
  1270. */
  1271. pick: null,
  1272. /**
  1273. * @property {Arroy} [accept=null]
  1274. * @namespace options
  1275. * @for Uploader
  1276. * @description 指定接受哪些类型的文件。 由于目前还有ext转mimeType表,所以这里需要分开指定。
  1277. *
  1278. * * `title` {String} 文字描述
  1279. * * `extensions` {String} 允许的文件后缀,不带点,多个用逗号分割。
  1280. * * `mimeTypes` {String} 多个用逗号分割。
  1281. *
  1282. * 如:
  1283. *
  1284. * ```
  1285. * {
  1286. * title: 'Images',
  1287. * extensions: 'gif,jpg,jpeg,bmp,png',
  1288. * mimeTypes: 'image/*'
  1289. * }
  1290. * ```
  1291. */
  1292. accept: null/*{
  1293. title: 'Images',
  1294. extensions: 'gif,jpg,jpeg,bmp,png',
  1295. mimeTypes: 'image/*'
  1296. }*/
  1297. });
  1298. return Uploader.register({
  1299. 'add-btn': 'addButton',
  1300. refresh: 'refresh',
  1301. disable: 'disable',
  1302. enable: 'enable'
  1303. }, {
  1304. init: function( opts ) {
  1305. this.pickers = [];
  1306. return opts.pick && this.addButton( opts.pick );
  1307. },
  1308. refresh: function() {
  1309. $.each( this.pickers, function() {
  1310. this.refresh();
  1311. });
  1312. },
  1313. /**
  1314. * @method addButton
  1315. * @for Uploader
  1316. * @grammar addButton( pick ) => Promise
  1317. * @description
  1318. * 添加文件选择按钮,如果一个按钮不够,需要调用此方法来添加。参数跟[options.pick](#WebUploader:Uploader:options)一致。
  1319. * @example
  1320. * uploader.addButton({
  1321. * id: '#btnContainer',
  1322. * innerHTML: '选择文件'
  1323. * });
  1324. */
  1325. addButton: function( pick ) {
  1326. var me = this,
  1327. opts = me.options,
  1328. accept = opts.accept,
  1329. options, picker, deferred;
  1330. if ( !pick ) {
  1331. return;
  1332. }
  1333. deferred = Base.Deferred();
  1334. $.isPlainObject( pick ) || (pick = {
  1335. id: pick
  1336. });
  1337. options = $.extend({}, pick, {
  1338. accept: $.isPlainObject( accept ) ? [ accept ] : accept,
  1339. swf: opts.swf,
  1340. runtimeOrder: opts.runtimeOrder
  1341. });
  1342. picker = new FilePicker( options );
  1343. picker.once( 'ready', deferred.resolve );
  1344. picker.on( 'select', function( files ) {
  1345. me.owner.request( 'add-file', [ files ]);
  1346. });
  1347. picker.init();
  1348. this.pickers.push( picker );
  1349. return deferred.promise();
  1350. },
  1351. disable: function() {
  1352. $.each( this.pickers, function() {
  1353. this.disable();
  1354. });
  1355. },
  1356. enable: function() {
  1357. $.each( this.pickers, function() {
  1358. this.enable();
  1359. });
  1360. }
  1361. });
  1362. });
  1363. /**
  1364. * @fileOverview Image
  1365. */
  1366. define('lib/image',[
  1367. 'base',
  1368. 'runtime/client',
  1369. 'lib/blob'
  1370. ], function( Base, RuntimeClient, Blob ) {
  1371. var $ = Base.$;
  1372. // 构造器。
  1373. function Image( opts ) {
  1374. this.options = $.extend({}, Image.options, opts );
  1375. RuntimeClient.call( this, 'Image' );
  1376. this.on( 'load', function() {
  1377. this._info = this.exec('info');
  1378. this._meta = this.exec('meta');
  1379. });
  1380. }
  1381. // 默认选项。
  1382. Image.options = {
  1383. // 默认的图片处理质量
  1384. quality: 90,
  1385. // 是否裁剪
  1386. crop: false,
  1387. // 是否保留头部信息
  1388. preserveHeaders: true,
  1389. // 是否允许放大。
  1390. allowMagnify: true
  1391. };
  1392. // 继承RuntimeClient.
  1393. Base.inherits( RuntimeClient, {
  1394. constructor: Image,
  1395. info: function( val ) {
  1396. // setter
  1397. if ( val ) {
  1398. this._info = val;
  1399. return this;
  1400. }
  1401. // getter
  1402. return this._info;
  1403. },
  1404. meta: function( val ) {
  1405. // setter
  1406. if ( val ) {
  1407. this._meta = val;
  1408. return this;
  1409. }
  1410. // getter
  1411. return this._meta;
  1412. },
  1413. loadFromBlob: function( blob ) {
  1414. var me = this,
  1415. ruid = blob.getRuid();
  1416. this.connectRuntime( ruid, function() {
  1417. me.exec( 'init', me.options );
  1418. me.exec( 'loadFromBlob', blob );
  1419. });
  1420. },
  1421. resize: function() {
  1422. var args = Base.slice( arguments );
  1423. return this.exec.apply( this, [ 'resize' ].concat( args ) );
  1424. },
  1425. getAsDataUrl: function( type ) {
  1426. return this.exec( 'getAsDataUrl', type );
  1427. },
  1428. getAsBlob: function( type ) {
  1429. var blob = this.exec( 'getAsBlob', type );
  1430. return new Blob( this.getRuid(), blob );
  1431. }
  1432. });
  1433. return Image;
  1434. });
  1435. /**
  1436. * @fileOverview 图片操作, 负责预览图片和上传前压缩图片
  1437. */
  1438. define('widgets/image',[
  1439. 'base',
  1440. 'uploader',
  1441. 'lib/image',
  1442. 'widgets/widget'
  1443. ], function( Base, Uploader, Image ) {
  1444. var $ = Base.$,
  1445. throttle;
  1446. // 根据要处理的文件大小来节流,一次不能处理太多,会卡。
  1447. throttle = (function( max ) {
  1448. var occupied = 0,
  1449. waiting = [],
  1450. tick = function() {
  1451. var item;
  1452. while ( waiting.length && occupied < max ) {
  1453. item = waiting.shift();
  1454. occupied += item[ 0 ];
  1455. item[ 1 ]();
  1456. }
  1457. };
  1458. return function( emiter, size, cb ) {
  1459. waiting.push([ size, cb ]);
  1460. emiter.once( 'destroy', function() {
  1461. occupied -= size;
  1462. setTimeout( tick, 1 );
  1463. });
  1464. setTimeout( tick, 1 );
  1465. };
  1466. })( 5 * 1024 * 1024 );
  1467. $.extend( Uploader.options, {
  1468. /**
  1469. * @property {Object} [thumb]
  1470. * @namespace options
  1471. * @for Uploader
  1472. * @description 配置生成缩略图的选项。
  1473. *
  1474. * 默认为:
  1475. *
  1476. * ```javascript
  1477. * {
  1478. * width: 110,
  1479. * height: 110,
  1480. *
  1481. * // 图片质量,只有type为`image/jpeg`的时候才有效。
  1482. * quality: 70,
  1483. *
  1484. * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
  1485. * allowMagnify: true,
  1486. *
  1487. * // 是否允许裁剪。
  1488. * crop: true,
  1489. *
  1490. * // 是否保留头部meta信息。
  1491. * preserveHeaders: false,
  1492. *
  1493. * // 为空的话则保留原有图片格式。
  1494. * // 否则强制转换成指定的类型。
  1495. * type: 'image/jpeg'
  1496. * }
  1497. * ```
  1498. */
  1499. thumb: {
  1500. width: 110,
  1501. height: 110,
  1502. quality: 70,
  1503. allowMagnify: true,
  1504. crop: true,
  1505. preserveHeaders: false,
  1506. // 为空的话则保留原有图片格式。
  1507. // 否则强制转换成指定的类型。
  1508. // IE 8下面 base64 大小不能超过 32K 否则预览失败,而非 jpeg 编码的图片很可
  1509. // 能会超过 32k, 所以这里设置成预览的时候都是 image/jpeg
  1510. type: 'image/jpeg'
  1511. },
  1512. /**
  1513. * @property {Object} [compress]
  1514. * @namespace options
  1515. * @for Uploader
  1516. * @description 配置压缩的图片的选项。如果此选项为`false`, 则图片在上传前不进行压缩。
  1517. *
  1518. * 默认为:
  1519. *
  1520. * ```javascript
  1521. * {
  1522. * width: 1600,
  1523. * height: 1600,
  1524. *
  1525. * // 图片质量,只有type为`image/jpeg`的时候才有效。
  1526. * quality: 90,
  1527. *
  1528. * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
  1529. * allowMagnify: false,
  1530. *
  1531. * // 是否允许裁剪。
  1532. * crop: false,
  1533. *
  1534. * // 是否保留头部meta信息。
  1535. * preserveHeaders: true
  1536. * }
  1537. * ```
  1538. */
  1539. compress: {
  1540. width: 1600,
  1541. height: 1600,
  1542. quality: 90,
  1543. allowMagnify: false,
  1544. crop: false,
  1545. preserveHeaders: true
  1546. }
  1547. });
  1548. return Uploader.register({
  1549. 'make-thumb': 'makeThumb',
  1550. 'before-send-file': 'compressImage'
  1551. }, {
  1552. /**
  1553. * 生成缩略图,此过程为异步,所以需要传入`callback`。
  1554. * 通常情况在图片加入队里后调用此方法来生成预览图以增强交互效果。
  1555. *
  1556. * `callback`中可以接收到两个参数。
  1557. * * 第一个为error,如果生成缩略图有错误,此error将为真。
  1558. * * 第二个为ret, 缩略图的Data URL值。
  1559. *
  1560. * **注意**
  1561. * Date URL在IE6/7中不支持,所以不用调用此方法了,直接显示一张暂不支持预览图片好了。
  1562. *
  1563. *
  1564. * @method makeThumb
  1565. * @grammar makeThumb( file, callback ) => undefined
  1566. * @grammar makeThumb( file, callback, width, height ) => undefined
  1567. * @for Uploader
  1568. * @example
  1569. *
  1570. * uploader.on( 'fileQueued', function( file ) {
  1571. * var $li = ...;
  1572. *
  1573. * uploader.makeThumb( file, function( error, ret ) {
  1574. * if ( error ) {
  1575. * $li.text('预览错误');
  1576. * } else {
  1577. * $li.append('<img alt="" src="' + ret + '" />');
  1578. * }
  1579. * });
  1580. *
  1581. * });
  1582. */
  1583. makeThumb: function( file, cb, width, height ) {
  1584. var opts, image;
  1585. file = this.request( 'get-file', file );
  1586. // 只预览图片格式。
  1587. if ( !file.type.match( /^image/ ) ) {
  1588. cb( true );
  1589. return;
  1590. }
  1591. opts = $.extend({}, this.options.thumb );
  1592. // 如果传入的是object.
  1593. if ( $.isPlainObject( width ) ) {
  1594. opts = $.extend( opts, width );
  1595. width = null;
  1596. }
  1597. width = width || opts.width;
  1598. height = height || opts.height;
  1599. image = new Image( opts );
  1600. image.once( 'load', function() {
  1601. file._info = file._info || image.info();
  1602. file._meta = file._meta || image.meta();
  1603. image.resize( width, height );
  1604. });
  1605. image.once( 'complete', function() {
  1606. cb( false, image.getAsDataUrl( opts.type ) );
  1607. image.destroy();
  1608. });
  1609. image.once( 'error', function() {
  1610. cb( true );
  1611. image.destroy();
  1612. });
  1613. throttle( image, file.source.size, function() {
  1614. file._info && image.info( file._info );
  1615. file._meta && image.meta( file._meta );
  1616. image.loadFromBlob( file.source );
  1617. });
  1618. },
  1619. compressImage: function( file ) {
  1620. var opts = this.options.compress || this.options.resize,
  1621. compressSize = opts && opts.compressSize || 300 * 1024,
  1622. image, deferred;
  1623. file = this.request( 'get-file', file );
  1624. // 只预览图片格式。
  1625. if ( !opts || !~'image/jpeg,image/jpg'.indexOf( file.type ) ||
  1626. file.size < compressSize ||
  1627. file._compressed ) {
  1628. return;
  1629. }
  1630. opts = $.extend({}, opts );
  1631. deferred = Base.Deferred();
  1632. image = new Image( opts );
  1633. deferred.always(function() {
  1634. image.destroy();
  1635. image = null;
  1636. });
  1637. image.once( 'error', deferred.reject );
  1638. image.once( 'load', function() {
  1639. file._info = file._info || image.info();
  1640. file._meta = file._meta || image.meta();
  1641. image.resize( opts.width, opts.height );
  1642. });
  1643. image.once( 'complete', function() {
  1644. var blob, size;
  1645. // 移动端 UC / qq 浏览器的无图模式下
  1646. // ctx.getImageData 处理大图的时候会报 Exception
  1647. // INDEX_SIZE_ERR: DOM Exception 1
  1648. try {
  1649. blob = image.getAsBlob( opts.type );
  1650. size = file.size;
  1651. // 如果压缩后,比原来还大则不用压缩后的。
  1652. if ( blob.size < size ) {
  1653. // file.source.destroy && file.source.destroy();
  1654. file.source = blob;
  1655. file.size = blob.size;
  1656. file.trigger( 'resize', blob.size, size );
  1657. }
  1658. // 标记,避免重复压缩。
  1659. file._compressed = true;
  1660. deferred.resolve();
  1661. } catch ( e ) {
  1662. // 出错了直接继续,让其上传原始图片
  1663. deferred.resolve();
  1664. }
  1665. });
  1666. file._info && image.info( file._info );
  1667. file._meta && image.meta( file._meta );
  1668. image.loadFromBlob( file.source );
  1669. return deferred.promise();
  1670. }
  1671. });
  1672. });
  1673. /**
  1674. * @fileOverview 文件属性封装
  1675. */
  1676. define('file',[
  1677. 'base',
  1678. 'mediator'
  1679. ], function( Base, Mediator ) {
  1680. var $ = Base.$,
  1681. idPrefix = 'WU_FILE_',
  1682. idSuffix = 0,
  1683. rExt = /\.([^.]+)$/,
  1684. statusMap = {};
  1685. function gid() {
  1686. return idPrefix + idSuffix++;
  1687. }
  1688. /**
  1689. * 文件类
  1690. * @class File
  1691. * @constructor 构造函数
  1692. * @grammar new File( source ) => File
  1693. * @param {Lib.File} source [lib.File](#Lib.File)实例, 此source对象是带有Runtime信息的。
  1694. */
  1695. function WUFile( source ) {
  1696. /**
  1697. * 文件名,包括扩展名(后缀)
  1698. * @property name
  1699. * @type {string}
  1700. */
  1701. this.name = source.name || 'Untitled';
  1702. /**
  1703. * 文件体积(字节)
  1704. * @property size
  1705. * @type {uint}
  1706. * @default 0
  1707. */
  1708. this.size = source.size || 0;
  1709. /**
  1710. * 文件MIMETYPE类型,与文件类型的对应关系请参考[http://t.cn/z8ZnFny](http://t.cn/z8ZnFny)
  1711. * @property type
  1712. * @type {string}
  1713. * @default 'application'
  1714. */
  1715. this.type = source.type || 'application';
  1716. /**
  1717. * 文件最后修改日期
  1718. * @property lastModifiedDate
  1719. * @type {int}
  1720. * @default 当前时间戳
  1721. */
  1722. this.lastModifiedDate = source.lastModifiedDate || (new Date() * 1);
  1723. /**
  1724. * 文件ID,每个对象具有唯一ID,与文件名无关
  1725. * @property id
  1726. * @type {string}
  1727. */
  1728. this.id = gid();
  1729. /**
  1730. * 文件扩展名,通过文件名获取,例如test.png的扩展名为png
  1731. * @property ext
  1732. * @type {string}
  1733. */
  1734. this.ext = rExt.exec( this.name ) ? RegExp.$1 : '';
  1735. /**
  1736. * 状态文字说明。在不同的status语境下有不同的用途。
  1737. * @property statusText
  1738. * @type {string}
  1739. */
  1740. this.statusText = '';
  1741. // 存储文件状态,防止通过属性直接修改
  1742. statusMap[ this.id ] = WUFile.Status.INITED;
  1743. this.source = source;
  1744. this.loaded = 0;
  1745. this.on( 'error', function( msg ) {
  1746. this.setStatus( WUFile.Status.ERROR, msg );
  1747. });
  1748. }
  1749. $.extend( WUFile.prototype, {
  1750. /**
  1751. * 设置状态,状态变化时会触发`change`事件。
  1752. * @method setStatus
  1753. * @grammar setStatus( status[, statusText] );
  1754. * @param {File.Status|String} status [文件状态值](#WebUploader:File:File.Status)
  1755. * @param {String} [statusText=''] 状态说明,常在error时使用,用http, abort,server等来标记是由于什么原因导致文件错误。
  1756. */
  1757. setStatus: function( status, text ) {
  1758. var prevStatus = statusMap[ this.id ];
  1759. typeof text !== 'undefined' && (this.statusText = text);
  1760. if ( status !== prevStatus ) {
  1761. statusMap[ this.id ] = status;
  1762. /**
  1763. * 文件状态变化
  1764. * @event statuschange
  1765. */
  1766. this.trigger( 'statuschange', status, prevStatus );
  1767. }
  1768. },
  1769. /**
  1770. * 获取文件状态
  1771. * @return {File.Status}
  1772. * @example
  1773. 文件状态具体包括以下几种类型:
  1774. {
  1775. // 初始化
  1776. INITED: 0,
  1777. // 已入队列
  1778. QUEUED: 1,
  1779. // 正在上传
  1780. PROGRESS: 2,
  1781. // 上传出错
  1782. ERROR: 3,
  1783. // 上传成功
  1784. COMPLETE: 4,
  1785. // 上传取消
  1786. CANCELLED: 5
  1787. }
  1788. */
  1789. getStatus: function() {
  1790. return statusMap[ this.id ];
  1791. },
  1792. /**
  1793. * 获取文件原始信息。
  1794. * @return {*}
  1795. */
  1796. getSource: function() {
  1797. return this.source;
  1798. },
  1799. destory: function() {
  1800. delete statusMap[ this.id ];
  1801. }
  1802. });
  1803. Mediator.installTo( WUFile.prototype );
  1804. /**
  1805. * 文件状态值,具体包括以下几种类型:
  1806. * * `inited` 初始状态
  1807. * * `queued` 已经进入队列, 等待上传
  1808. * * `progress` 上传中
  1809. * * `complete` 上传完成。
  1810. * * `error` 上传出错,可重试
  1811. * * `interrupt` 上传中断,可续传。
  1812. * * `invalid` 文件不合格,不能重试上传。会自动从队列中移除。
  1813. * * `cancelled` 文件被移除。
  1814. * @property {Object} Status
  1815. * @namespace File
  1816. * @class File
  1817. * @static
  1818. */
  1819. WUFile.Status = {
  1820. INITED: 'inited', // 初始状态
  1821. QUEUED: 'queued', // 已经进入队列, 等待上传
  1822. PROGRESS: 'progress', // 上传中
  1823. ERROR: 'error', // 上传出错,可重试
  1824. COMPLETE: 'complete', // 上传完成。
  1825. CANCELLED: 'cancelled', // 上传取消。
  1826. INTERRUPT: 'interrupt', // 上传中断,可续传。
  1827. INVALID: 'invalid' // 文件不合格,不能重试上传。
  1828. };
  1829. return WUFile;
  1830. });
  1831. /**
  1832. * @fileOverview 文件队列
  1833. */
  1834. define('queue',[
  1835. 'base',
  1836. 'mediator',
  1837. 'file'
  1838. ], function( Base, Mediator, WUFile ) {
  1839. var $ = Base.$,
  1840. STATUS = WUFile.Status;
  1841. /**
  1842. * 文件队列, 用来存储各个状态中的文件。
  1843. * @class Queue
  1844. * @extends Mediator
  1845. */
  1846. function Queue() {
  1847. /**
  1848. * 统计文件数。
  1849. * * `numOfQueue` 队列中的文件数。
  1850. * * `numOfSuccess` 上传成功的文件数
  1851. * * `numOfCancel` 被移除的文件数
  1852. * * `numOfProgress` 正在上传中的文件数
  1853. * * `numOfUploadFailed` 上传错误的文件数。
  1854. * * `numOfInvalid` 无效的文件数。
  1855. * @property {Object} stats
  1856. */
  1857. this.stats = {
  1858. numOfQueue: 0,
  1859. numOfSuccess: 0,
  1860. numOfCancel: 0,
  1861. numOfProgress: 0,
  1862. numOfUploadFailed: 0,
  1863. numOfInvalid: 0
  1864. };
  1865. // 上传队列,仅包括等待上传的文件
  1866. this._queue = [];
  1867. // 存储所有文件
  1868. this._map = {};
  1869. }
  1870. $.extend( Queue.prototype, {
  1871. /**
  1872. * 将新文件加入对队列尾部
  1873. *
  1874. * @method append
  1875. * @param {File} file 文件对象
  1876. */
  1877. append: function( file ) {
  1878. this._queue.push( file );
  1879. this._fileAdded( file );
  1880. return this;
  1881. },
  1882. /**
  1883. * 将新文件加入对队列头部
  1884. *
  1885. * @method prepend
  1886. * @param {File} file 文件对象
  1887. */
  1888. prepend: function( file ) {
  1889. this._queue.unshift( file );
  1890. this._fileAdded( file );
  1891. return this;
  1892. },
  1893. /**
  1894. * 获取文件对象
  1895. *
  1896. * @method getFile
  1897. * @param {String} fileId 文件ID
  1898. * @return {File}
  1899. */
  1900. getFile: function( fileId ) {
  1901. if ( typeof fileId !== 'string' ) {
  1902. return fileId;
  1903. }
  1904. return this._map[ fileId ];
  1905. },
  1906. /**
  1907. * 从队列中取出一个指定状态的文件。
  1908. * @grammar fetch( status ) => File
  1909. * @method fetch
  1910. * @param {String} status [文件状态值](#WebUploader:File:File.Status)
  1911. * @return {File} [File](#WebUploader:File)
  1912. */
  1913. fetch: function( status ) {
  1914. var len = this._queue.length,
  1915. i, file;
  1916. status = status || STATUS.QUEUED;
  1917. for ( i = 0; i < len; i++ ) {
  1918. file = this._queue[ i ];
  1919. if ( status === file.getStatus() ) {
  1920. return file;
  1921. }
  1922. }
  1923. return null;
  1924. },
  1925. /**
  1926. * 对队列进行排序,能够控制文件上传顺序。
  1927. * @grammar sort( fn ) => undefined
  1928. * @method sort
  1929. * @param {Function} fn 排序方法
  1930. */
  1931. sort: function( fn ) {
  1932. if ( typeof fn === 'function' ) {
  1933. this._queue.sort( fn );
  1934. }
  1935. },
  1936. /**
  1937. * 获取指定类型的文件列表, 列表中每一个成员为[File](#WebUploader:File)对象。
  1938. * @grammar getFiles( [status1[, status2 ...]] ) => Array
  1939. * @method getFiles
  1940. * @param {String} [status] [文件状态值](#WebUploader:File:File.Status)
  1941. */
  1942. getFiles: function() {
  1943. var sts = [].slice.call( arguments, 0 ),
  1944. ret = [],
  1945. i = 0,
  1946. len = this._queue.length,
  1947. file;
  1948. for ( ; i < len; i++ ) {
  1949. file = this._queue[ i ];
  1950. if ( sts.length && !~$.inArray( file.getStatus(), sts ) ) {
  1951. continue;
  1952. }
  1953. ret.push( file );
  1954. }
  1955. return ret;
  1956. },
  1957. _fileAdded: function( file ) {
  1958. var me = this,
  1959. existing = this._map[ file.id ];
  1960. if ( !existing ) {
  1961. this._map[ file.id ] = file;
  1962. file.on( 'statuschange', function( cur, pre ) {
  1963. me._onFileStatusChange( cur, pre );
  1964. });
  1965. }
  1966. file.setStatus( STATUS.QUEUED );
  1967. },
  1968. _onFileStatusChange: function( curStatus, preStatus ) {
  1969. var stats = this.stats;
  1970. switch ( preStatus ) {
  1971. case STATUS.PROGRESS:
  1972. stats.numOfProgress--;
  1973. break;
  1974. case STATUS.QUEUED:
  1975. stats.numOfQueue --;
  1976. break;
  1977. case STATUS.ERROR:
  1978. stats.numOfUploadFailed--;
  1979. break;
  1980. case STATUS.INVALID:
  1981. stats.numOfInvalid--;
  1982. break;
  1983. }
  1984. switch ( curStatus ) {
  1985. case STATUS.QUEUED:
  1986. stats.numOfQueue++;
  1987. break;
  1988. case STATUS.PROGRESS:
  1989. stats.numOfProgress++;
  1990. break;
  1991. case STATUS.ERROR:
  1992. stats.numOfUploadFailed++;
  1993. break;
  1994. case STATUS.COMPLETE:
  1995. stats.numOfSuccess++;
  1996. break;
  1997. case STATUS.CANCELLED:
  1998. stats.numOfCancel++;
  1999. break;
  2000. case STATUS.INVALID:
  2001. stats.numOfInvalid++;
  2002. break;
  2003. }
  2004. }
  2005. });
  2006. Mediator.installTo( Queue.prototype );
  2007. return Queue;
  2008. });
  2009. /**
  2010. * @fileOverview 队列
  2011. */
  2012. define('widgets/queue',[
  2013. 'base',
  2014. 'uploader',
  2015. 'queue',
  2016. 'file',
  2017. 'lib/file',
  2018. 'runtime/client',
  2019. 'widgets/widget'
  2020. ], function( Base, Uploader, Queue, WUFile, File, RuntimeClient ) {
  2021. var $ = Base.$,
  2022. rExt = /\.\w+$/,
  2023. Status = WUFile.Status;
  2024. return Uploader.register({
  2025. 'sort-files': 'sortFiles',
  2026. 'add-file': 'addFiles',
  2027. 'get-file': 'getFile',
  2028. 'fetch-file': 'fetchFile',
  2029. 'get-stats': 'getStats',
  2030. 'get-files': 'getFiles',
  2031. 'remove-file': 'removeFile',
  2032. 'retry': 'retry',
  2033. 'reset': 'reset',
  2034. 'accept-file': 'acceptFile'
  2035. }, {
  2036. init: function( opts ) {
  2037. var me = this,
  2038. deferred, len, i, item, arr, accept, runtime;
  2039. if ( $.isPlainObject( opts.accept ) ) {
  2040. opts.accept = [ opts.accept ];
  2041. }
  2042. // accept中的中生成匹配正则。
  2043. if ( opts.accept ) {
  2044. arr = [];
  2045. for ( i = 0, len = opts.accept.length; i < len; i++ ) {
  2046. item = opts.accept[ i ].extensions;
  2047. item && arr.push( item );
  2048. }
  2049. if ( arr.length ) {
  2050. accept = '\\.' + arr.join(',')
  2051. .replace( /,/g, '$|\\.' )
  2052. .replace( /\*/g, '.*' ) + '$';
  2053. }
  2054. me.accept = new RegExp( accept, 'i' );
  2055. }
  2056. me.queue = new Queue();
  2057. me.stats = me.queue.stats;
  2058. // 如果当前不是html5运行时,那就算了。
  2059. // 不执行后续操作
  2060. if ( this.request('predict-runtime-type') !== 'html5' ) {
  2061. return;
  2062. }
  2063. // 创建一个 html5 运行时的 placeholder
  2064. // 以至于外部添加原生 File 对象的时候能正确包裹一下供 webuploader 使用。
  2065. deferred = Base.Deferred();
  2066. runtime = new RuntimeClient('Placeholder');
  2067. runtime.connectRuntime({
  2068. runtimeOrder: 'html5'
  2069. }, function() {
  2070. me._ruid = runtime.getRuid();
  2071. deferred.resolve();
  2072. });
  2073. return deferred.promise();
  2074. },
  2075. // 为了支持外部直接添加一个原生File对象。
  2076. _wrapFile: function( file ) {
  2077. if ( !(file instanceof WUFile) ) {
  2078. if ( !(file instanceof File) ) {
  2079. if ( !this._ruid ) {
  2080. throw new Error('Can\'t add external files.');
  2081. }
  2082. file = new File( this._ruid, file );
  2083. }
  2084. file = new WUFile( file );
  2085. }
  2086. return file;
  2087. },
  2088. // 判断文件是否可以被加入队列
  2089. acceptFile: function( file ) {
  2090. var invalid = !file || file.size < 6 || this.accept &&
  2091. // 如果名字中有后缀,才做后缀白名单处理。
  2092. rExt.exec( file.name ) && !this.accept.test( file.name );
  2093. return !invalid;
  2094. },
  2095. /**
  2096. * @event beforeFileQueued
  2097. * @param {File} file File对象
  2098. * @description 当文件被加入队列之前触发,此事件的handler返回值为`false`,则此文件不会被添加进入队列。
  2099. * @for Uploader
  2100. */
  2101. /**
  2102. * @event fileQueued
  2103. * @param {File} file File对象
  2104. * @description 当文件被加入队列以后触发。
  2105. * @for Uploader
  2106. */
  2107. _addFile: function( file ) {
  2108. var me = this;
  2109. file = me._wrapFile( file );
  2110. // 不过类型判断允许不允许,先派送 `beforeFileQueued`
  2111. if ( !me.owner.trigger( 'beforeFileQueued', file ) ) {
  2112. return;
  2113. }
  2114. // 类型不匹配,则派送错误事件,并返回。
  2115. if ( !me.acceptFile( file ) ) {
  2116. me.owner.trigger( 'error', 'Q_TYPE_DENIED', file );
  2117. return;
  2118. }
  2119. console.log(11111,file)
  2120. me.queue.append( file );
  2121. me.owner.trigger( 'fileQueued', file );
  2122. return file;
  2123. },
  2124. getFile: function( fileId ) {
  2125. return this.queue.getFile( fileId );
  2126. },
  2127. /**
  2128. * @event filesQueued
  2129. * @param {File} files 数组,内容为原始File(lib/File)对象。
  2130. * @description 当一批文件添加进队列以后触发。
  2131. * @for Uploader
  2132. */
  2133. /**
  2134. * @method addFiles
  2135. * @grammar addFiles( file ) => undefined
  2136. * @grammar addFiles( [file1, file2 ...] ) => undefined
  2137. * @param {Array of File or File} [files] Files 对象 数组
  2138. * @description 添加文件到队列
  2139. * @for Uploader
  2140. */
  2141. addFiles: function( files ) {
  2142. var me = this;
  2143. if ( !files.length ) {
  2144. files = [ files ];
  2145. }
  2146. files = $.map( files, function( file ) {
  2147. return me._addFile( file );
  2148. });
  2149. me.owner.trigger( 'filesQueued', files );
  2150. if ( me.options.auto ) {
  2151. me.request('start-upload');
  2152. }
  2153. },
  2154. getStats: function() {
  2155. return this.stats;
  2156. },
  2157. /**
  2158. * @event fileDequeued
  2159. * @param {File} file File对象
  2160. * @description 当文件被移除队列后触发。
  2161. * @for Uploader
  2162. */
  2163. /**
  2164. * @method removeFile
  2165. * @grammar removeFile( file ) => undefined
  2166. * @grammar removeFile( id ) => undefined
  2167. * @param {File|id} file File对象或这File对象的id
  2168. * @description 移除某一文件。
  2169. * @for Uploader
  2170. * @example
  2171. *
  2172. * $li.on('click', '.remove-this', function() {
  2173. * uploader.removeFile( file );
  2174. * })
  2175. */
  2176. removeFile: function( file ) {
  2177. var me = this;
  2178. file = file.id ? file : me.queue.getFile( file );
  2179. file.setStatus( Status.CANCELLED );
  2180. me.owner.trigger( 'fileDequeued', file );
  2181. },
  2182. /**
  2183. * @method getFiles
  2184. * @grammar getFiles() => Array
  2185. * @grammar getFiles( status1, status2, status... ) => Array
  2186. * @description 返回指定状态的文件集合,不传参数将返回所有状态的文件。
  2187. * @for Uploader
  2188. * @example
  2189. * console.log( uploader.getFiles() ); // => all files
  2190. * console.log( uploader.getFiles('error') ) // => all error files.
  2191. */
  2192. getFiles: function() {
  2193. return this.queue.getFiles.apply( this.queue, arguments );
  2194. },
  2195. fetchFile: function() {
  2196. return this.queue.fetch.apply( this.queue, arguments );
  2197. },
  2198. /**
  2199. * @method retry
  2200. * @grammar retry() => undefined
  2201. * @grammar retry( file ) => undefined
  2202. * @description 重试上传,重试指定文件,或者从出错的文件开始重新上传。
  2203. * @for Uploader
  2204. * @example
  2205. * function retry() {
  2206. * uploader.retry();
  2207. * }
  2208. */
  2209. retry: function( file, noForceStart ) {
  2210. var me = this,
  2211. files, i, len;
  2212. if ( file ) {
  2213. file = file.id ? file : me.queue.getFile( file );
  2214. file.setStatus( Status.QUEUED );
  2215. noForceStart || me.request('start-upload');
  2216. return;
  2217. }
  2218. files = me.queue.getFiles( Status.ERROR );
  2219. i = 0;
  2220. len = files.length;
  2221. for ( ; i < len; i++ ) {
  2222. file = files[ i ];
  2223. file.setStatus( Status.QUEUED );
  2224. }
  2225. me.request('start-upload');
  2226. },
  2227. /**
  2228. * @method sort
  2229. * @grammar sort( fn ) => undefined
  2230. * @description 排序队列中的文件,在上传之前调整可以控制上传顺序。
  2231. * @for Uploader
  2232. */
  2233. sortFiles: function() {
  2234. return this.queue.sort.apply( this.queue, arguments );
  2235. },
  2236. /**
  2237. * @method reset
  2238. * @grammar reset() => undefined
  2239. * @description 重置uploader。目前只重置了队列。
  2240. * @for Uploader
  2241. * @example
  2242. * uploader.reset();
  2243. */
  2244. reset: function() {
  2245. this.queue = new Queue();
  2246. this.stats = this.queue.stats;
  2247. }
  2248. });
  2249. });
  2250. /**
  2251. * @fileOverview 添加获取Runtime相关信息的方法。
  2252. */
  2253. define('widgets/runtime',[
  2254. 'uploader',
  2255. 'runtime/runtime',
  2256. 'widgets/widget'
  2257. ], function( Uploader, Runtime ) {
  2258. Uploader.support = function() {
  2259. return Runtime.hasRuntime.apply( Runtime, arguments );
  2260. };
  2261. return Uploader.register({
  2262. 'predict-runtime-type': 'predictRuntmeType'
  2263. }, {
  2264. init: function() {
  2265. if ( !this.predictRuntmeType() ) {
  2266. throw Error('Runtime Error');
  2267. }
  2268. },
  2269. /**
  2270. * 预测Uploader将采用哪个`Runtime`
  2271. * @grammar predictRuntmeType() => String
  2272. * @method predictRuntmeType
  2273. * @for Uploader
  2274. */
  2275. predictRuntmeType: function() {
  2276. var orders = this.options.runtimeOrder || Runtime.orders,
  2277. type = this.type,
  2278. i, len;
  2279. if ( !type ) {
  2280. orders = orders.split( /\s*,\s*/g );
  2281. for ( i = 0, len = orders.length; i < len; i++ ) {
  2282. if ( Runtime.hasRuntime( orders[ i ] ) ) {
  2283. this.type = type = orders[ i ];
  2284. break;
  2285. }
  2286. }
  2287. }
  2288. return type;
  2289. }
  2290. });
  2291. });
  2292. /**
  2293. * @fileOverview Transport
  2294. */
  2295. define('lib/transport',[
  2296. 'base',
  2297. 'runtime/client',
  2298. 'mediator'
  2299. ], function( Base, RuntimeClient, Mediator ) {
  2300. var $ = Base.$;
  2301. function Transport( opts ) {
  2302. var me = this;
  2303. opts = me.options = $.extend( true, {}, Transport.options, opts || {} );
  2304. RuntimeClient.call( this, 'Transport' );
  2305. this._blob = null;
  2306. this._formData = opts.formData || {};
  2307. this._headers = opts.headers || {};
  2308. this.on( 'progress', this._timeout );
  2309. this.on( 'load error', function() {
  2310. me.trigger( 'progress', 1 );
  2311. clearTimeout( me._timer );
  2312. });
  2313. }
  2314. Transport.options = {
  2315. server: '',
  2316. method: 'POST',
  2317. // 跨域时,是否允许携带cookie, 只有html5 runtime才有效
  2318. withCredentials: false,
  2319. fileVal: 'file',
  2320. timeout: 2 * 60 * 1000, // 2分钟
  2321. formData: {},
  2322. headers: {},
  2323. sendAsBinary: false
  2324. };
  2325. $.extend( Transport.prototype, {
  2326. // 添加Blob, 只能添加一次,最后一次有效。
  2327. appendBlob: function( key, blob, filename ) {
  2328. var me = this,
  2329. opts = me.options;
  2330. if ( me.getRuid() ) {
  2331. me.disconnectRuntime();
  2332. }
  2333. // 连接到blob归属的同一个runtime.
  2334. me.connectRuntime( blob.ruid, function() {
  2335. me.exec('init');
  2336. });
  2337. me._blob = blob;
  2338. opts.fileVal = key || opts.fileVal;
  2339. opts.filename = filename || opts.filename;
  2340. },
  2341. // 添加其他字段
  2342. append: function( key, value ) {
  2343. if ( typeof key === 'object' ) {
  2344. $.extend( this._formData, key );
  2345. } else {
  2346. this._formData[ key ] = value;
  2347. }
  2348. },
  2349. setRequestHeader: function( key, value ) {
  2350. if ( typeof key === 'object' ) {
  2351. $.extend( this._headers, key );
  2352. } else {
  2353. this._headers[ key ] = value;
  2354. }
  2355. },
  2356. send: function( method ) {
  2357. this.exec( 'send', method );
  2358. this._timeout();
  2359. },
  2360. abort: function() {
  2361. clearTimeout( this._timer );
  2362. return this.exec('abort');
  2363. },
  2364. destroy: function() {
  2365. this.trigger('destroy');
  2366. this.off();
  2367. this.exec('destroy');
  2368. this.disconnectRuntime();
  2369. },
  2370. getResponse: function() {
  2371. return this.exec('getResponse');
  2372. },
  2373. getResponseAsJson: function() {
  2374. return this.exec('getResponseAsJson');
  2375. },
  2376. getStatus: function() {
  2377. return this.exec('getStatus');
  2378. },
  2379. _timeout: function() {
  2380. var me = this,
  2381. duration = me.options.timeout;
  2382. if ( !duration ) {
  2383. return;
  2384. }
  2385. clearTimeout( me._timer );
  2386. me._timer = setTimeout(function() {
  2387. me.abort();
  2388. me.trigger( 'error', 'timeout' );
  2389. }, duration );
  2390. }
  2391. });
  2392. // 让Transport具备事件功能。
  2393. Mediator.installTo( Transport.prototype );
  2394. return Transport;
  2395. });
  2396. /**
  2397. * @fileOverview 负责文件上传相关。
  2398. */
  2399. define('widgets/upload',[
  2400. 'base',
  2401. 'uploader',
  2402. 'file',
  2403. 'lib/transport',
  2404. 'widgets/widget'
  2405. ], function( Base, Uploader, WUFile, Transport ) {
  2406. var $ = Base.$,
  2407. isPromise = Base.isPromise,
  2408. Status = WUFile.Status;
  2409. // 添加默认配置项
  2410. $.extend( Uploader.options, {
  2411. /**
  2412. * @property {Boolean} [prepareNextFile=false]
  2413. * @namespace options
  2414. * @for Uploader
  2415. * @description 是否允许在文件传输时提前把下一个文件准备好。
  2416. * 对于一个文件的准备工作比较耗时,比如图片压缩,md5序列化。
  2417. * 如果能提前在当前文件传输期处理,可以节省总体耗时。
  2418. */
  2419. prepareNextFile: false,
  2420. /**
  2421. * @property {Boolean} [chunked=false]
  2422. * @namespace options
  2423. * @for Uploader
  2424. * @description 是否要分片处理大文件上传。
  2425. */
  2426. chunked: false,
  2427. /**
  2428. * @property {Boolean} [chunkSize=5242880]
  2429. * @namespace options
  2430. * @for Uploader
  2431. * @description 如果要分片,分多大一片? 默认大小为5M.
  2432. */
  2433. chunkSize: 5 * 1024 * 1024,
  2434. /**
  2435. * @property {Boolean} [chunkRetry=2]
  2436. * @namespace options
  2437. * @for Uploader
  2438. * @description 如果某个分片由于网络问题出错,允许自动重传多少次?
  2439. */
  2440. chunkRetry: 2,
  2441. /**
  2442. * @property {Boolean} [threads=3]
  2443. * @namespace options
  2444. * @for Uploader
  2445. * @description 上传并发数。允许同时最大上传进程数。
  2446. */
  2447. threads: 3,
  2448. /**
  2449. * @property {Object} [formData]
  2450. * @namespace options
  2451. * @for Uploader
  2452. * @description 文件上传请求的参数表,每次发送都会发送此对象中的参数。
  2453. */
  2454. formData: null
  2455. /**
  2456. * @property {Object} [fileVal='file']
  2457. * @namespace options
  2458. * @for Uploader
  2459. * @description 设置文件上传域的name。
  2460. */
  2461. /**
  2462. * @property {Object} [method='POST']
  2463. * @namespace options
  2464. * @for Uploader
  2465. * @description 文件上传方式,`POST`或者`GET`。
  2466. */
  2467. /**
  2468. * @property {Object} [sendAsBinary=false]
  2469. * @namespace options
  2470. * @for Uploader
  2471. * @description 是否已二进制的流的方式发送文件,这样整个上传内容`php://input`都为文件内容,
  2472. * 其他参数在$_GET数组中。
  2473. */
  2474. });
  2475. // 负责将文件切片。
  2476. function CuteFile( file, chunkSize ) {
  2477. var pending = [],
  2478. blob = file.source,
  2479. total = blob.size,
  2480. chunks = chunkSize ? Math.ceil( total / chunkSize ) : 1,
  2481. start = 0,
  2482. index = 0,
  2483. len;
  2484. while ( index < chunks ) {
  2485. len = Math.min( chunkSize, total - start );
  2486. pending.push({
  2487. file: file,
  2488. start: start,
  2489. end: chunkSize ? (start + len) : total,
  2490. total: total,
  2491. chunks: chunks,
  2492. chunk: index++
  2493. });
  2494. start += len;
  2495. }
  2496. file.blocks = pending.concat();
  2497. file.remaning = pending.length;
  2498. return {
  2499. file: file,
  2500. has: function() {
  2501. return !!pending.length;
  2502. },
  2503. fetch: function() {
  2504. return pending.shift();
  2505. }
  2506. };
  2507. }
  2508. Uploader.register({
  2509. 'start-upload': 'start',
  2510. 'stop-upload': 'stop',
  2511. 'skip-file': 'skipFile',
  2512. 'is-in-progress': 'isInProgress'
  2513. }, {
  2514. init: function() {
  2515. var owner = this.owner;
  2516. this.runing = false;
  2517. // 记录当前正在传的数据,跟threads相关
  2518. this.pool = [];
  2519. // 缓存即将上传的文件。
  2520. this.pending = [];
  2521. // 跟踪还有多少分片没有完成上传。
  2522. this.remaning = 0;
  2523. this.__tick = Base.bindFn( this._tick, this );
  2524. owner.on( 'uploadComplete', function( file ) {
  2525. // 把其他块取消了。
  2526. file.blocks && $.each( file.blocks, function( _, v ) {
  2527. v.transport && (v.transport.abort(), v.transport.destroy());
  2528. delete v.transport;
  2529. });
  2530. delete file.blocks;
  2531. delete file.remaning;
  2532. });
  2533. },
  2534. /**
  2535. * @event startUpload
  2536. * @description 当开始上传流程时触发。
  2537. * @for Uploader
  2538. */
  2539. /**
  2540. * 开始上传。此方法可以从初始状态调用开始上传流程,也可以从暂停状态调用,继续上传流程。
  2541. * @grammar upload() => undefined
  2542. * @method upload
  2543. * @for Uploader
  2544. */
  2545. start: function() {
  2546. var me = this;
  2547. // 移出invalid的文件
  2548. $.each( me.request( 'get-files', Status.INVALID ), function() {
  2549. me.request( 'remove-file', this );
  2550. });
  2551. if ( me.runing ) {
  2552. return;
  2553. }
  2554. me.runing = true;
  2555. // 如果有暂停的,则续传
  2556. $.each( me.pool, function( _, v ) {
  2557. var file = v.file;
  2558. if ( file.getStatus() === Status.INTERRUPT ) {
  2559. file.setStatus( Status.PROGRESS );
  2560. me._trigged = false;
  2561. v.transport && v.transport.send();
  2562. }
  2563. });
  2564. me._trigged = false;
  2565. me.owner.trigger('startUpload');
  2566. Base.nextTick( me.__tick );
  2567. },
  2568. /**
  2569. * @event stopUpload
  2570. * @description 当开始上传流程暂停时触发。
  2571. * @for Uploader
  2572. */
  2573. /**
  2574. * 暂停上传。第一个参数为是否中断上传当前正在上传的文件。
  2575. * @grammar stop() => undefined
  2576. * @grammar stop( true ) => undefined
  2577. * @method stop
  2578. * @for Uploader
  2579. */
  2580. stop: function( interrupt ) {
  2581. var me = this;
  2582. if ( me.runing === false ) {
  2583. return;
  2584. }
  2585. me.runing = false;
  2586. interrupt && $.each( me.pool, function( _, v ) {
  2587. v.transport && v.transport.abort();
  2588. v.file.setStatus( Status.INTERRUPT );
  2589. });
  2590. me.owner.trigger('stopUpload');
  2591. },
  2592. /**
  2593. * 判断`Uplaode`r是否正在上传中。
  2594. * @grammar isInProgress() => Boolean
  2595. * @method isInProgress
  2596. * @for Uploader
  2597. */
  2598. isInProgress: function() {
  2599. return !!this.runing;
  2600. },
  2601. getStats: function() {
  2602. return this.request('get-stats');
  2603. },
  2604. /**
  2605. * 掉过一个文件上传,直接标记指定文件为已上传状态。
  2606. * @grammar skipFile( file ) => undefined
  2607. * @method skipFile
  2608. * @for Uploader
  2609. */
  2610. skipFile: function( file, status ) {
  2611. file = this.request( 'get-file', file );
  2612. file.setStatus( status || Status.COMPLETE );
  2613. file.skipped = true;
  2614. // 如果正在上传。
  2615. file.blocks && $.each( file.blocks, function( _, v ) {
  2616. var _tr = v.transport;
  2617. if ( _tr ) {
  2618. _tr.abort();
  2619. _tr.destroy();
  2620. delete v.transport;
  2621. }
  2622. });
  2623. this.owner.trigger( 'uploadSkip', file );
  2624. },
  2625. /**
  2626. * @event uploadFinished
  2627. * @description 当所有文件上传结束时触发。
  2628. * @for Uploader
  2629. */
  2630. _tick: function() {
  2631. var me = this,
  2632. opts = me.options,
  2633. fn, val;
  2634. // 上一个promise还没有结束,则等待完成后再执行。
  2635. if ( me._promise ) {
  2636. return me._promise.always( me.__tick );
  2637. }
  2638. // 还有位置,且还有文件要处理的话。
  2639. if ( me.pool.length < opts.threads && (val = me._nextBlock()) ) {
  2640. me._trigged = false;
  2641. fn = function( val ) {
  2642. me._promise = null;
  2643. // 有可能是reject过来的,所以要检测val的类型。
  2644. val && val.file && me._startSend( val );
  2645. Base.nextTick( me.__tick );
  2646. };
  2647. me._promise = isPromise( val ) ? val.always( fn ) : fn( val );
  2648. // 没有要上传的了,且没有正在传输的了。
  2649. } else if ( !me.remaning && !me.getStats().numOfQueue ) {
  2650. me.runing = false;
  2651. me._trigged || Base.nextTick(function() {
  2652. me.owner.trigger('uploadFinished');
  2653. });
  2654. me._trigged = true;
  2655. }
  2656. },
  2657. _nextBlock: function() {
  2658. var me = this,
  2659. act = me._act,
  2660. opts = me.options,
  2661. next, done;
  2662. // 如果当前文件还有没有需要传输的,则直接返回剩下的。
  2663. if ( act && act.has() &&
  2664. act.file.getStatus() === Status.PROGRESS ) {
  2665. // 是否提前准备下一个文件
  2666. if ( opts.prepareNextFile && !me.pending.length ) {
  2667. me._prepareNextFile();
  2668. }
  2669. return act.fetch();
  2670. // 否则,如果正在运行,则准备下一个文件,并等待完成后返回下个分片。
  2671. } else if ( me.runing ) {
  2672. // 如果缓存中有,则直接在缓存中取,没有则去queue中取。
  2673. if ( !me.pending.length && me.getStats().numOfQueue ) {
  2674. me._prepareNextFile();
  2675. }
  2676. next = me.pending.shift();
  2677. done = function( file ) {
  2678. if ( !file ) {
  2679. return null;
  2680. }
  2681. act = CuteFile( file, opts.chunked ? opts.chunkSize : 0 );
  2682. me._act = act;
  2683. return act.fetch();
  2684. };
  2685. // 文件可能还在prepare中,也有可能已经完全准备好了。
  2686. return isPromise( next ) ?
  2687. next[ next.pipe ? 'pipe' : 'then']( done ) :
  2688. done( next );
  2689. }
  2690. },
  2691. /**
  2692. * @event uploadStart
  2693. * @param {File} file File对象
  2694. * @description 某个文件开始上传前触发,一个文件只会触发一次。
  2695. * @for Uploader
  2696. */
  2697. _prepareNextFile: function() {
  2698. var me = this,
  2699. file = me.request('fetch-file'),
  2700. pending = me.pending,
  2701. promise;
  2702. if ( file ) {
  2703. promise = me.request( 'before-send-file', file, function() {
  2704. // 有可能文件被skip掉了。文件被skip掉后,状态坑定不是Queued.
  2705. if ( file.getStatus() === Status.QUEUED ) {
  2706. me.owner.trigger( 'uploadStart', file );
  2707. file.setStatus( Status.PROGRESS );
  2708. return file;
  2709. }
  2710. return me._finishFile( file );
  2711. });
  2712. // 如果还在pending中,则替换成文件本身。
  2713. promise.done(function() {
  2714. var idx = $.inArray( promise, pending );
  2715. ~idx && pending.splice( idx, 1, file );
  2716. });
  2717. // befeore-send-file的钩子就有错误发生。
  2718. promise.fail(function( reason ) {
  2719. file.setStatus( Status.ERROR, reason );
  2720. me.owner.trigger( 'uploadError', file, reason );
  2721. me.owner.trigger( 'uploadComplete', file );
  2722. });
  2723. pending.push( promise );
  2724. }
  2725. },
  2726. // 让出位置了,可以让其他分片开始上传
  2727. _popBlock: function( block ) {
  2728. var idx = $.inArray( block, this.pool );
  2729. this.pool.splice( idx, 1 );
  2730. block.file.remaning--;
  2731. this.remaning--;
  2732. },
  2733. // 开始上传,可以被掉过。如果promise被reject了,则表示跳过此分片。
  2734. _startSend: function( block ) {
  2735. var me = this,
  2736. file = block.file,
  2737. promise;
  2738. me.pool.push( block );
  2739. me.remaning++;
  2740. // 如果没有分片,则直接使用原始的。
  2741. // 不会丢失content-type信息。
  2742. block.blob = block.chunks === 1 ? file.source :
  2743. file.source.slice( block.start, block.end );
  2744. // hook, 每个分片发送之前可能要做些异步的事情。
  2745. promise = me.request( 'before-send', block, function() {
  2746. // 有可能文件已经上传出错了,所以不需要再传输了。
  2747. if ( file.getStatus() === Status.PROGRESS ) {
  2748. me._doSend( block );
  2749. } else {
  2750. me._popBlock( block );
  2751. Base.nextTick( me.__tick );
  2752. }
  2753. });
  2754. // 如果为fail了,则跳过此分片。
  2755. promise.fail(function() {
  2756. if ( file.remaning === 1 ) {
  2757. me._finishFile( file ).always(function() {
  2758. block.percentage = 1;
  2759. me._popBlock( block );
  2760. me.owner.trigger( 'uploadComplete', file );
  2761. Base.nextTick( me.__tick );
  2762. });
  2763. } else {
  2764. block.percentage = 1;
  2765. me._popBlock( block );
  2766. Base.nextTick( me.__tick );
  2767. }
  2768. });
  2769. },
  2770. /**
  2771. * @event uploadBeforeSend
  2772. * @param {Object} object
  2773. * @param {Object} data 默认的上传参数,可以扩展此对象来控制上传参数。
  2774. * @description 当某个文件的分块在发送前触发,主要用来询问是否要添加附带参数,大文件在开起分片上传的前提下此事件可能会触发多次。
  2775. * @for Uploader
  2776. */
  2777. /**
  2778. * @event uploadAccept
  2779. * @param {Object} object
  2780. * @param {Object} ret 服务端的返回数据,json格式,如果服务端不是json格式,从ret._raw中取数据,自行解析。
  2781. * @description 当某个文件上传到服务端响应后,会派送此事件来询问服务端响应是否有效。如果此事件handler返回值为`false`, 则此文件将派送`server`类型的`uploadError`事件。
  2782. * @for Uploader
  2783. */
  2784. /**
  2785. * @event uploadProgress
  2786. * @param {File} file File对象
  2787. * @param {Number} percentage 上传进度
  2788. * @description 上传过程中触发,携带上传进度。
  2789. * @for Uploader
  2790. */
  2791. /**
  2792. * @event uploadError
  2793. * @param {File} file File对象
  2794. * @param {String} reason 出错的code
  2795. * @description 当文件上传出错时触发。
  2796. * @for Uploader
  2797. */
  2798. /**
  2799. * @event uploadSuccess
  2800. * @param {File} file File对象
  2801. * @param {Object} response 服务端返回的数据
  2802. * @description 当文件上传成功时触发。
  2803. * @for Uploader
  2804. */
  2805. /**
  2806. * @event uploadComplete
  2807. * @param {File} [file] File对象
  2808. * @description 不管成功或者失败,文件上传完成时触发。
  2809. * @for Uploader
  2810. */
  2811. // 做上传操作。
  2812. _doSend: function( block ) {
  2813. var me = this,
  2814. owner = me.owner,
  2815. opts = me.options,
  2816. file = block.file,
  2817. tr = new Transport( opts ),
  2818. data = $.extend({}, opts.formData ),
  2819. headers = $.extend({}, opts.headers ),
  2820. requestAccept, ret;
  2821. block.transport = tr;
  2822. tr.on( 'destroy', function() {
  2823. delete block.transport;
  2824. me._popBlock( block );
  2825. Base.nextTick( me.__tick );
  2826. });
  2827. // 广播上传进度。以文件为单位。
  2828. tr.on( 'progress', function( percentage ) {
  2829. var totalPercent = 0,
  2830. uploaded = 0;
  2831. // 可能没有abort掉,progress还是执行进来了。
  2832. // if ( !file.blocks ) {
  2833. // return;
  2834. // }
  2835. totalPercent = block.percentage = percentage;
  2836. if ( block.chunks > 1 ) { // 计算文件的整体速度。
  2837. $.each( file.blocks, function( _, v ) {
  2838. uploaded += (v.percentage || 0) * (v.end - v.start);
  2839. });
  2840. totalPercent = uploaded / file.size;
  2841. }
  2842. owner.trigger( 'uploadProgress', file, totalPercent || 0 );
  2843. });
  2844. // 用来询问,是否返回的结果是有错误的。
  2845. requestAccept = function( reject ) {
  2846. var fn;
  2847. ret = tr.getResponseAsJson() || {};
  2848. ret._raw = tr.getResponse();
  2849. fn = function( value ) {
  2850. reject = value;
  2851. };
  2852. // 服务端响应了,不代表成功了,询问是否响应正确。
  2853. if ( !owner.trigger( 'uploadAccept', block, ret, fn ) ) {
  2854. reject = reject || 'server';
  2855. }
  2856. return reject;
  2857. };
  2858. // 尝试重试,然后广播文件上传出错。
  2859. tr.on( 'error', function( type, flag ) {
  2860. block.retried = block.retried || 0;
  2861. // 自动重试
  2862. if ( block.chunks > 1 && ~'http,abort'.indexOf( type ) &&
  2863. block.retried < opts.chunkRetry ) {
  2864. block.retried++;
  2865. tr.send();
  2866. } else {
  2867. // http status 500 ~ 600
  2868. if ( !flag && type === 'server' ) {
  2869. type = requestAccept( type );
  2870. }
  2871. file.setStatus( Status.ERROR, type );
  2872. owner.trigger( 'uploadError', file, type );
  2873. owner.trigger( 'uploadComplete', file );
  2874. }
  2875. });
  2876. // 上传成功
  2877. tr.on( 'load', function() {
  2878. var reason;
  2879. // 如果非预期,转向上传出错。
  2880. if ( (reason = requestAccept()) ) {
  2881. tr.trigger( 'error', reason, true );
  2882. return;
  2883. }
  2884. // 全部上传完成。
  2885. if ( file.remaning === 1 ) {
  2886. me._finishFile( file, ret );
  2887. } else {
  2888. tr.destroy();
  2889. }
  2890. });
  2891. // 配置默认的上传字段。
  2892. data = $.extend( data, {
  2893. id: file.id,
  2894. name: file.name,
  2895. type: file.type,
  2896. lastModifiedDate: file.lastModifiedDate,
  2897. size: file.size
  2898. });
  2899. block.chunks > 1 && $.extend( data, {
  2900. chunks: block.chunks,
  2901. chunk: block.chunk
  2902. });
  2903. // 在发送之间可以添加字段什么的。。。
  2904. // 如果默认的字段不够使用,可以通过监听此事件来扩展
  2905. owner.trigger( 'uploadBeforeSend', block, data, headers );
  2906. // 开始发送。
  2907. tr.appendBlob( opts.fileVal, block.blob, file.name );
  2908. tr.append( data );
  2909. tr.setRequestHeader( headers );
  2910. tr.send();
  2911. },
  2912. // 完成上传。
  2913. _finishFile: function( file, ret, hds ) {
  2914. var owner = this.owner;
  2915. return owner
  2916. .request( 'after-send-file', arguments, function() {
  2917. file.setStatus( Status.COMPLETE );
  2918. owner.trigger( 'uploadSuccess', file, ret, hds );
  2919. })
  2920. .fail(function( reason ) {
  2921. // 如果外部已经标记为invalid什么的,不再改状态。
  2922. if ( file.getStatus() === Status.PROGRESS ) {
  2923. file.setStatus( Status.ERROR, reason );
  2924. }
  2925. owner.trigger( 'uploadError', file, reason );
  2926. })
  2927. .always(function() {
  2928. owner.trigger( 'uploadComplete', file );
  2929. });
  2930. }
  2931. });
  2932. });
  2933. /**
  2934. * @fileOverview Runtime管理器,负责Runtime的选择, 连接
  2935. */
  2936. define('runtime/compbase',[],function() {
  2937. function CompBase( owner, runtime ) {
  2938. this.owner = owner;
  2939. this.options = owner.options;
  2940. this.getRuntime = function() {
  2941. return runtime;
  2942. };
  2943. this.getRuid = function() {
  2944. return runtime.uid;
  2945. };
  2946. this.trigger = function() {
  2947. return owner.trigger.apply( owner, arguments );
  2948. };
  2949. }
  2950. return CompBase;
  2951. });
  2952. /**
  2953. * @fileOverview Html5Runtime
  2954. */
  2955. define('runtime/html5/runtime',[
  2956. 'base',
  2957. 'runtime/runtime',
  2958. 'runtime/compbase'
  2959. ], function( Base, Runtime, CompBase ) {
  2960. var type = 'html5',
  2961. components = {};
  2962. function Html5Runtime() {
  2963. var pool = {},
  2964. me = this,
  2965. destory = this.destory;
  2966. Runtime.apply( me, arguments );
  2967. me.type = type;
  2968. // 这个方法的调用者,实际上是RuntimeClient
  2969. me.exec = function( comp, fn/*, args...*/) {
  2970. var client = this,
  2971. uid = client.uid,
  2972. args = Base.slice( arguments, 2 ),
  2973. instance;
  2974. if ( components[ comp ] ) {
  2975. instance = pool[ uid ] = pool[ uid ] ||
  2976. new components[ comp ]( client, me );
  2977. if ( instance[ fn ] ) {
  2978. return instance[ fn ].apply( instance, args );
  2979. }
  2980. }
  2981. };
  2982. me.destory = function() {
  2983. // @todo 删除池子中的所有实例
  2984. return destory && destory.apply( this, arguments );
  2985. };
  2986. }
  2987. Base.inherits( Runtime, {
  2988. constructor: Html5Runtime,
  2989. // 不需要连接其他程序,直接执行callback
  2990. init: function() {
  2991. var me = this;
  2992. setTimeout(function() {
  2993. me.trigger('ready');
  2994. }, 1 );
  2995. }
  2996. });
  2997. // 注册Components
  2998. Html5Runtime.register = function( name, component ) {
  2999. var klass = components[ name ] = Base.inherits( CompBase, component );
  3000. return klass;
  3001. };
  3002. // 注册html5运行时。
  3003. // 只有在支持的前提下注册。
  3004. if ( window.Blob && window.FileReader && window.DataView ) {
  3005. Runtime.addRuntime( type, Html5Runtime );
  3006. }
  3007. return Html5Runtime;
  3008. });
  3009. /**
  3010. * @fileOverview Blob Html实现
  3011. */
  3012. define('runtime/html5/blob',[
  3013. 'runtime/html5/runtime',
  3014. 'lib/blob'
  3015. ], function( Html5Runtime, Blob ) {
  3016. return Html5Runtime.register( 'Blob', {
  3017. slice: function( start, end ) {
  3018. var blob = this.owner.source,
  3019. slice = blob.slice || blob.webkitSlice || blob.mozSlice;
  3020. blob = slice.call( blob, start, end );
  3021. return new Blob( this.getRuid(), blob );
  3022. }
  3023. });
  3024. });
  3025. /**
  3026. * @fileOverview FilePicker
  3027. */
  3028. define('runtime/html5/filepicker',[
  3029. 'base',
  3030. 'runtime/html5/runtime'
  3031. ], function( Base, Html5Runtime ) {
  3032. var $ = Base.$;
  3033. return Html5Runtime.register( 'FilePicker', {
  3034. init: function() {
  3035. var container = this.getRuntime().getContainer(),
  3036. me = this,
  3037. owner = me.owner,
  3038. opts = me.options,
  3039. lable = $( document.createElement('label') ),
  3040. input = $( document.createElement('input') ),
  3041. arr, i, len, mouseHandler;
  3042. input.attr( 'type', 'file' );
  3043. input.attr( 'name', opts.name );
  3044. input.addClass('webuploader-element-invisible');
  3045. lable.on( 'click', function() {
  3046. input.trigger('click');
  3047. });
  3048. lable.css({
  3049. opacity: 0,
  3050. width: '100%',
  3051. height: '100%',
  3052. display: 'block',
  3053. cursor: 'pointer',
  3054. background: '#ffffff'
  3055. });
  3056. if ( opts.multiple ) {
  3057. input.attr( 'multiple', 'multiple' );
  3058. }
  3059. // @todo Firefox不支持单独指定后缀
  3060. if ( opts.accept && opts.accept.length > 0 ) {
  3061. arr = [];
  3062. for ( i = 0, len = opts.accept.length; i < len; i++ ) {
  3063. arr.push( opts.accept[ i ].mimeTypes );
  3064. }
  3065. input.attr( 'accept', arr.join(',') );
  3066. }
  3067. container.append( input );
  3068. container.append( lable );
  3069. mouseHandler = function( e ) {
  3070. owner.trigger( e.type );
  3071. };
  3072. input.on( 'change', function( e ) {
  3073. var fn = arguments.callee,
  3074. clone;
  3075. me.files = e.target.files;
  3076. // reset input
  3077. clone = this.cloneNode( true );
  3078. this.parentNode.replaceChild( clone, this );
  3079. input.off();
  3080. input = $( clone ).on( 'change', fn )
  3081. .on( 'mouseenter mouseleave', mouseHandler );
  3082. owner.trigger('change');
  3083. });
  3084. lable.on( 'mouseenter mouseleave', mouseHandler );
  3085. },
  3086. getFiles: function() {
  3087. return this.files;
  3088. },
  3089. destroy: function() {
  3090. // todo
  3091. }
  3092. });
  3093. });
  3094. /**
  3095. * Terms:
  3096. *
  3097. * Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
  3098. * @fileOverview Image控件
  3099. */
  3100. define('runtime/html5/util',[
  3101. 'base'
  3102. ], function( Base ) {
  3103. var urlAPI = window.createObjectURL && window ||
  3104. window.URL && URL.revokeObjectURL && URL ||
  3105. window.webkitURL,
  3106. createObjectURL = Base.noop,
  3107. revokeObjectURL = createObjectURL;
  3108. if ( urlAPI ) {
  3109. // 更安全的方式调用,比如android里面就能把context改成其他的对象。
  3110. createObjectURL = function() {
  3111. return urlAPI.createObjectURL.apply( urlAPI, arguments );
  3112. };
  3113. revokeObjectURL = function() {
  3114. return urlAPI.revokeObjectURL.apply( urlAPI, arguments );
  3115. };
  3116. }
  3117. return {
  3118. createObjectURL: createObjectURL,
  3119. revokeObjectURL: revokeObjectURL,
  3120. dataURL2Blob: function( dataURI ) {
  3121. var byteStr, intArray, ab, i, mimetype, parts;
  3122. parts = dataURI.split(',');
  3123. if ( ~parts[ 0 ].indexOf('base64') ) {
  3124. byteStr = atob( parts[ 1 ] );
  3125. } else {
  3126. byteStr = decodeURIComponent( parts[ 1 ] );
  3127. }
  3128. ab = new ArrayBuffer( byteStr.length );
  3129. intArray = new Uint8Array( ab );
  3130. for ( i = 0; i < byteStr.length; i++ ) {
  3131. intArray[ i ] = byteStr.charCodeAt( i );
  3132. }
  3133. mimetype = parts[ 0 ].split(':')[ 1 ].split(';')[ 0 ];
  3134. return this.arrayBufferToBlob( ab, mimetype );
  3135. },
  3136. dataURL2ArrayBuffer: function( dataURI ) {
  3137. var byteStr, intArray, i, parts;
  3138. parts = dataURI.split(',');
  3139. if ( ~parts[ 0 ].indexOf('base64') ) {
  3140. byteStr = atob( parts[ 1 ] );
  3141. } else {
  3142. byteStr = decodeURIComponent( parts[ 1 ] );
  3143. }
  3144. intArray = new Uint8Array( byteStr.length );
  3145. for ( i = 0; i < byteStr.length; i++ ) {
  3146. intArray[ i ] = byteStr.charCodeAt( i );
  3147. }
  3148. return intArray.buffer;
  3149. },
  3150. arrayBufferToBlob: function( buffer, type ) {
  3151. var builder = window.BlobBuilder || window.WebKitBlobBuilder,
  3152. bb;
  3153. // android不支持直接new Blob, 只能借助blobbuilder.
  3154. if ( builder ) {
  3155. bb = new builder();
  3156. bb.append( buffer );
  3157. return bb.getBlob( type );
  3158. }
  3159. return new Blob([ buffer ], type ? { type: type } : {} );
  3160. },
  3161. // 抽出来主要是为了解决android下面canvas.toDataUrl不支持jpeg.
  3162. // 你得到的结果是png.
  3163. canvasToDataUrl: function( canvas, type, quality ) {
  3164. return canvas.toDataURL( type, quality / 100 );
  3165. },
  3166. // imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
  3167. parseMeta: function( blob, callback ) {
  3168. callback( false, {});
  3169. },
  3170. // imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
  3171. updateImageHead: function( data ) {
  3172. return data;
  3173. }
  3174. };
  3175. });
  3176. /**
  3177. * Terms:
  3178. *
  3179. * Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
  3180. * @fileOverview Image控件
  3181. */
  3182. define('runtime/html5/imagemeta',[
  3183. 'runtime/html5/util'
  3184. ], function( Util ) {
  3185. var api;
  3186. api = {
  3187. parsers: {
  3188. 0xffe1: []
  3189. },
  3190. maxMetaDataSize: 262144,
  3191. parse: function( blob, cb ) {
  3192. var me = this,
  3193. fr = new FileReader();
  3194. fr.onload = function() {
  3195. cb( false, me._parse( this.result ) );
  3196. fr = fr.onload = fr.onerror = null;
  3197. };
  3198. fr.onerror = function( e ) {
  3199. cb( e.message );
  3200. fr = fr.onload = fr.onerror = null;
  3201. };
  3202. blob = blob.slice( 0, me.maxMetaDataSize );
  3203. fr.readAsArrayBuffer( blob.getSource() );
  3204. },
  3205. _parse: function( buffer, noParse ) {
  3206. if ( buffer.byteLength < 6 ) {
  3207. return;
  3208. }
  3209. var dataview = new DataView( buffer ),
  3210. offset = 2,
  3211. maxOffset = dataview.byteLength - 4,
  3212. headLength = offset,
  3213. ret = {},
  3214. markerBytes, markerLength, parsers, i;
  3215. if ( dataview.getUint16( 0 ) === 0xffd8 ) {
  3216. while ( offset < maxOffset ) {
  3217. markerBytes = dataview.getUint16( offset );
  3218. if ( markerBytes >= 0xffe0 && markerBytes <= 0xffef ||
  3219. markerBytes === 0xfffe ) {
  3220. markerLength = dataview.getUint16( offset + 2 ) + 2;
  3221. if ( offset + markerLength > dataview.byteLength ) {
  3222. break;
  3223. }
  3224. parsers = api.parsers[ markerBytes ];
  3225. if ( !noParse && parsers ) {
  3226. for ( i = 0; i < parsers.length; i += 1 ) {
  3227. parsers[ i ].call( api, dataview, offset,
  3228. markerLength, ret );
  3229. }
  3230. }
  3231. offset += markerLength;
  3232. headLength = offset;
  3233. } else {
  3234. break;
  3235. }
  3236. }
  3237. if ( headLength > 6 ) {
  3238. if ( buffer.slice ) {
  3239. ret.imageHead = buffer.slice( 2, headLength );
  3240. } else {
  3241. // Workaround for IE10, which does not yet
  3242. // support ArrayBuffer.slice:
  3243. ret.imageHead = new Uint8Array( buffer )
  3244. .subarray( 2, headLength );
  3245. }
  3246. }
  3247. }
  3248. return ret;
  3249. },
  3250. updateImageHead: function( buffer, head ) {
  3251. var data = this._parse( buffer, true ),
  3252. buf1, buf2, bodyoffset;
  3253. bodyoffset = 2;
  3254. if ( data.imageHead ) {
  3255. bodyoffset = 2 + data.imageHead.byteLength;
  3256. }
  3257. if ( buffer.slice ) {
  3258. buf2 = buffer.slice( bodyoffset );
  3259. } else {
  3260. buf2 = new Uint8Array( buffer ).subarray( bodyoffset );
  3261. }
  3262. buf1 = new Uint8Array( head.byteLength + 2 + buf2.byteLength );
  3263. buf1[ 0 ] = 0xFF;
  3264. buf1[ 1 ] = 0xD8;
  3265. buf1.set( new Uint8Array( head ), 2 );
  3266. buf1.set( new Uint8Array( buf2 ), head.byteLength + 2 );
  3267. return buf1.buffer;
  3268. }
  3269. };
  3270. Util.parseMeta = function() {
  3271. return api.parse.apply( api, arguments );
  3272. };
  3273. Util.updateImageHead = function() {
  3274. return api.updateImageHead.apply( api, arguments );
  3275. };
  3276. return api;
  3277. });
  3278. /**
  3279. * 代码来自于:https://github.com/blueimp/JavaScript-Load-Image
  3280. * 暂时项目中只用了orientation.
  3281. *
  3282. * 去除了 Exif Sub IFD Pointer, GPS Info IFD Pointer, Exif Thumbnail.
  3283. * @fileOverview EXIF解析
  3284. */
  3285. // Sample
  3286. // ====================================
  3287. // Make : Apple
  3288. // Model : iPhone 4S
  3289. // Orientation : 1
  3290. // XResolution : 72 [72/1]
  3291. // YResolution : 72 [72/1]
  3292. // ResolutionUnit : 2
  3293. // Software : QuickTime 7.7.1
  3294. // DateTime : 2013:09:01 22:53:55
  3295. // ExifIFDPointer : 190
  3296. // ExposureTime : 0.058823529411764705 [1/17]
  3297. // FNumber : 2.4 [12/5]
  3298. // ExposureProgram : Normal program
  3299. // ISOSpeedRatings : 800
  3300. // ExifVersion : 0220
  3301. // DateTimeOriginal : 2013:09:01 22:52:51
  3302. // DateTimeDigitized : 2013:09:01 22:52:51
  3303. // ComponentsConfiguration : YCbCr
  3304. // ShutterSpeedValue : 4.058893515764426
  3305. // ApertureValue : 2.5260688216892597 [4845/1918]
  3306. // BrightnessValue : -0.3126686601998395
  3307. // MeteringMode : Pattern
  3308. // Flash : Flash did not fire, compulsory flash mode
  3309. // FocalLength : 4.28 [107/25]
  3310. // SubjectArea : [4 values]
  3311. // FlashpixVersion : 0100
  3312. // ColorSpace : 1
  3313. // PixelXDimension : 2448
  3314. // PixelYDimension : 3264
  3315. // SensingMethod : One-chip color area sensor
  3316. // ExposureMode : 0
  3317. // WhiteBalance : Auto white balance
  3318. // FocalLengthIn35mmFilm : 35
  3319. // SceneCaptureType : Standard
  3320. define('runtime/html5/imagemeta/exif',[
  3321. 'base',
  3322. 'runtime/html5/imagemeta'
  3323. ], function( Base, ImageMeta ) {
  3324. var EXIF = {};
  3325. EXIF.ExifMap = function() {
  3326. return this;
  3327. };
  3328. EXIF.ExifMap.prototype.map = {
  3329. 'Orientation': 0x0112
  3330. };
  3331. EXIF.ExifMap.prototype.get = function( id ) {
  3332. return this[ id ] || this[ this.map[ id ] ];
  3333. };
  3334. EXIF.exifTagTypes = {
  3335. // byte, 8-bit unsigned int:
  3336. 1: {
  3337. getValue: function( dataView, dataOffset ) {
  3338. return dataView.getUint8( dataOffset );
  3339. },
  3340. size: 1
  3341. },
  3342. // ascii, 8-bit byte:
  3343. 2: {
  3344. getValue: function( dataView, dataOffset ) {
  3345. return String.fromCharCode( dataView.getUint8( dataOffset ) );
  3346. },
  3347. size: 1,
  3348. ascii: true
  3349. },
  3350. // short, 16 bit int:
  3351. 3: {
  3352. getValue: function( dataView, dataOffset, littleEndian ) {
  3353. return dataView.getUint16( dataOffset, littleEndian );
  3354. },
  3355. size: 2
  3356. },
  3357. // long, 32 bit int:
  3358. 4: {
  3359. getValue: function( dataView, dataOffset, littleEndian ) {
  3360. return dataView.getUint32( dataOffset, littleEndian );
  3361. },
  3362. size: 4
  3363. },
  3364. // rational = two long values,
  3365. // first is numerator, second is denominator:
  3366. 5: {
  3367. getValue: function( dataView, dataOffset, littleEndian ) {
  3368. return dataView.getUint32( dataOffset, littleEndian ) /
  3369. dataView.getUint32( dataOffset + 4, littleEndian );
  3370. },
  3371. size: 8
  3372. },
  3373. // slong, 32 bit signed int:
  3374. 9: {
  3375. getValue: function( dataView, dataOffset, littleEndian ) {
  3376. return dataView.getInt32( dataOffset, littleEndian );
  3377. },
  3378. size: 4
  3379. },
  3380. // srational, two slongs, first is numerator, second is denominator:
  3381. 10: {
  3382. getValue: function( dataView, dataOffset, littleEndian ) {
  3383. return dataView.getInt32( dataOffset, littleEndian ) /
  3384. dataView.getInt32( dataOffset + 4, littleEndian );
  3385. },
  3386. size: 8
  3387. }
  3388. };
  3389. // undefined, 8-bit byte, value depending on field:
  3390. EXIF.exifTagTypes[ 7 ] = EXIF.exifTagTypes[ 1 ];
  3391. EXIF.getExifValue = function( dataView, tiffOffset, offset, type, length,
  3392. littleEndian ) {
  3393. var tagType = EXIF.exifTagTypes[ type ],
  3394. tagSize, dataOffset, values, i, str, c;
  3395. if ( !tagType ) {
  3396. Base.log('Invalid Exif data: Invalid tag type.');
  3397. return;
  3398. }
  3399. tagSize = tagType.size * length;
  3400. // Determine if the value is contained in the dataOffset bytes,
  3401. // or if the value at the dataOffset is a pointer to the actual data:
  3402. dataOffset = tagSize > 4 ? tiffOffset + dataView.getUint32( offset + 8,
  3403. littleEndian ) : (offset + 8);
  3404. if ( dataOffset + tagSize > dataView.byteLength ) {
  3405. Base.log('Invalid Exif data: Invalid data offset.');
  3406. return;
  3407. }
  3408. if ( length === 1 ) {
  3409. return tagType.getValue( dataView, dataOffset, littleEndian );
  3410. }
  3411. values = [];
  3412. for ( i = 0; i < length; i += 1 ) {
  3413. values[ i ] = tagType.getValue( dataView,
  3414. dataOffset + i * tagType.size, littleEndian );
  3415. }
  3416. if ( tagType.ascii ) {
  3417. str = '';
  3418. // Concatenate the chars:
  3419. for ( i = 0; i < values.length; i += 1 ) {
  3420. c = values[ i ];
  3421. // Ignore the terminating NULL byte(s):
  3422. if ( c === '\u0000' ) {
  3423. break;
  3424. }
  3425. str += c;
  3426. }
  3427. return str;
  3428. }
  3429. return values;
  3430. };
  3431. EXIF.parseExifTag = function( dataView, tiffOffset, offset, littleEndian,
  3432. data ) {
  3433. var tag = dataView.getUint16( offset, littleEndian );
  3434. data.exif[ tag ] = EXIF.getExifValue( dataView, tiffOffset, offset,
  3435. dataView.getUint16( offset + 2, littleEndian ), // tag type
  3436. dataView.getUint32( offset + 4, littleEndian ), // tag length
  3437. littleEndian );
  3438. };
  3439. EXIF.parseExifTags = function( dataView, tiffOffset, dirOffset,
  3440. littleEndian, data ) {
  3441. var tagsNumber, dirEndOffset, i;
  3442. if ( dirOffset + 6 > dataView.byteLength ) {
  3443. Base.log('Invalid Exif data: Invalid directory offset.');
  3444. return;
  3445. }
  3446. tagsNumber = dataView.getUint16( dirOffset, littleEndian );
  3447. dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
  3448. if ( dirEndOffset + 4 > dataView.byteLength ) {
  3449. Base.log('Invalid Exif data: Invalid directory size.');
  3450. return;
  3451. }
  3452. for ( i = 0; i < tagsNumber; i += 1 ) {
  3453. this.parseExifTag( dataView, tiffOffset,
  3454. dirOffset + 2 + 12 * i, // tag offset
  3455. littleEndian, data );
  3456. }
  3457. // Return the offset to the next directory:
  3458. return dataView.getUint32( dirEndOffset, littleEndian );
  3459. };
  3460. // EXIF.getExifThumbnail = function(dataView, offset, length) {
  3461. // var hexData,
  3462. // i,
  3463. // b;
  3464. // if (!length || offset + length > dataView.byteLength) {
  3465. // Base.log('Invalid Exif data: Invalid thumbnail data.');
  3466. // return;
  3467. // }
  3468. // hexData = [];
  3469. // for (i = 0; i < length; i += 1) {
  3470. // b = dataView.getUint8(offset + i);
  3471. // hexData.push((b < 16 ? '0' : '') + b.toString(16));
  3472. // }
  3473. // return 'data:image/jpeg,%' + hexData.join('%');
  3474. // };
  3475. EXIF.parseExifData = function( dataView, offset, length, data ) {
  3476. var tiffOffset = offset + 10,
  3477. littleEndian, dirOffset;
  3478. // Check for the ASCII code for "Exif" (0x45786966):
  3479. if ( dataView.getUint32( offset + 4 ) !== 0x45786966 ) {
  3480. // No Exif data, might be XMP data instead
  3481. return;
  3482. }
  3483. if ( tiffOffset + 8 > dataView.byteLength ) {
  3484. Base.log('Invalid Exif data: Invalid segment size.');
  3485. return;
  3486. }
  3487. // Check for the two null bytes:
  3488. if ( dataView.getUint16( offset + 8 ) !== 0x0000 ) {
  3489. Base.log('Invalid Exif data: Missing byte alignment offset.');
  3490. return;
  3491. }
  3492. // Check the byte alignment:
  3493. switch ( dataView.getUint16( tiffOffset ) ) {
  3494. case 0x4949:
  3495. littleEndian = true;
  3496. break;
  3497. case 0x4D4D:
  3498. littleEndian = false;
  3499. break;
  3500. default:
  3501. Base.log('Invalid Exif data: Invalid byte alignment marker.');
  3502. return;
  3503. }
  3504. // Check for the TIFF tag marker (0x002A):
  3505. if ( dataView.getUint16( tiffOffset + 2, littleEndian ) !== 0x002A ) {
  3506. Base.log('Invalid Exif data: Missing TIFF marker.');
  3507. return;
  3508. }
  3509. // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
  3510. dirOffset = dataView.getUint32( tiffOffset + 4, littleEndian );
  3511. // Create the exif object to store the tags:
  3512. data.exif = new EXIF.ExifMap();
  3513. // Parse the tags of the main image directory and retrieve the
  3514. // offset to the next directory, usually the thumbnail directory:
  3515. dirOffset = EXIF.parseExifTags( dataView, tiffOffset,
  3516. tiffOffset + dirOffset, littleEndian, data );
  3517. // 尝试读取缩略图
  3518. // if ( dirOffset ) {
  3519. // thumbnailData = {exif: {}};
  3520. // dirOffset = EXIF.parseExifTags(
  3521. // dataView,
  3522. // tiffOffset,
  3523. // tiffOffset + dirOffset,
  3524. // littleEndian,
  3525. // thumbnailData
  3526. // );
  3527. // // Check for JPEG Thumbnail offset:
  3528. // if (thumbnailData.exif[0x0201]) {
  3529. // data.exif.Thumbnail = EXIF.getExifThumbnail(
  3530. // dataView,
  3531. // tiffOffset + thumbnailData.exif[0x0201],
  3532. // thumbnailData.exif[0x0202] // Thumbnail data length
  3533. // );
  3534. // }
  3535. // }
  3536. };
  3537. ImageMeta.parsers[ 0xffe1 ].push( EXIF.parseExifData );
  3538. return EXIF;
  3539. });
  3540. /**
  3541. * @fileOverview Image
  3542. */
  3543. define('runtime/html5/image',[
  3544. 'base',
  3545. 'runtime/html5/runtime',
  3546. 'runtime/html5/util'
  3547. ], function( Base, Html5Runtime, Util ) {
  3548. var BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D';
  3549. return Html5Runtime.register( 'Image', {
  3550. // flag: 标记是否被修改过。
  3551. modified: false,
  3552. init: function() {
  3553. var me = this,
  3554. img = new Image();
  3555. img.onload = function() {
  3556. me._info = {
  3557. type: me.type,
  3558. width: this.width,
  3559. height: this.height
  3560. };
  3561. // 读取meta信息。
  3562. if ( !me._metas && 'image/jpeg' === me.type ) {
  3563. Util.parseMeta( me._blob, function( error, ret ) {
  3564. me._metas = ret;
  3565. me.owner.trigger('load');
  3566. });
  3567. } else {
  3568. me.owner.trigger('load');
  3569. }
  3570. };
  3571. img.onerror = function() {
  3572. me.owner.trigger('error');
  3573. };
  3574. me._img = img;
  3575. },
  3576. loadFromBlob: function( blob ) {
  3577. var me = this,
  3578. img = me._img;
  3579. me._blob = blob;
  3580. me.type = blob.type;
  3581. img.src = Util.createObjectURL( blob.getSource() );
  3582. me.owner.once( 'load', function() {
  3583. Util.revokeObjectURL( img.src );
  3584. });
  3585. },
  3586. resize: function( width, height ) {
  3587. var canvas = this._canvas ||
  3588. (this._canvas = document.createElement('canvas'));
  3589. this._resize( this._img, canvas, width, height );
  3590. this._blob = null; // 没用了,可以删掉了。
  3591. this.modified = true;
  3592. this.owner.trigger('complete');
  3593. },
  3594. getAsBlob: function( type ) {
  3595. var blob = this._blob,
  3596. opts = this.options,
  3597. canvas;
  3598. type = type || this.type;
  3599. // blob需要重新生成。
  3600. if ( this.modified || this.type !== type ) {
  3601. canvas = this._canvas;
  3602. if ( type === 'image/jpeg' ) {
  3603. blob = Util.canvasToDataUrl( canvas, 'image/jpeg',
  3604. opts.quality );
  3605. if ( opts.preserveHeaders && this._metas &&
  3606. this._metas.imageHead ) {
  3607. blob = Util.dataURL2ArrayBuffer( blob );
  3608. blob = Util.updateImageHead( blob,
  3609. this._metas.imageHead );
  3610. blob = Util.arrayBufferToBlob( blob, type );
  3611. return blob;
  3612. }
  3613. } else {
  3614. blob = Util.canvasToDataUrl( canvas, type );
  3615. }
  3616. blob = Util.dataURL2Blob( blob );
  3617. }
  3618. return blob;
  3619. },
  3620. getAsDataUrl: function( type ) {
  3621. var opts = this.options;
  3622. type = type || this.type;
  3623. if ( type === 'image/jpeg' ) {
  3624. return Util.canvasToDataUrl( this._canvas, type, opts.quality );
  3625. } else {
  3626. return this._canvas.toDataURL( type );
  3627. }
  3628. },
  3629. getOrientation: function() {
  3630. return this._metas && this._metas.exif &&
  3631. this._metas.exif.get('Orientation') || 1;
  3632. },
  3633. info: function( val ) {
  3634. // setter
  3635. if ( val ) {
  3636. this._info = val;
  3637. return this;
  3638. }
  3639. // getter
  3640. return this._info;
  3641. },
  3642. meta: function( val ) {
  3643. // setter
  3644. if ( val ) {
  3645. this._meta = val;
  3646. return this;
  3647. }
  3648. // getter
  3649. return this._meta;
  3650. },
  3651. destroy: function() {
  3652. var canvas = this._canvas;
  3653. this._img.onload = null;
  3654. if ( canvas ) {
  3655. canvas.getContext('2d')
  3656. .clearRect( 0, 0, canvas.width, canvas.height );
  3657. canvas.width = canvas.height = 0;
  3658. this._canvas = null;
  3659. }
  3660. // 释放内存。非常重要,否则释放不了image的内存。
  3661. this._img.src = BLANK;
  3662. this._img = this._blob = null;
  3663. },
  3664. _resize: function( img, cvs, width, height ) {
  3665. var opts = this.options,
  3666. naturalWidth = img.width,
  3667. naturalHeight = img.height,
  3668. orientation = this.getOrientation(),
  3669. scale, w, h, x, y;
  3670. // values that require 90 degree rotation
  3671. if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) {
  3672. // 交换width, height的值。
  3673. width ^= height;
  3674. height ^= width;
  3675. width ^= height;
  3676. }
  3677. scale = Math[ opts.crop ? 'max' : 'min' ]( width / naturalWidth,
  3678. height / naturalHeight );
  3679. // 不允许放大。
  3680. opts.allowMagnify || (scale = Math.min( 1, scale ));
  3681. w = naturalWidth * scale;
  3682. h = naturalHeight * scale;
  3683. if ( opts.crop ) {
  3684. cvs.width = width;
  3685. cvs.height = height;
  3686. } else {
  3687. cvs.width = w;
  3688. cvs.height = h;
  3689. }
  3690. x = (cvs.width - w) / 2;
  3691. y = (cvs.height - h) / 2;
  3692. opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation );
  3693. this._renderImageToCanvas( cvs, img, x, y, w, h );
  3694. },
  3695. _rotate2Orientaion: function( canvas, orientation ) {
  3696. var width = canvas.width,
  3697. height = canvas.height,
  3698. ctx = canvas.getContext('2d');
  3699. switch ( orientation ) {
  3700. case 5:
  3701. case 6:
  3702. case 7:
  3703. case 8:
  3704. canvas.width = height;
  3705. canvas.height = width;
  3706. break;
  3707. }
  3708. switch ( orientation ) {
  3709. case 2: // horizontal flip
  3710. ctx.translate( width, 0 );
  3711. ctx.scale( -1, 1 );
  3712. break;
  3713. case 3: // 180 rotate left
  3714. ctx.translate( width, height );
  3715. ctx.rotate( Math.PI );
  3716. break;
  3717. case 4: // vertical flip
  3718. ctx.translate( 0, height );
  3719. ctx.scale( 1, -1 );
  3720. break;
  3721. case 5: // vertical flip + 90 rotate right
  3722. ctx.rotate( 0.5 * Math.PI );
  3723. ctx.scale( 1, -1 );
  3724. break;
  3725. case 6: // 90 rotate right
  3726. ctx.rotate( 0.5 * Math.PI );
  3727. ctx.translate( 0, -height );
  3728. break;
  3729. case 7: // horizontal flip + 90 rotate right
  3730. ctx.rotate( 0.5 * Math.PI );
  3731. ctx.translate( width, -height );
  3732. ctx.scale( -1, 1 );
  3733. break;
  3734. case 8: // 90 rotate left
  3735. ctx.rotate( -0.5 * Math.PI );
  3736. ctx.translate( -width, 0 );
  3737. break;
  3738. }
  3739. },
  3740. // https://github.com/stomita/ios-imagefile-megapixel/
  3741. // blob/master/src/megapix-image.js
  3742. _renderImageToCanvas: (function() {
  3743. // 如果不是ios, 不需要这么复杂!
  3744. if ( !Base.os.ios ) {
  3745. return function( canvas, img, x, y, w, h ) {
  3746. canvas.getContext('2d').drawImage( img, x, y, w, h );
  3747. };
  3748. }
  3749. /**
  3750. * Detecting vertical squash in loaded image.
  3751. * Fixes a bug which squash image vertically while drawing into
  3752. * canvas for some images.
  3753. */
  3754. function detectVerticalSquash( img, iw, ih ) {
  3755. var canvas = document.createElement('canvas'),
  3756. ctx = canvas.getContext('2d'),
  3757. sy = 0,
  3758. ey = ih,
  3759. py = ih,
  3760. data, alpha, ratio;
  3761. canvas.width = 1;
  3762. canvas.height = ih;
  3763. ctx.drawImage( img, 0, 0 );
  3764. data = ctx.getImageData( 0, 0, 1, ih ).data;
  3765. // search image edge pixel position in case
  3766. // it is squashed vertically.
  3767. while ( py > sy ) {
  3768. alpha = data[ (py - 1) * 4 + 3 ];
  3769. if ( alpha === 0 ) {
  3770. ey = py;
  3771. } else {
  3772. sy = py;
  3773. }
  3774. py = (ey + sy) >> 1;
  3775. }
  3776. ratio = (py / ih);
  3777. return (ratio === 0) ? 1 : ratio;
  3778. }
  3779. // fix ie7 bug
  3780. // http://stackoverflow.com/questions/11929099/
  3781. // html5-canvas-drawimage-ratio-bug-ios
  3782. if ( Base.os.ios >= 7 ) {
  3783. return function( canvas, img, x, y, w, h ) {
  3784. var iw = img.naturalWidth,
  3785. ih = img.naturalHeight,
  3786. vertSquashRatio = detectVerticalSquash( img, iw, ih );
  3787. return canvas.getContext('2d').drawImage( img, 0, 0,
  3788. iw * vertSquashRatio, ih * vertSquashRatio,
  3789. x, y, w, h );
  3790. };
  3791. }
  3792. /**
  3793. * Detect subsampling in loaded image.
  3794. * In iOS, larger images than 2M pixels may be
  3795. * subsampled in rendering.
  3796. */
  3797. function detectSubsampling( img ) {
  3798. var iw = img.naturalWidth,
  3799. ih = img.naturalHeight,
  3800. canvas, ctx;
  3801. // subsampling may happen overmegapixel image
  3802. if ( iw * ih > 1024 * 1024 ) {
  3803. canvas = document.createElement('canvas');
  3804. canvas.width = canvas.height = 1;
  3805. ctx = canvas.getContext('2d');
  3806. ctx.drawImage( img, -iw + 1, 0 );
  3807. // subsampled image becomes half smaller in rendering size.
  3808. // check alpha channel value to confirm image is covering
  3809. // edge pixel or not. if alpha value is 0
  3810. // image is not covering, hence subsampled.
  3811. return ctx.getImageData( 0, 0, 1, 1 ).data[ 3 ] === 0;
  3812. } else {
  3813. return false;
  3814. }
  3815. }
  3816. return function( canvas, img, x, y, width, height ) {
  3817. var iw = img.naturalWidth,
  3818. ih = img.naturalHeight,
  3819. ctx = canvas.getContext('2d'),
  3820. subsampled = detectSubsampling( img ),
  3821. doSquash = this.type === 'image/jpeg',
  3822. d = 1024,
  3823. sy = 0,
  3824. dy = 0,
  3825. tmpCanvas, tmpCtx, vertSquashRatio, dw, dh, sx, dx;
  3826. if ( subsampled ) {
  3827. iw /= 2;
  3828. ih /= 2;
  3829. }
  3830. ctx.save();
  3831. tmpCanvas = document.createElement('canvas');
  3832. tmpCanvas.width = tmpCanvas.height = d;
  3833. tmpCtx = tmpCanvas.getContext('2d');
  3834. vertSquashRatio = doSquash ?
  3835. detectVerticalSquash( img, iw, ih ) : 1;
  3836. dw = Math.ceil( d * width / iw );
  3837. dh = Math.ceil( d * height / ih / vertSquashRatio );
  3838. while ( sy < ih ) {
  3839. sx = 0;
  3840. dx = 0;
  3841. while ( sx < iw ) {
  3842. tmpCtx.clearRect( 0, 0, d, d );
  3843. tmpCtx.drawImage( img, -sx, -sy );
  3844. ctx.drawImage( tmpCanvas, 0, 0, d, d,
  3845. x + dx, y + dy, dw, dh );
  3846. sx += d;
  3847. dx += dw;
  3848. }
  3849. sy += d;
  3850. dy += dh;
  3851. }
  3852. ctx.restore();
  3853. tmpCanvas = tmpCtx = null;
  3854. };
  3855. })()
  3856. });
  3857. });
  3858. /**
  3859. * 这个方式性能不行,但是可以解决android里面的toDataUrl的bug
  3860. * android里面toDataUrl('image/jpege')得到的结果却是png.
  3861. *
  3862. * 所以这里没辙,只能借助这个工具
  3863. * @fileOverview jpeg encoder
  3864. */
  3865. define('runtime/html5/jpegencoder',[], function( require, exports, module ) {
  3866. /*
  3867. Copyright (c) 2008, Adobe Systems Incorporated
  3868. All rights reserved.
  3869. Redistribution and use in source and binary forms, with or without
  3870. modification, are permitted provided that the following conditions are
  3871. met:
  3872. * Redistributions of source code must retain the above copyright notice,
  3873. this list of conditions and the following disclaimer.
  3874. * Redistributions in binary form must reproduce the above copyright
  3875. notice, this list of conditions and the following disclaimer in the
  3876. documentation and/or other materials provided with the distribution.
  3877. * Neither the name of Adobe Systems Incorporated nor the names of its
  3878. contributors may be used to endorse or promote products derived from
  3879. this software without specific prior written permission.
  3880. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  3881. IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  3882. THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  3883. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  3884. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  3885. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  3886. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  3887. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  3888. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  3889. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  3890. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  3891. */
  3892. /*
  3893. JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009
  3894. Basic GUI blocking jpeg encoder
  3895. */
  3896. function JPEGEncoder(quality) {
  3897. var self = this;
  3898. var fround = Math.round;
  3899. var ffloor = Math.floor;
  3900. var YTable = new Array(64);
  3901. var UVTable = new Array(64);
  3902. var fdtbl_Y = new Array(64);
  3903. var fdtbl_UV = new Array(64);
  3904. var YDC_HT;
  3905. var UVDC_HT;
  3906. var YAC_HT;
  3907. var UVAC_HT;
  3908. var bitcode = new Array(65535);
  3909. var category = new Array(65535);
  3910. var outputfDCTQuant = new Array(64);
  3911. var DU = new Array(64);
  3912. var byteout = [];
  3913. var bytenew = 0;
  3914. var bytepos = 7;
  3915. var YDU = new Array(64);
  3916. var UDU = new Array(64);
  3917. var VDU = new Array(64);
  3918. var clt = new Array(256);
  3919. var RGB_YUV_TABLE = new Array(2048);
  3920. var currentQuality;
  3921. var ZigZag = [
  3922. 0, 1, 5, 6,14,15,27,28,
  3923. 2, 4, 7,13,16,26,29,42,
  3924. 3, 8,12,17,25,30,41,43,
  3925. 9,11,18,24,31,40,44,53,
  3926. 10,19,23,32,39,45,52,54,
  3927. 20,22,33,38,46,51,55,60,
  3928. 21,34,37,47,50,56,59,61,
  3929. 35,36,48,49,57,58,62,63
  3930. ];
  3931. var std_dc_luminance_nrcodes = [0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0];
  3932. var std_dc_luminance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
  3933. var std_ac_luminance_nrcodes = [0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d];
  3934. var std_ac_luminance_values = [
  3935. 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,
  3936. 0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,
  3937. 0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,
  3938. 0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,
  3939. 0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,
  3940. 0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,
  3941. 0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,
  3942. 0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,
  3943. 0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,
  3944. 0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,
  3945. 0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,
  3946. 0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
  3947. 0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,
  3948. 0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,
  3949. 0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,
  3950. 0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,
  3951. 0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,
  3952. 0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,
  3953. 0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,
  3954. 0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
  3955. 0xf9,0xfa
  3956. ];
  3957. var std_dc_chrominance_nrcodes = [0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0];
  3958. var std_dc_chrominance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
  3959. var std_ac_chrominance_nrcodes = [0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77];
  3960. var std_ac_chrominance_values = [
  3961. 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,
  3962. 0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,
  3963. 0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,
  3964. 0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,
  3965. 0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,
  3966. 0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,
  3967. 0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,
  3968. 0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,
  3969. 0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,
  3970. 0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,
  3971. 0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,
  3972. 0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
  3973. 0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,
  3974. 0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,
  3975. 0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,
  3976. 0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,
  3977. 0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,
  3978. 0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,
  3979. 0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,
  3980. 0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
  3981. 0xf9,0xfa
  3982. ];
  3983. function initQuantTables(sf){
  3984. var YQT = [
  3985. 16, 11, 10, 16, 24, 40, 51, 61,
  3986. 12, 12, 14, 19, 26, 58, 60, 55,
  3987. 14, 13, 16, 24, 40, 57, 69, 56,
  3988. 14, 17, 22, 29, 51, 87, 80, 62,
  3989. 18, 22, 37, 56, 68,109,103, 77,
  3990. 24, 35, 55, 64, 81,104,113, 92,
  3991. 49, 64, 78, 87,103,121,120,101,
  3992. 72, 92, 95, 98,112,100,103, 99
  3993. ];
  3994. for (var i = 0; i < 64; i++) {
  3995. var t = ffloor((YQT[i]*sf+50)/100);
  3996. if (t < 1) {
  3997. t = 1;
  3998. } else if (t > 255) {
  3999. t = 255;
  4000. }
  4001. YTable[ZigZag[i]] = t;
  4002. }
  4003. var UVQT = [
  4004. 17, 18, 24, 47, 99, 99, 99, 99,
  4005. 18, 21, 26, 66, 99, 99, 99, 99,
  4006. 24, 26, 56, 99, 99, 99, 99, 99,
  4007. 47, 66, 99, 99, 99, 99, 99, 99,
  4008. 99, 99, 99, 99, 99, 99, 99, 99,
  4009. 99, 99, 99, 99, 99, 99, 99, 99,
  4010. 99, 99, 99, 99, 99, 99, 99, 99,
  4011. 99, 99, 99, 99, 99, 99, 99, 99
  4012. ];
  4013. for (var j = 0; j < 64; j++) {
  4014. var u = ffloor((UVQT[j]*sf+50)/100);
  4015. if (u < 1) {
  4016. u = 1;
  4017. } else if (u > 255) {
  4018. u = 255;
  4019. }
  4020. UVTable[ZigZag[j]] = u;
  4021. }
  4022. var aasf = [
  4023. 1.0, 1.387039845, 1.306562965, 1.175875602,
  4024. 1.0, 0.785694958, 0.541196100, 0.275899379
  4025. ];
  4026. var k = 0;
  4027. for (var row = 0; row < 8; row++)
  4028. {
  4029. for (var col = 0; col < 8; col++)
  4030. {
  4031. fdtbl_Y[k] = (1.0 / (YTable [ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
  4032. fdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
  4033. k++;
  4034. }
  4035. }
  4036. }
  4037. function computeHuffmanTbl(nrcodes, std_table){
  4038. var codevalue = 0;
  4039. var pos_in_table = 0;
  4040. var HT = new Array();
  4041. for (var k = 1; k <= 16; k++) {
  4042. for (var j = 1; j <= nrcodes[k]; j++) {
  4043. HT[std_table[pos_in_table]] = [];
  4044. HT[std_table[pos_in_table]][0] = codevalue;
  4045. HT[std_table[pos_in_table]][1] = k;
  4046. pos_in_table++;
  4047. codevalue++;
  4048. }
  4049. codevalue*=2;
  4050. }
  4051. return HT;
  4052. }
  4053. function initHuffmanTbl()
  4054. {
  4055. YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values);
  4056. UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values);
  4057. YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values);
  4058. UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values);
  4059. }
  4060. function initCategoryNumber()
  4061. {
  4062. var nrlower = 1;
  4063. var nrupper = 2;
  4064. for (var cat = 1; cat <= 15; cat++) {
  4065. //Positive numbers
  4066. for (var nr = nrlower; nr<nrupper; nr++) {
  4067. category[32767+nr] = cat;
  4068. bitcode[32767+nr] = [];
  4069. bitcode[32767+nr][1] = cat;
  4070. bitcode[32767+nr][0] = nr;
  4071. }
  4072. //Negative numbers
  4073. for (var nrneg =-(nrupper-1); nrneg<=-nrlower; nrneg++) {
  4074. category[32767+nrneg] = cat;
  4075. bitcode[32767+nrneg] = [];
  4076. bitcode[32767+nrneg][1] = cat;
  4077. bitcode[32767+nrneg][0] = nrupper-1+nrneg;
  4078. }
  4079. nrlower <<= 1;
  4080. nrupper <<= 1;
  4081. }
  4082. }
  4083. function initRGBYUVTable() {
  4084. for(var i = 0; i < 256;i++) {
  4085. RGB_YUV_TABLE[i] = 19595 * i;
  4086. RGB_YUV_TABLE[(i+ 256)>>0] = 38470 * i;
  4087. RGB_YUV_TABLE[(i+ 512)>>0] = 7471 * i + 0x8000;
  4088. RGB_YUV_TABLE[(i+ 768)>>0] = -11059 * i;
  4089. RGB_YUV_TABLE[(i+1024)>>0] = -21709 * i;
  4090. RGB_YUV_TABLE[(i+1280)>>0] = 32768 * i + 0x807FFF;
  4091. RGB_YUV_TABLE[(i+1536)>>0] = -27439 * i;
  4092. RGB_YUV_TABLE[(i+1792)>>0] = - 5329 * i;
  4093. }
  4094. }
  4095. // IO functions
  4096. function writeBits(bs)
  4097. {
  4098. var value = bs[0];
  4099. var posval = bs[1]-1;
  4100. while ( posval >= 0 ) {
  4101. if (value & (1 << posval) ) {
  4102. bytenew |= (1 << bytepos);
  4103. }
  4104. posval--;
  4105. bytepos--;
  4106. if (bytepos < 0) {
  4107. if (bytenew == 0xFF) {
  4108. writeByte(0xFF);
  4109. writeByte(0);
  4110. }
  4111. else {
  4112. writeByte(bytenew);
  4113. }
  4114. bytepos=7;
  4115. bytenew=0;
  4116. }
  4117. }
  4118. }
  4119. function writeByte(value)
  4120. {
  4121. byteout.push(clt[value]); // write char directly instead of converting later
  4122. }
  4123. function writeWord(value)
  4124. {
  4125. writeByte((value>>8)&0xFF);
  4126. writeByte((value )&0xFF);
  4127. }
  4128. // DCT & quantization core
  4129. function fDCTQuant(data, fdtbl)
  4130. {
  4131. var d0, d1, d2, d3, d4, d5, d6, d7;
  4132. /* Pass 1: process rows. */
  4133. var dataOff=0;
  4134. var i;
  4135. var I8 = 8;
  4136. var I64 = 64;
  4137. for (i=0; i<I8; ++i)
  4138. {
  4139. d0 = data[dataOff];
  4140. d1 = data[dataOff+1];
  4141. d2 = data[dataOff+2];
  4142. d3 = data[dataOff+3];
  4143. d4 = data[dataOff+4];
  4144. d5 = data[dataOff+5];
  4145. d6 = data[dataOff+6];
  4146. d7 = data[dataOff+7];
  4147. var tmp0 = d0 + d7;
  4148. var tmp7 = d0 - d7;
  4149. var tmp1 = d1 + d6;
  4150. var tmp6 = d1 - d6;
  4151. var tmp2 = d2 + d5;
  4152. var tmp5 = d2 - d5;
  4153. var tmp3 = d3 + d4;
  4154. var tmp4 = d3 - d4;
  4155. /* Even part */
  4156. var tmp10 = tmp0 + tmp3; /* phase 2 */
  4157. var tmp13 = tmp0 - tmp3;
  4158. var tmp11 = tmp1 + tmp2;
  4159. var tmp12 = tmp1 - tmp2;
  4160. data[dataOff] = tmp10 + tmp11; /* phase 3 */
  4161. data[dataOff+4] = tmp10 - tmp11;
  4162. var z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */
  4163. data[dataOff+2] = tmp13 + z1; /* phase 5 */
  4164. data[dataOff+6] = tmp13 - z1;
  4165. /* Odd part */
  4166. tmp10 = tmp4 + tmp5; /* phase 2 */
  4167. tmp11 = tmp5 + tmp6;
  4168. tmp12 = tmp6 + tmp7;
  4169. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  4170. var z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */
  4171. var z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */
  4172. var z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */
  4173. var z3 = tmp11 * 0.707106781; /* c4 */
  4174. var z11 = tmp7 + z3; /* phase 5 */
  4175. var z13 = tmp7 - z3;
  4176. data[dataOff+5] = z13 + z2; /* phase 6 */
  4177. data[dataOff+3] = z13 - z2;
  4178. data[dataOff+1] = z11 + z4;
  4179. data[dataOff+7] = z11 - z4;
  4180. dataOff += 8; /* advance pointer to next row */
  4181. }
  4182. /* Pass 2: process columns. */
  4183. dataOff = 0;
  4184. for (i=0; i<I8; ++i)
  4185. {
  4186. d0 = data[dataOff];
  4187. d1 = data[dataOff + 8];
  4188. d2 = data[dataOff + 16];
  4189. d3 = data[dataOff + 24];
  4190. d4 = data[dataOff + 32];
  4191. d5 = data[dataOff + 40];
  4192. d6 = data[dataOff + 48];
  4193. d7 = data[dataOff + 56];
  4194. var tmp0p2 = d0 + d7;
  4195. var tmp7p2 = d0 - d7;
  4196. var tmp1p2 = d1 + d6;
  4197. var tmp6p2 = d1 - d6;
  4198. var tmp2p2 = d2 + d5;
  4199. var tmp5p2 = d2 - d5;
  4200. var tmp3p2 = d3 + d4;
  4201. var tmp4p2 = d3 - d4;
  4202. /* Even part */
  4203. var tmp10p2 = tmp0p2 + tmp3p2; /* phase 2 */
  4204. var tmp13p2 = tmp0p2 - tmp3p2;
  4205. var tmp11p2 = tmp1p2 + tmp2p2;
  4206. var tmp12p2 = tmp1p2 - tmp2p2;
  4207. data[dataOff] = tmp10p2 + tmp11p2; /* phase 3 */
  4208. data[dataOff+32] = tmp10p2 - tmp11p2;
  4209. var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781; /* c4 */
  4210. data[dataOff+16] = tmp13p2 + z1p2; /* phase 5 */
  4211. data[dataOff+48] = tmp13p2 - z1p2;
  4212. /* Odd part */
  4213. tmp10p2 = tmp4p2 + tmp5p2; /* phase 2 */
  4214. tmp11p2 = tmp5p2 + tmp6p2;
  4215. tmp12p2 = tmp6p2 + tmp7p2;
  4216. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  4217. var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433; /* c6 */
  4218. var z2p2 = 0.541196100 * tmp10p2 + z5p2; /* c2-c6 */
  4219. var z4p2 = 1.306562965 * tmp12p2 + z5p2; /* c2+c6 */
  4220. var z3p2 = tmp11p2 * 0.707106781; /* c4 */
  4221. var z11p2 = tmp7p2 + z3p2; /* phase 5 */
  4222. var z13p2 = tmp7p2 - z3p2;
  4223. data[dataOff+40] = z13p2 + z2p2; /* phase 6 */
  4224. data[dataOff+24] = z13p2 - z2p2;
  4225. data[dataOff+ 8] = z11p2 + z4p2;
  4226. data[dataOff+56] = z11p2 - z4p2;
  4227. dataOff++; /* advance pointer to next column */
  4228. }
  4229. // Quantize/descale the coefficients
  4230. var fDCTQuant;
  4231. for (i=0; i<I64; ++i)
  4232. {
  4233. // Apply the quantization and scaling factor & Round to nearest integer
  4234. fDCTQuant = data[i]*fdtbl[i];
  4235. outputfDCTQuant[i] = (fDCTQuant > 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0);
  4236. //outputfDCTQuant[i] = fround(fDCTQuant);
  4237. }
  4238. return outputfDCTQuant;
  4239. }
  4240. function writeAPP0()
  4241. {
  4242. writeWord(0xFFE0); // marker
  4243. writeWord(16); // length
  4244. writeByte(0x4A); // J
  4245. writeByte(0x46); // F
  4246. writeByte(0x49); // I
  4247. writeByte(0x46); // F
  4248. writeByte(0); // = "JFIF",'\0'
  4249. writeByte(1); // versionhi
  4250. writeByte(1); // versionlo
  4251. writeByte(0); // xyunits
  4252. writeWord(1); // xdensity
  4253. writeWord(1); // ydensity
  4254. writeByte(0); // thumbnwidth
  4255. writeByte(0); // thumbnheight
  4256. }
  4257. function writeSOF0(width, height)
  4258. {
  4259. writeWord(0xFFC0); // marker
  4260. writeWord(17); // length, truecolor YUV JPG
  4261. writeByte(8); // precision
  4262. writeWord(height);
  4263. writeWord(width);
  4264. writeByte(3); // nrofcomponents
  4265. writeByte(1); // IdY
  4266. writeByte(0x11); // HVY
  4267. writeByte(0); // QTY
  4268. writeByte(2); // IdU
  4269. writeByte(0x11); // HVU
  4270. writeByte(1); // QTU
  4271. writeByte(3); // IdV
  4272. writeByte(0x11); // HVV
  4273. writeByte(1); // QTV
  4274. }
  4275. function writeDQT()
  4276. {
  4277. writeWord(0xFFDB); // marker
  4278. writeWord(132); // length
  4279. writeByte(0);
  4280. for (var i=0; i<64; i++) {
  4281. writeByte(YTable[i]);
  4282. }
  4283. writeByte(1);
  4284. for (var j=0; j<64; j++) {
  4285. writeByte(UVTable[j]);
  4286. }
  4287. }
  4288. function writeDHT()
  4289. {
  4290. writeWord(0xFFC4); // marker
  4291. writeWord(0x01A2); // length
  4292. writeByte(0); // HTYDCinfo
  4293. for (var i=0; i<16; i++) {
  4294. writeByte(std_dc_luminance_nrcodes[i+1]);
  4295. }
  4296. for (var j=0; j<=11; j++) {
  4297. writeByte(std_dc_luminance_values[j]);
  4298. }
  4299. writeByte(0x10); // HTYACinfo
  4300. for (var k=0; k<16; k++) {
  4301. writeByte(std_ac_luminance_nrcodes[k+1]);
  4302. }
  4303. for (var l=0; l<=161; l++) {
  4304. writeByte(std_ac_luminance_values[l]);
  4305. }
  4306. writeByte(1); // HTUDCinfo
  4307. for (var m=0; m<16; m++) {
  4308. writeByte(std_dc_chrominance_nrcodes[m+1]);
  4309. }
  4310. for (var n=0; n<=11; n++) {
  4311. writeByte(std_dc_chrominance_values[n]);
  4312. }
  4313. writeByte(0x11); // HTUACinfo
  4314. for (var o=0; o<16; o++) {
  4315. writeByte(std_ac_chrominance_nrcodes[o+1]);
  4316. }
  4317. for (var p=0; p<=161; p++) {
  4318. writeByte(std_ac_chrominance_values[p]);
  4319. }
  4320. }
  4321. function writeSOS()
  4322. {
  4323. writeWord(0xFFDA); // marker
  4324. writeWord(12); // length
  4325. writeByte(3); // nrofcomponents
  4326. writeByte(1); // IdY
  4327. writeByte(0); // HTY
  4328. writeByte(2); // IdU
  4329. writeByte(0x11); // HTU
  4330. writeByte(3); // IdV
  4331. writeByte(0x11); // HTV
  4332. writeByte(0); // Ss
  4333. writeByte(0x3f); // Se
  4334. writeByte(0); // Bf
  4335. }
  4336. function processDU(CDU, fdtbl, DC, HTDC, HTAC){
  4337. var EOB = HTAC[0x00];
  4338. var M16zeroes = HTAC[0xF0];
  4339. var pos;
  4340. var I16 = 16;
  4341. var I63 = 63;
  4342. var I64 = 64;
  4343. var DU_DCT = fDCTQuant(CDU, fdtbl);
  4344. //ZigZag reorder
  4345. for (var j=0;j<I64;++j) {
  4346. DU[ZigZag[j]]=DU_DCT[j];
  4347. }
  4348. var Diff = DU[0] - DC; DC = DU[0];
  4349. //Encode DC
  4350. if (Diff==0) {
  4351. writeBits(HTDC[0]); // Diff might be 0
  4352. } else {
  4353. pos = 32767+Diff;
  4354. writeBits(HTDC[category[pos]]);
  4355. writeBits(bitcode[pos]);
  4356. }
  4357. //Encode ACs
  4358. var end0pos = 63; // was const... which is crazy
  4359. for (; (end0pos>0)&&(DU[end0pos]==0); end0pos--) {};
  4360. //end0pos = first element in reverse order !=0
  4361. if ( end0pos == 0) {
  4362. writeBits(EOB);
  4363. return DC;
  4364. }
  4365. var i = 1;
  4366. var lng;
  4367. while ( i <= end0pos ) {
  4368. var startpos = i;
  4369. for (; (DU[i]==0) && (i<=end0pos); ++i) {}
  4370. var nrzeroes = i-startpos;
  4371. if ( nrzeroes >= I16 ) {
  4372. lng = nrzeroes>>4;
  4373. for (var nrmarker=1; nrmarker <= lng; ++nrmarker)
  4374. writeBits(M16zeroes);
  4375. nrzeroes = nrzeroes&0xF;
  4376. }
  4377. pos = 32767+DU[i];
  4378. writeBits(HTAC[(nrzeroes<<4)+category[pos]]);
  4379. writeBits(bitcode[pos]);
  4380. i++;
  4381. }
  4382. if ( end0pos != I63 ) {
  4383. writeBits(EOB);
  4384. }
  4385. return DC;
  4386. }
  4387. function initCharLookupTable(){
  4388. var sfcc = String.fromCharCode;
  4389. for(var i=0; i < 256; i++){ ///// ACHTUNG // 255
  4390. clt[i] = sfcc(i);
  4391. }
  4392. }
  4393. this.encode = function(image,quality) // image data object
  4394. {
  4395. // var time_start = new Date().getTime();
  4396. if(quality) setQuality(quality);
  4397. // Initialize bit writer
  4398. byteout = new Array();
  4399. bytenew=0;
  4400. bytepos=7;
  4401. // Add JPEG headers
  4402. writeWord(0xFFD8); // SOI
  4403. writeAPP0();
  4404. writeDQT();
  4405. writeSOF0(image.width,image.height);
  4406. writeDHT();
  4407. writeSOS();
  4408. // Encode 8x8 macroblocks
  4409. var DCY=0;
  4410. var DCU=0;
  4411. var DCV=0;
  4412. bytenew=0;
  4413. bytepos=7;
  4414. this.encode.displayName = "_encode_";
  4415. var imageData = image.data;
  4416. var width = image.width;
  4417. var height = image.height;
  4418. var quadWidth = width*4;
  4419. var tripleWidth = width*3;
  4420. var x, y = 0;
  4421. var r, g, b;
  4422. var start,p, col,row,pos;
  4423. while(y < height){
  4424. x = 0;
  4425. while(x < quadWidth){
  4426. start = quadWidth * y + x;
  4427. p = start;
  4428. col = -1;
  4429. row = 0;
  4430. for(pos=0; pos < 64; pos++){
  4431. row = pos >> 3;// /8
  4432. col = ( pos & 7 ) * 4; // %8
  4433. p = start + ( row * quadWidth ) + col;
  4434. if(y+row >= height){ // padding bottom
  4435. p-= (quadWidth*(y+1+row-height));
  4436. }
  4437. if(x+col >= quadWidth){ // padding right
  4438. p-= ((x+col) - quadWidth +4)
  4439. }
  4440. r = imageData[ p++ ];
  4441. g = imageData[ p++ ];
  4442. b = imageData[ p++ ];
  4443. /* // calculate YUV values dynamically
  4444. YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80
  4445. UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));
  4446. VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));
  4447. */
  4448. // use lookup table (slightly faster)
  4449. YDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256)>>0] + RGB_YUV_TABLE[(b + 512)>>0]) >> 16)-128;
  4450. UDU[pos] = ((RGB_YUV_TABLE[(r + 768)>>0] + RGB_YUV_TABLE[(g + 1024)>>0] + RGB_YUV_TABLE[(b + 1280)>>0]) >> 16)-128;
  4451. VDU[pos] = ((RGB_YUV_TABLE[(r + 1280)>>0] + RGB_YUV_TABLE[(g + 1536)>>0] + RGB_YUV_TABLE[(b + 1792)>>0]) >> 16)-128;
  4452. }
  4453. DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
  4454. DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
  4455. DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
  4456. x+=32;
  4457. }
  4458. y+=8;
  4459. }
  4460. ////////////////////////////////////////////////////////////////
  4461. // Do the bit alignment of the EOI marker
  4462. if ( bytepos >= 0 ) {
  4463. var fillbits = [];
  4464. fillbits[1] = bytepos+1;
  4465. fillbits[0] = (1<<(bytepos+1))-1;
  4466. writeBits(fillbits);
  4467. }
  4468. writeWord(0xFFD9); //EOI
  4469. var jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join(''));
  4470. byteout = [];
  4471. // benchmarking
  4472. // var duration = new Date().getTime() - time_start;
  4473. // console.log('Encoding time: '+ currentQuality + 'ms');
  4474. //
  4475. return jpegDataUri
  4476. }
  4477. function setQuality(quality){
  4478. if (quality <= 0) {
  4479. quality = 1;
  4480. }
  4481. if (quality > 100) {
  4482. quality = 100;
  4483. }
  4484. if(currentQuality == quality) return // don't recalc if unchanged
  4485. var sf = 0;
  4486. if (quality < 50) {
  4487. sf = Math.floor(5000 / quality);
  4488. } else {
  4489. sf = Math.floor(200 - quality*2);
  4490. }
  4491. initQuantTables(sf);
  4492. currentQuality = quality;
  4493. // console.log('Quality set to: '+quality +'%');
  4494. }
  4495. function init(){
  4496. // var time_start = new Date().getTime();
  4497. if(!quality) quality = 50;
  4498. // Create tables
  4499. initCharLookupTable()
  4500. initHuffmanTbl();
  4501. initCategoryNumber();
  4502. initRGBYUVTable();
  4503. setQuality(quality);
  4504. // var duration = new Date().getTime() - time_start;
  4505. // console.log('Initialization '+ duration + 'ms');
  4506. }
  4507. init();
  4508. };
  4509. JPEGEncoder.encode = function( data, quality ) {
  4510. var encoder = new JPEGEncoder( quality );
  4511. return encoder.encode( data );
  4512. }
  4513. return JPEGEncoder;
  4514. });
  4515. /**
  4516. * @fileOverview Fix android canvas.toDataUrl bug.
  4517. */
  4518. define('runtime/html5/androidpatch',[
  4519. 'runtime/html5/util',
  4520. 'runtime/html5/jpegencoder',
  4521. 'base'
  4522. ], function( Util, encoder, Base ) {
  4523. var origin = Util.canvasToDataUrl,
  4524. supportJpeg;
  4525. Util.canvasToDataUrl = function( canvas, type, quality ) {
  4526. var ctx, w, h, fragement, parts;
  4527. // 非android手机直接跳过。
  4528. if ( !Base.os.android ) {
  4529. return origin.apply( null, arguments );
  4530. }
  4531. // 检测是否canvas支持jpeg导出,根据数据格式来判断。
  4532. // JPEG 前两位分别是:255, 216
  4533. if ( type === 'image/jpeg' && typeof supportJpeg === 'undefined' ) {
  4534. fragement = origin.apply( null, arguments );
  4535. parts = fragement.split(',');
  4536. if ( ~parts[ 0 ].indexOf('base64') ) {
  4537. fragement = atob( parts[ 1 ] );
  4538. } else {
  4539. fragement = decodeURIComponent( parts[ 1 ] );
  4540. }
  4541. fragement = fragement.substring( 0, 2 );
  4542. supportJpeg = fragement.charCodeAt( 0 ) === 255 &&
  4543. fragement.charCodeAt( 1 ) === 216;
  4544. }
  4545. // 只有在android环境下才修复
  4546. if ( type === 'image/jpeg' && !supportJpeg ) {
  4547. w = canvas.width;
  4548. h = canvas.height;
  4549. ctx = canvas.getContext('2d');
  4550. return encoder.encode( ctx.getImageData( 0, 0, w, h ), quality );
  4551. }
  4552. return origin.apply( null, arguments );
  4553. };
  4554. });
  4555. /**
  4556. * @fileOverview Transport
  4557. * @todo 支持chunked传输,优势:
  4558. * 可以将大文件分成小块,挨个传输,可以提高大文件成功率,当失败的时候,也只需要重传那小部分,
  4559. * 而不需要重头再传一次。另外断点续传也需要用chunked方式。
  4560. */
  4561. define('runtime/html5/transport',[
  4562. 'base',
  4563. 'runtime/html5/runtime'
  4564. ], function( Base, Html5Runtime ) {
  4565. var noop = Base.noop,
  4566. $ = Base.$;
  4567. return Html5Runtime.register( 'Transport', {
  4568. init: function() {
  4569. this._status = 0;
  4570. this._response = null;
  4571. },
  4572. send: function() {
  4573. var owner = this.owner,
  4574. opts = this.options,
  4575. xhr = this._initAjax(),
  4576. blob = owner._blob,
  4577. server = opts.server,
  4578. formData, binary, fr;
  4579. if ( opts.sendAsBinary ) {
  4580. server += (/\?/.test( server ) ? '&' : '?') +
  4581. $.param( owner._formData );
  4582. binary = blob.getSource();
  4583. } else {
  4584. formData = new FormData();
  4585. $.each( owner._formData, function( k, v ) {
  4586. formData.append( k, v );
  4587. });
  4588. formData.append( opts.fileVal, blob.getSource(),
  4589. opts.filename || owner._formData.name || '' );
  4590. }
  4591. if ( opts.withCredentials && 'withCredentials' in xhr ) {
  4592. xhr.open( opts.method, server, true );
  4593. xhr.withCredentials = true;
  4594. } else {
  4595. xhr.open( opts.method, server );
  4596. }
  4597. this._setRequestHeader( xhr, opts.headers );
  4598. if ( binary ) {
  4599. xhr.overrideMimeType('application/octet-stream');
  4600. // android直接发送blob会导致服务端接收到的是空文件。
  4601. // bug详情。
  4602. // https://code.google.com/p/android/issues/detail?id=39882
  4603. // 所以先用fileReader读取出来再通过arraybuffer的方式发送。
  4604. if ( Base.os.android ) {
  4605. fr = new FileReader();
  4606. fr.onload = function() {
  4607. xhr.send( this.result );
  4608. fr = fr.onload = null;
  4609. };
  4610. fr.readAsArrayBuffer( binary );
  4611. } else {
  4612. xhr.send( binary );
  4613. }
  4614. } else {
  4615. xhr.send( formData );
  4616. }
  4617. },
  4618. getResponse: function() {
  4619. return this._response;
  4620. },
  4621. getResponseAsJson: function() {
  4622. return this._parseJson( this._response );
  4623. },
  4624. getStatus: function() {
  4625. return this._status;
  4626. },
  4627. abort: function() {
  4628. var xhr = this._xhr;
  4629. if ( xhr ) {
  4630. xhr.upload.onprogress = noop;
  4631. xhr.onreadystatechange = noop;
  4632. xhr.abort();
  4633. this._xhr = xhr = null;
  4634. }
  4635. },
  4636. destroy: function() {
  4637. this.abort();
  4638. },
  4639. _initAjax: function() {
  4640. var me = this,
  4641. xhr = new XMLHttpRequest(),
  4642. opts = this.options;
  4643. if ( opts.withCredentials && !('withCredentials' in xhr) &&
  4644. typeof XDomainRequest !== 'undefined' ) {
  4645. xhr = new XDomainRequest();
  4646. }
  4647. xhr.upload.onprogress = function( e ) {
  4648. var percentage = 0;
  4649. if ( e.lengthComputable ) {
  4650. percentage = e.loaded / e.total;
  4651. }
  4652. return me.trigger( 'progress', percentage );
  4653. };
  4654. xhr.onreadystatechange = function() {
  4655. if ( xhr.readyState !== 4 ) {
  4656. return;
  4657. }
  4658. xhr.upload.onprogress = noop;
  4659. xhr.onreadystatechange = noop;
  4660. me._xhr = null;
  4661. me._status = xhr.status;
  4662. if ( xhr.status >= 200 && xhr.status < 300 ) {
  4663. me._response = xhr.responseText;
  4664. return me.trigger('load');
  4665. } else if ( xhr.status >= 500 && xhr.status < 600 ) {
  4666. me._response = xhr.responseText;
  4667. return me.trigger( 'error', 'server' );
  4668. }
  4669. return me.trigger( 'error', me._status ? 'http' : 'abort' );
  4670. };
  4671. me._xhr = xhr;
  4672. return xhr;
  4673. },
  4674. _setRequestHeader: function( xhr, headers ) {
  4675. $.each( headers, function( key, val ) {
  4676. xhr.setRequestHeader( key, val );
  4677. });
  4678. },
  4679. _parseJson: function( str ) {
  4680. var json;
  4681. try {
  4682. json = JSON.parse( str );
  4683. } catch ( ex ) {
  4684. json = {};
  4685. }
  4686. return json;
  4687. }
  4688. });
  4689. });
  4690. define('webuploader',[
  4691. 'base',
  4692. 'widgets/filepicker',
  4693. 'widgets/image',
  4694. 'widgets/queue',
  4695. 'widgets/runtime',
  4696. 'widgets/upload',
  4697. 'runtime/html5/blob',
  4698. 'runtime/html5/filepicker',
  4699. 'runtime/html5/imagemeta/exif',
  4700. 'runtime/html5/image',
  4701. 'runtime/html5/androidpatch',
  4702. 'runtime/html5/transport'
  4703. ], function( Base ) {
  4704. return Base;
  4705. });
  4706. return require('webuploader');
  4707. });