webuploader.js 178 KB

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