webuploader.withoutimage.js 159 KB

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