webuploader.noimage.js 164 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027
  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|dom} 指定选择文件的按钮容器,不指定则不创建按钮。**注意** 这里虽然写的是 id, 但是不是只支持 id, 还支持 class, 或者 dom 节点。
  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. /**
  2244. * @property {Object} [runtimeOrder=html5,flash]
  2245. * @namespace options
  2246. * @for Uploader
  2247. * @description 指定运行时启动顺序。默认会想尝试 html5 是否支持,如果支持则使用 html5, 否则则使用 flash.
  2248. *
  2249. * 可以将此值设置成 `flash`,来强制使用 flash 运行时。
  2250. */
  2251. return Uploader.register({
  2252. name: 'runtime',
  2253. init: function() {
  2254. if ( !this.predictRuntimeType() ) {
  2255. throw Error('Runtime Error');
  2256. }
  2257. },
  2258. /**
  2259. * 预测Uploader将采用哪个`Runtime`
  2260. * @grammar predictRuntimeType() => String
  2261. * @method predictRuntimeType
  2262. * @for Uploader
  2263. */
  2264. predictRuntimeType: function() {
  2265. var orders = this.options.runtimeOrder || Runtime.orders,
  2266. type = this.type,
  2267. i, len;
  2268. if ( !type ) {
  2269. orders = orders.split( /\s*,\s*/g );
  2270. for ( i = 0, len = orders.length; i < len; i++ ) {
  2271. if ( Runtime.hasRuntime( orders[ i ] ) ) {
  2272. this.type = type = orders[ i ];
  2273. break;
  2274. }
  2275. }
  2276. }
  2277. return type;
  2278. }
  2279. });
  2280. });
  2281. /**
  2282. * @fileOverview Transport
  2283. */
  2284. define('lib/transport',[
  2285. 'base',
  2286. 'runtime/client',
  2287. 'mediator'
  2288. ], function( Base, RuntimeClient, Mediator ) {
  2289. var $ = Base.$;
  2290. function Transport( opts ) {
  2291. var me = this;
  2292. opts = me.options = $.extend( true, {}, Transport.options, opts || {} );
  2293. RuntimeClient.call( this, 'Transport' );
  2294. this._blob = null;
  2295. this._formData = opts.formData || {};
  2296. this._headers = opts.headers || {};
  2297. this.on( 'progress', this._timeout );
  2298. this.on( 'load error', function() {
  2299. me.trigger( 'progress', 1 );
  2300. clearTimeout( me._timer );
  2301. });
  2302. }
  2303. Transport.options = {
  2304. server: '',
  2305. method: 'POST',
  2306. // 跨域时,是否允许携带cookie, 只有html5 runtime才有效
  2307. withCredentials: false,
  2308. fileVal: 'file',
  2309. timeout: 2 * 60 * 1000, // 2分钟
  2310. formData: {},
  2311. headers: {},
  2312. sendAsBinary: false
  2313. };
  2314. $.extend( Transport.prototype, {
  2315. // 添加Blob, 只能添加一次,最后一次有效。
  2316. appendBlob: function( key, blob, filename ) {
  2317. var me = this,
  2318. opts = me.options;
  2319. if ( me.getRuid() ) {
  2320. me.disconnectRuntime();
  2321. }
  2322. // 连接到blob归属的同一个runtime.
  2323. me.connectRuntime( blob.ruid, function() {
  2324. me.exec('init');
  2325. });
  2326. me._blob = blob;
  2327. opts.fileVal = key || opts.fileVal;
  2328. opts.filename = filename || opts.filename;
  2329. },
  2330. // 添加其他字段
  2331. append: function( key, value ) {
  2332. if ( typeof key === 'object' ) {
  2333. $.extend( this._formData, key );
  2334. } else {
  2335. this._formData[ key ] = value;
  2336. }
  2337. },
  2338. setRequestHeader: function( key, value ) {
  2339. if ( typeof key === 'object' ) {
  2340. $.extend( this._headers, key );
  2341. } else {
  2342. this._headers[ key ] = value;
  2343. }
  2344. },
  2345. send: function( method ) {
  2346. this.exec( 'send', method );
  2347. this._timeout();
  2348. },
  2349. abort: function() {
  2350. clearTimeout( this._timer );
  2351. return this.exec('abort');
  2352. },
  2353. destroy: function() {
  2354. this.trigger('destroy');
  2355. this.off();
  2356. this.exec('destroy');
  2357. this.disconnectRuntime();
  2358. },
  2359. getResponse: function() {
  2360. return this.exec('getResponse');
  2361. },
  2362. getResponseAsJson: function() {
  2363. return this.exec('getResponseAsJson');
  2364. },
  2365. getStatus: function() {
  2366. return this.exec('getStatus');
  2367. },
  2368. _timeout: function() {
  2369. var me = this,
  2370. duration = me.options.timeout;
  2371. if ( !duration ) {
  2372. return;
  2373. }
  2374. clearTimeout( me._timer );
  2375. me._timer = setTimeout(function() {
  2376. me.abort();
  2377. me.trigger( 'error', 'timeout' );
  2378. }, duration );
  2379. }
  2380. });
  2381. // 让Transport具备事件功能。
  2382. Mediator.installTo( Transport.prototype );
  2383. return Transport;
  2384. });
  2385. /**
  2386. * @fileOverview 负责文件上传相关。
  2387. */
  2388. define('widgets/upload',[
  2389. 'base',
  2390. 'uploader',
  2391. 'file',
  2392. 'lib/transport',
  2393. 'widgets/widget'
  2394. ], function( Base, Uploader, WUFile, Transport ) {
  2395. var $ = Base.$,
  2396. isPromise = Base.isPromise,
  2397. Status = WUFile.Status;
  2398. // 添加默认配置项
  2399. $.extend( Uploader.options, {
  2400. /**
  2401. * @property {Boolean} [prepareNextFile=false]
  2402. * @namespace options
  2403. * @for Uploader
  2404. * @description 是否允许在文件传输时提前把下一个文件准备好。
  2405. * 对于一个文件的准备工作比较耗时,比如图片压缩,md5序列化。
  2406. * 如果能提前在当前文件传输期处理,可以节省总体耗时。
  2407. */
  2408. prepareNextFile: false,
  2409. /**
  2410. * @property {Boolean} [chunked=false]
  2411. * @namespace options
  2412. * @for Uploader
  2413. * @description 是否要分片处理大文件上传。
  2414. */
  2415. chunked: false,
  2416. /**
  2417. * @property {Boolean} [chunkSize=5242880]
  2418. * @namespace options
  2419. * @for Uploader
  2420. * @description 如果要分片,分多大一片? 默认大小为5M.
  2421. */
  2422. chunkSize: 5 * 1024 * 1024,
  2423. /**
  2424. * @property {Boolean} [chunkRetry=2]
  2425. * @namespace options
  2426. * @for Uploader
  2427. * @description 如果某个分片由于网络问题出错,允许自动重传多少次?
  2428. */
  2429. chunkRetry: 2,
  2430. /**
  2431. * @property {Boolean} [threads=3]
  2432. * @namespace options
  2433. * @for Uploader
  2434. * @description 上传并发数。允许同时最大上传进程数。
  2435. */
  2436. threads: 3,
  2437. /**
  2438. * @property {Object} [formData={}]
  2439. * @namespace options
  2440. * @for Uploader
  2441. * @description 文件上传请求的参数表,每次发送都会发送此对象中的参数。
  2442. */
  2443. formData: {}
  2444. /**
  2445. * @property {Object} [fileVal='file']
  2446. * @namespace options
  2447. * @for Uploader
  2448. * @description 设置文件上传域的name。
  2449. */
  2450. /**
  2451. * @property {Object} [method='POST']
  2452. * @namespace options
  2453. * @for Uploader
  2454. * @description 文件上传方式,`POST`或者`GET`。
  2455. */
  2456. /**
  2457. * @property {Object} [sendAsBinary=false]
  2458. * @namespace options
  2459. * @for Uploader
  2460. * @description 是否已二进制的流的方式发送文件,这样整个上传内容`php://input`都为文件内容,
  2461. * 其他参数在$_GET数组中。
  2462. */
  2463. });
  2464. // 负责将文件切片。
  2465. function CuteFile( file, chunkSize ) {
  2466. var pending = [],
  2467. blob = file.source,
  2468. total = blob.size,
  2469. chunks = chunkSize ? Math.ceil( total / chunkSize ) : 1,
  2470. start = 0,
  2471. index = 0,
  2472. len, api;
  2473. api = {
  2474. file: file,
  2475. has: function() {
  2476. return !!pending.length;
  2477. },
  2478. shift: function() {
  2479. return pending.shift();
  2480. },
  2481. unshift: function( block ) {
  2482. pending.unshift( block );
  2483. }
  2484. };
  2485. while ( index < chunks ) {
  2486. len = Math.min( chunkSize, total - start );
  2487. pending.push({
  2488. file: file,
  2489. start: start,
  2490. end: chunkSize ? (start + len) : total,
  2491. total: total,
  2492. chunks: chunks,
  2493. chunk: index++,
  2494. cuted: api
  2495. });
  2496. start += len;
  2497. }
  2498. file.blocks = pending.concat();
  2499. file.remaning = pending.length;
  2500. return api;
  2501. }
  2502. Uploader.register({
  2503. name: 'upload',
  2504. init: function() {
  2505. var owner = this.owner,
  2506. me = this;
  2507. this.runing = false;
  2508. this.progress = false;
  2509. owner
  2510. .on( 'startUpload', function() {
  2511. me.progress = true;
  2512. })
  2513. .on( 'uploadFinished', function() {
  2514. me.progress = false;
  2515. });
  2516. // 记录当前正在传的数据,跟threads相关
  2517. this.pool = [];
  2518. // 缓存分好片的文件。
  2519. this.stack = [];
  2520. // 缓存即将上传的文件。
  2521. this.pending = [];
  2522. // 跟踪还有多少分片在上传中但是没有完成上传。
  2523. this.remaning = 0;
  2524. this.__tick = Base.bindFn( this._tick, this );
  2525. owner.on( 'uploadComplete', function( file ) {
  2526. // 把其他块取消了。
  2527. file.blocks && $.each( file.blocks, function( _, v ) {
  2528. v.transport && (v.transport.abort(), v.transport.destroy());
  2529. delete v.transport;
  2530. });
  2531. delete file.blocks;
  2532. delete file.remaning;
  2533. });
  2534. },
  2535. reset: function() {
  2536. this.request( 'stop-upload', true );
  2537. this.runing = false;
  2538. this.pool = [];
  2539. this.stack = [];
  2540. this.pending = [];
  2541. this.remaning = 0;
  2542. this._trigged = false;
  2543. this._promise = null;
  2544. },
  2545. /**
  2546. * @event startUpload
  2547. * @description 当开始上传流程时触发。
  2548. * @for Uploader
  2549. */
  2550. /**
  2551. * 开始上传。此方法可以从初始状态调用开始上传流程,也可以从暂停状态调用,继续上传流程。
  2552. *
  2553. * 可以指定开始某一个文件。
  2554. * @grammar upload() => undefined
  2555. * @grammar upload( file | fileId) => undefined
  2556. * @method upload
  2557. * @for Uploader
  2558. */
  2559. startUpload: function(file) {
  2560. var me = this;
  2561. // 移出invalid的文件
  2562. $.each( me.request( 'get-files', Status.INVALID ), function() {
  2563. me.request( 'remove-file', this );
  2564. });
  2565. // 如果指定了开始某个文件,则只开始指定文件。
  2566. if ( file ) {
  2567. file = file.id ? file : me.request( 'get-file', file );
  2568. if (file.getStatus() === Status.INTERRUPT) {
  2569. $.each( me.pool, function( _, v ) {
  2570. // 之前暂停过。
  2571. if (v.file !== file) {
  2572. return;
  2573. }
  2574. v.transport && v.transport.send();
  2575. });
  2576. file.setStatus( Status.QUEUED );
  2577. } else if (file.getStatus() === Status.PROGRESS) {
  2578. return;
  2579. } else {
  2580. file.setStatus( Status.QUEUED );
  2581. }
  2582. } else {
  2583. $.each( me.request( 'get-files', [ Status.INITED ] ), function() {
  2584. this.setStatus( Status.QUEUED );
  2585. });
  2586. }
  2587. if ( me.runing ) {
  2588. return;
  2589. }
  2590. me.runing = true;
  2591. var files = [];
  2592. // 如果有暂停的,则续传
  2593. $.each( me.pool, function( _, v ) {
  2594. var file = v.file;
  2595. if ( file.getStatus() === Status.INTERRUPT ) {
  2596. files.push(file);
  2597. me._trigged = false;
  2598. v.transport && v.transport.send();
  2599. }
  2600. });
  2601. var file;
  2602. while ( (file = files.shift()) ) {
  2603. file.setStatus( Status.PROGRESS );
  2604. }
  2605. file || $.each( me.request( 'get-files',
  2606. Status.INTERRUPT ), function() {
  2607. this.setStatus( Status.PROGRESS );
  2608. });
  2609. me._trigged = false;
  2610. Base.nextTick( me.__tick );
  2611. me.owner.trigger('startUpload');
  2612. },
  2613. /**
  2614. * @event stopUpload
  2615. * @description 当开始上传流程暂停时触发。
  2616. * @for Uploader
  2617. */
  2618. /**
  2619. * 暂停上传。第一个参数为是否中断上传当前正在上传的文件。
  2620. *
  2621. * 如果第一个参数是文件,则只暂停指定文件。
  2622. * @grammar stop() => undefined
  2623. * @grammar stop( true ) => undefined
  2624. * @grammar stop( file ) => undefined
  2625. * @method stop
  2626. * @for Uploader
  2627. */
  2628. stopUpload: function( file, interrupt ) {
  2629. var me = this;
  2630. if (file === true) {
  2631. interrupt = file;
  2632. file = null;
  2633. }
  2634. if ( me.runing === false ) {
  2635. return;
  2636. }
  2637. // 如果只是暂停某个文件。
  2638. if ( file ) {
  2639. file = file.id ? file : me.request( 'get-file', file );
  2640. if ( file.getStatus() !== Status.PROGRESS &&
  2641. file.getStatus() !== Status.QUEUED ) {
  2642. return;
  2643. }
  2644. file.setStatus( Status.INTERRUPT );
  2645. $.each( me.pool, function( _, v ) {
  2646. // 只 abort 指定的文件。
  2647. if (v.file !== file) {
  2648. return;
  2649. }
  2650. v.transport && v.transport.abort();
  2651. me._putback(v);
  2652. me._popBlock(v);
  2653. });
  2654. return Base.nextTick( me.__tick );
  2655. }
  2656. me.runing = false;
  2657. if (this._promise && this._promise.file) {
  2658. this._promise.file.setStatus( Status.INTERRUPT );
  2659. }
  2660. interrupt && $.each( me.pool, function( _, v ) {
  2661. v.transport && v.transport.abort();
  2662. v.file.setStatus( Status.INTERRUPT );
  2663. });
  2664. me.owner.trigger('stopUpload');
  2665. },
  2666. /**
  2667. * @method cancelFile
  2668. * @grammar cancelFile( file ) => undefined
  2669. * @grammar cancelFile( id ) => undefined
  2670. * @param {File|id} file File对象或这File对象的id
  2671. * @description 标记文件状态为已取消, 同时将中断文件传输。
  2672. * @for Uploader
  2673. * @example
  2674. *
  2675. * $li.on('click', '.remove-this', function() {
  2676. * uploader.cancelFile( file );
  2677. * })
  2678. */
  2679. cancelFile: function( file ) {
  2680. file = file.id ? file : this.request( 'get-file', file );
  2681. // 如果正在上传。
  2682. file.blocks && $.each( file.blocks, function( _, v ) {
  2683. var _tr = v.transport;
  2684. if ( _tr ) {
  2685. _tr.abort();
  2686. _tr.destroy();
  2687. delete v.transport;
  2688. }
  2689. });
  2690. file.setStatus( Status.CANCELLED );
  2691. this.owner.trigger( 'fileDequeued', file );
  2692. },
  2693. /**
  2694. * 判断`Uplaode`r是否正在上传中。
  2695. * @grammar isInProgress() => Boolean
  2696. * @method isInProgress
  2697. * @for Uploader
  2698. */
  2699. isInProgress: function() {
  2700. return !!this.progress;
  2701. },
  2702. _getStats: function() {
  2703. return this.request('get-stats');
  2704. },
  2705. /**
  2706. * 掉过一个文件上传,直接标记指定文件为已上传状态。
  2707. * @grammar skipFile( file ) => undefined
  2708. * @method skipFile
  2709. * @for Uploader
  2710. */
  2711. skipFile: function( file, status ) {
  2712. file = file.id ? file : this.request( 'get-file', file );
  2713. file.setStatus( status || Status.COMPLETE );
  2714. file.skipped = true;
  2715. // 如果正在上传。
  2716. file.blocks && $.each( file.blocks, function( _, v ) {
  2717. var _tr = v.transport;
  2718. if ( _tr ) {
  2719. _tr.abort();
  2720. _tr.destroy();
  2721. delete v.transport;
  2722. }
  2723. });
  2724. this.owner.trigger( 'uploadSkip', file );
  2725. },
  2726. /**
  2727. * @event uploadFinished
  2728. * @description 当所有文件上传结束时触发。
  2729. * @for Uploader
  2730. */
  2731. _tick: function() {
  2732. var me = this,
  2733. opts = me.options,
  2734. fn, val;
  2735. // 上一个promise还没有结束,则等待完成后再执行。
  2736. if ( me._promise ) {
  2737. return me._promise.always( me.__tick );
  2738. }
  2739. // 还有位置,且还有文件要处理的话。
  2740. if ( me.pool.length < opts.threads && (val = me._nextBlock()) ) {
  2741. me._trigged = false;
  2742. fn = function( val ) {
  2743. me._promise = null;
  2744. // 有可能是reject过来的,所以要检测val的类型。
  2745. val && val.file && me._startSend( val );
  2746. Base.nextTick( me.__tick );
  2747. };
  2748. me._promise = isPromise( val ) ? val.always( fn ) : fn( val );
  2749. // 没有要上传的了,且没有正在传输的了。
  2750. } else if ( !me.remaning && !me._getStats().numOfQueue &&
  2751. !me._getStats().numofInterrupt ) {
  2752. me.runing = false;
  2753. me._trigged || Base.nextTick(function() {
  2754. me.owner.trigger('uploadFinished');
  2755. });
  2756. me._trigged = true;
  2757. }
  2758. },
  2759. _putback: function(block) {
  2760. var idx;
  2761. block.cuted.unshift(block);
  2762. idx = this.stack.indexOf(block.cuted);
  2763. if (!~idx) {
  2764. this.stack.unshift(block.cuted);
  2765. }
  2766. },
  2767. _getStack: function() {
  2768. var i = 0,
  2769. act;
  2770. while ( (act = this.stack[ i++ ]) ) {
  2771. if ( act.has() && act.file.getStatus() === Status.PROGRESS ) {
  2772. return act;
  2773. } else if (!act.has() ||
  2774. act.file.getStatus() !== Status.PROGRESS &&
  2775. act.file.getStatus() !== Status.INTERRUPT ) {
  2776. // 把已经处理完了的,或者,状态为非 progress(上传中)、
  2777. // interupt(暂停中) 的移除。
  2778. this.stack.splice( --i, 1 );
  2779. }
  2780. }
  2781. return null;
  2782. },
  2783. _nextBlock: function() {
  2784. var me = this,
  2785. opts = me.options,
  2786. act, next, done, preparing;
  2787. // 如果当前文件还有没有需要传输的,则直接返回剩下的。
  2788. if ( (act = this._getStack()) ) {
  2789. // 是否提前准备下一个文件
  2790. if ( opts.prepareNextFile && !me.pending.length ) {
  2791. me._prepareNextFile();
  2792. }
  2793. return act.shift();
  2794. // 否则,如果正在运行,则准备下一个文件,并等待完成后返回下个分片。
  2795. } else if ( me.runing ) {
  2796. // 如果缓存中有,则直接在缓存中取,没有则去queue中取。
  2797. if ( !me.pending.length && me._getStats().numOfQueue ) {
  2798. me._prepareNextFile();
  2799. }
  2800. next = me.pending.shift();
  2801. done = function( file ) {
  2802. if ( !file ) {
  2803. return null;
  2804. }
  2805. act = CuteFile( file, opts.chunked ? opts.chunkSize : 0 );
  2806. me.stack.push(act);
  2807. return act.shift();
  2808. };
  2809. // 文件可能还在prepare中,也有可能已经完全准备好了。
  2810. if ( isPromise( next) ) {
  2811. preparing = next.file;
  2812. next = next[ next.pipe ? 'pipe' : 'then' ]( done );
  2813. next.file = preparing;
  2814. return next;
  2815. }
  2816. return done( next );
  2817. }
  2818. },
  2819. /**
  2820. * @event uploadStart
  2821. * @param {File} file File对象
  2822. * @description 某个文件开始上传前触发,一个文件只会触发一次。
  2823. * @for Uploader
  2824. */
  2825. _prepareNextFile: function() {
  2826. var me = this,
  2827. file = me.request('fetch-file'),
  2828. pending = me.pending,
  2829. promise;
  2830. if ( file ) {
  2831. promise = me.request( 'before-send-file', file, function() {
  2832. // 有可能文件被skip掉了。文件被skip掉后,状态坑定不是Queued.
  2833. if ( file.getStatus() === Status.PROGRESS ||
  2834. file.getStatus() === Status.INTERRUPT ) {
  2835. return file;
  2836. }
  2837. return me._finishFile( file );
  2838. });
  2839. me.owner.trigger( 'uploadStart', file );
  2840. file.setStatus( Status.PROGRESS );
  2841. promise.file = file;
  2842. // 如果还在pending中,则替换成文件本身。
  2843. promise.done(function() {
  2844. var idx = $.inArray( promise, pending );
  2845. ~idx && pending.splice( idx, 1, file );
  2846. });
  2847. // befeore-send-file的钩子就有错误发生。
  2848. promise.fail(function( reason ) {
  2849. file.setStatus( Status.ERROR, reason );
  2850. me.owner.trigger( 'uploadError', file, reason );
  2851. me.owner.trigger( 'uploadComplete', file );
  2852. });
  2853. pending.push( promise );
  2854. }
  2855. },
  2856. // 让出位置了,可以让其他分片开始上传
  2857. _popBlock: function( block ) {
  2858. var idx = $.inArray( block, this.pool );
  2859. this.pool.splice( idx, 1 );
  2860. block.file.remaning--;
  2861. this.remaning--;
  2862. },
  2863. // 开始上传,可以被掉过。如果promise被reject了,则表示跳过此分片。
  2864. _startSend: function( block ) {
  2865. var me = this,
  2866. file = block.file,
  2867. promise;
  2868. // 有可能在 before-send-file 的 promise 期间改变了文件状态。
  2869. // 如:暂停,取消
  2870. // 我们不能中断 promise, 但是可以在 promise 完后,不做上传操作。
  2871. if ( file.getStatus() !== Status.PROGRESS ) {
  2872. // 如果是中断,则还需要放回去。
  2873. if (file.getStatus() === Status.INTERRUPT) {
  2874. me._putback(block);
  2875. }
  2876. return;
  2877. }
  2878. me.pool.push( block );
  2879. me.remaning++;
  2880. // 如果没有分片,则直接使用原始的。
  2881. // 不会丢失content-type信息。
  2882. block.blob = block.chunks === 1 ? file.source :
  2883. file.source.slice( block.start, block.end );
  2884. // hook, 每个分片发送之前可能要做些异步的事情。
  2885. promise = me.request( 'before-send', block, function() {
  2886. // 有可能文件已经上传出错了,所以不需要再传输了。
  2887. if ( file.getStatus() === Status.PROGRESS ) {
  2888. me._doSend( block );
  2889. } else {
  2890. me._popBlock( block );
  2891. Base.nextTick( me.__tick );
  2892. }
  2893. });
  2894. // 如果为fail了,则跳过此分片。
  2895. promise.fail(function() {
  2896. if ( file.remaning === 1 ) {
  2897. me._finishFile( file ).always(function() {
  2898. block.percentage = 1;
  2899. me._popBlock( block );
  2900. me.owner.trigger( 'uploadComplete', file );
  2901. Base.nextTick( me.__tick );
  2902. });
  2903. } else {
  2904. block.percentage = 1;
  2905. me.updateFileProgress( file );
  2906. me._popBlock( block );
  2907. Base.nextTick( me.__tick );
  2908. }
  2909. });
  2910. },
  2911. /**
  2912. * @event uploadBeforeSend
  2913. * @param {Object} object
  2914. * @param {Object} data 默认的上传参数,可以扩展此对象来控制上传参数。
  2915. * @param {Object} headers 可以扩展此对象来控制上传头部。
  2916. * @description 当某个文件的分块在发送前触发,主要用来询问是否要添加附带参数,大文件在开起分片上传的前提下此事件可能会触发多次。
  2917. * @for Uploader
  2918. */
  2919. /**
  2920. * @event uploadAccept
  2921. * @param {Object} object
  2922. * @param {Object} ret 服务端的返回数据,json格式,如果服务端不是json格式,从ret._raw中取数据,自行解析。
  2923. * @description 当某个文件上传到服务端响应后,会派送此事件来询问服务端响应是否有效。如果此事件handler返回值为`false`, 则此文件将派送`server`类型的`uploadError`事件。
  2924. * @for Uploader
  2925. */
  2926. /**
  2927. * @event uploadProgress
  2928. * @param {File} file File对象
  2929. * @param {Number} percentage 上传进度
  2930. * @description 上传过程中触发,携带上传进度。
  2931. * @for Uploader
  2932. */
  2933. /**
  2934. * @event uploadError
  2935. * @param {File} file File对象
  2936. * @param {String} reason 出错的code
  2937. * @description 当文件上传出错时触发。
  2938. * @for Uploader
  2939. */
  2940. /**
  2941. * @event uploadSuccess
  2942. * @param {File} file File对象
  2943. * @param {Object} response 服务端返回的数据
  2944. * @description 当文件上传成功时触发。
  2945. * @for Uploader
  2946. */
  2947. /**
  2948. * @event uploadComplete
  2949. * @param {File} [file] File对象
  2950. * @description 不管成功或者失败,文件上传完成时触发。
  2951. * @for Uploader
  2952. */
  2953. // 做上传操作。
  2954. _doSend: function( block ) {
  2955. var me = this,
  2956. owner = me.owner,
  2957. opts = me.options,
  2958. file = block.file,
  2959. tr = new Transport( opts ),
  2960. data = $.extend({}, opts.formData ),
  2961. headers = $.extend({}, opts.headers ),
  2962. requestAccept, ret;
  2963. block.transport = tr;
  2964. tr.on( 'destroy', function() {
  2965. delete block.transport;
  2966. me._popBlock( block );
  2967. Base.nextTick( me.__tick );
  2968. });
  2969. // 广播上传进度。以文件为单位。
  2970. tr.on( 'progress', function( percentage ) {
  2971. block.percentage = percentage;
  2972. me.updateFileProgress( file );
  2973. });
  2974. // 用来询问,是否返回的结果是有错误的。
  2975. requestAccept = function( reject ) {
  2976. var fn;
  2977. ret = tr.getResponseAsJson() || {};
  2978. ret._raw = tr.getResponse();
  2979. fn = function( value ) {
  2980. reject = value;
  2981. };
  2982. // 服务端响应了,不代表成功了,询问是否响应正确。
  2983. if ( !owner.trigger( 'uploadAccept', block, ret, fn ) ) {
  2984. reject = reject || 'server';
  2985. }
  2986. return reject;
  2987. };
  2988. // 尝试重试,然后广播文件上传出错。
  2989. tr.on( 'error', function( type, flag ) {
  2990. block.retried = block.retried || 0;
  2991. // 自动重试
  2992. if ( block.chunks > 1 && ~'http,abort'.indexOf( type ) &&
  2993. block.retried < opts.chunkRetry ) {
  2994. block.retried++;
  2995. tr.send();
  2996. } else {
  2997. // http status 500 ~ 600
  2998. if ( !flag && type === 'server' ) {
  2999. type = requestAccept( type );
  3000. }
  3001. file.setStatus( Status.ERROR, type );
  3002. owner.trigger( 'uploadError', file, type );
  3003. owner.trigger( 'uploadComplete', file );
  3004. }
  3005. });
  3006. // 上传成功
  3007. tr.on( 'load', function() {
  3008. var reason;
  3009. // 如果非预期,转向上传出错。
  3010. if ( (reason = requestAccept()) ) {
  3011. tr.trigger( 'error', reason, true );
  3012. return;
  3013. }
  3014. // 全部上传完成。
  3015. if ( file.remaning === 1 ) {
  3016. me._finishFile( file, ret );
  3017. } else {
  3018. tr.destroy();
  3019. }
  3020. });
  3021. // 配置默认的上传字段。
  3022. data = $.extend( data, {
  3023. id: file.id,
  3024. name: file.name,
  3025. type: file.type,
  3026. lastModifiedDate: file.lastModifiedDate,
  3027. size: file.size
  3028. });
  3029. block.chunks > 1 && $.extend( data, {
  3030. chunks: block.chunks,
  3031. chunk: block.chunk
  3032. });
  3033. // 在发送之间可以添加字段什么的。。。
  3034. // 如果默认的字段不够使用,可以通过监听此事件来扩展
  3035. owner.trigger( 'uploadBeforeSend', block, data, headers );
  3036. // 开始发送。
  3037. tr.appendBlob( opts.fileVal, block.blob, file.name );
  3038. tr.append( data );
  3039. tr.setRequestHeader( headers );
  3040. tr.send();
  3041. },
  3042. // 完成上传。
  3043. _finishFile: function( file, ret, hds ) {
  3044. var owner = this.owner;
  3045. return owner
  3046. .request( 'after-send-file', arguments, function() {
  3047. file.setStatus( Status.COMPLETE );
  3048. owner.trigger( 'uploadSuccess', file, ret, hds );
  3049. })
  3050. .fail(function( reason ) {
  3051. // 如果外部已经标记为invalid什么的,不再改状态。
  3052. if ( file.getStatus() === Status.PROGRESS ) {
  3053. file.setStatus( Status.ERROR, reason );
  3054. }
  3055. owner.trigger( 'uploadError', file, reason );
  3056. })
  3057. .always(function() {
  3058. owner.trigger( 'uploadComplete', file );
  3059. });
  3060. },
  3061. updateFileProgress: function(file) {
  3062. var totalPercent = 0,
  3063. uploaded = 0;
  3064. if (!file.blocks) {
  3065. return;
  3066. }
  3067. $.each( file.blocks, function( _, v ) {
  3068. uploaded += (v.percentage || 0) * (v.end - v.start);
  3069. });
  3070. totalPercent = uploaded / file.size;
  3071. this.owner.trigger( 'uploadProgress', file, totalPercent || 0 );
  3072. }
  3073. });
  3074. });
  3075. /**
  3076. * @fileOverview 各种验证,包括文件总大小是否超出、单文件是否超出和文件是否重复。
  3077. */
  3078. define('widgets/validator',[
  3079. 'base',
  3080. 'uploader',
  3081. 'file',
  3082. 'widgets/widget'
  3083. ], function( Base, Uploader, WUFile ) {
  3084. var $ = Base.$,
  3085. validators = {},
  3086. api;
  3087. /**
  3088. * @event error
  3089. * @param {String} type 错误类型。
  3090. * @description 当validate不通过时,会以派送错误事件的形式通知调用者。通过`upload.on('error', handler)`可以捕获到此类错误,目前有以下错误会在特定的情况下派送错来。
  3091. *
  3092. * * `Q_EXCEED_NUM_LIMIT` 在设置了`fileNumLimit`且尝试给`uploader`添加的文件数量超出这个值时派送。
  3093. * * `Q_EXCEED_SIZE_LIMIT` 在设置了`Q_EXCEED_SIZE_LIMIT`且尝试给`uploader`添加的文件总大小超出这个值时派送。
  3094. * * `Q_TYPE_DENIED` 当文件类型不满足时触发。。
  3095. * @for Uploader
  3096. */
  3097. // 暴露给外面的api
  3098. api = {
  3099. // 添加验证器
  3100. addValidator: function( type, cb ) {
  3101. validators[ type ] = cb;
  3102. },
  3103. // 移除验证器
  3104. removeValidator: function( type ) {
  3105. delete validators[ type ];
  3106. }
  3107. };
  3108. // 在Uploader初始化的时候启动Validators的初始化
  3109. Uploader.register({
  3110. name: 'validator',
  3111. init: function() {
  3112. var me = this;
  3113. Base.nextTick(function() {
  3114. $.each( validators, function() {
  3115. this.call( me.owner );
  3116. });
  3117. });
  3118. }
  3119. });
  3120. /**
  3121. * @property {int} [fileNumLimit=undefined]
  3122. * @namespace options
  3123. * @for Uploader
  3124. * @description 验证文件总数量, 超出则不允许加入队列。
  3125. */
  3126. api.addValidator( 'fileNumLimit', function() {
  3127. var uploader = this,
  3128. opts = uploader.options,
  3129. count = 0,
  3130. max = parseInt( opts.fileNumLimit, 10 ),
  3131. flag = true;
  3132. if ( !max ) {
  3133. return;
  3134. }
  3135. uploader.on( 'beforeFileQueued', function( file ) {
  3136. if ( count >= max && flag ) {
  3137. flag = false;
  3138. this.trigger( 'error', 'Q_EXCEED_NUM_LIMIT', max, file );
  3139. setTimeout(function() {
  3140. flag = true;
  3141. }, 1 );
  3142. }
  3143. return count >= max ? false : true;
  3144. });
  3145. uploader.on( 'fileQueued', function() {
  3146. count++;
  3147. });
  3148. uploader.on( 'fileDequeued', function() {
  3149. count--;
  3150. });
  3151. uploader.on( 'reset', function() {
  3152. count = 0;
  3153. });
  3154. });
  3155. /**
  3156. * @property {int} [fileSizeLimit=undefined]
  3157. * @namespace options
  3158. * @for Uploader
  3159. * @description 验证文件总大小是否超出限制, 超出则不允许加入队列。
  3160. */
  3161. api.addValidator( 'fileSizeLimit', function() {
  3162. var uploader = this,
  3163. opts = uploader.options,
  3164. count = 0,
  3165. max = parseInt( opts.fileSizeLimit, 10 ),
  3166. flag = true;
  3167. if ( !max ) {
  3168. return;
  3169. }
  3170. uploader.on( 'beforeFileQueued', function( file ) {
  3171. var invalid = count + file.size > max;
  3172. if ( invalid && flag ) {
  3173. flag = false;
  3174. this.trigger( 'error', 'Q_EXCEED_SIZE_LIMIT', max, file );
  3175. setTimeout(function() {
  3176. flag = true;
  3177. }, 1 );
  3178. }
  3179. return invalid ? false : true;
  3180. });
  3181. uploader.on( 'fileQueued', function( file ) {
  3182. count += file.size;
  3183. });
  3184. uploader.on( 'fileDequeued', function( file ) {
  3185. count -= file.size;
  3186. });
  3187. uploader.on( 'reset', function() {
  3188. count = 0;
  3189. });
  3190. });
  3191. /**
  3192. * @property {int} [fileSingleSizeLimit=undefined]
  3193. * @namespace options
  3194. * @for Uploader
  3195. * @description 验证单个文件大小是否超出限制, 超出则不允许加入队列。
  3196. */
  3197. api.addValidator( 'fileSingleSizeLimit', function() {
  3198. var uploader = this,
  3199. opts = uploader.options,
  3200. max = opts.fileSingleSizeLimit;
  3201. if ( !max ) {
  3202. return;
  3203. }
  3204. uploader.on( 'beforeFileQueued', function( file ) {
  3205. if ( file.size > max ) {
  3206. file.setStatus( WUFile.Status.INVALID, 'exceed_size' );
  3207. this.trigger( 'error', 'F_EXCEED_SIZE', max, file );
  3208. return false;
  3209. }
  3210. });
  3211. });
  3212. /**
  3213. * @property {Boolean} [duplicate=undefined]
  3214. * @namespace options
  3215. * @for Uploader
  3216. * @description 去重, 根据文件名字、文件大小和最后修改时间来生成hash Key.
  3217. */
  3218. api.addValidator( 'duplicate', function() {
  3219. var uploader = this,
  3220. opts = uploader.options,
  3221. mapping = {};
  3222. if ( opts.duplicate ) {
  3223. return;
  3224. }
  3225. function hashString( str ) {
  3226. var hash = 0,
  3227. i = 0,
  3228. len = str.length,
  3229. _char;
  3230. for ( ; i < len; i++ ) {
  3231. _char = str.charCodeAt( i );
  3232. hash = _char + (hash << 6) + (hash << 16) - hash;
  3233. }
  3234. return hash;
  3235. }
  3236. uploader.on( 'beforeFileQueued', function( file ) {
  3237. var hash = file.__hash || (file.__hash = hashString( file.name +
  3238. file.size + file.lastModifiedDate ));
  3239. // 已经重复了
  3240. if ( mapping[ hash ] ) {
  3241. this.trigger( 'error', 'F_DUPLICATE', file );
  3242. return false;
  3243. }
  3244. });
  3245. uploader.on( 'fileQueued', function( file ) {
  3246. var hash = file.__hash;
  3247. hash && (mapping[ hash ] = true);
  3248. });
  3249. uploader.on( 'fileDequeued', function( file ) {
  3250. var hash = file.__hash;
  3251. hash && (delete mapping[ hash ]);
  3252. });
  3253. uploader.on( 'reset', function() {
  3254. mapping = {};
  3255. });
  3256. });
  3257. return api;
  3258. });
  3259. /**
  3260. * @fileOverview Runtime管理器,负责Runtime的选择, 连接
  3261. */
  3262. define('runtime/compbase',[],function() {
  3263. function CompBase( owner, runtime ) {
  3264. this.owner = owner;
  3265. this.options = owner.options;
  3266. this.getRuntime = function() {
  3267. return runtime;
  3268. };
  3269. this.getRuid = function() {
  3270. return runtime.uid;
  3271. };
  3272. this.trigger = function() {
  3273. return owner.trigger.apply( owner, arguments );
  3274. };
  3275. }
  3276. return CompBase;
  3277. });
  3278. /**
  3279. * @fileOverview Html5Runtime
  3280. */
  3281. define('runtime/html5/runtime',[
  3282. 'base',
  3283. 'runtime/runtime',
  3284. 'runtime/compbase'
  3285. ], function( Base, Runtime, CompBase ) {
  3286. var type = 'html5',
  3287. components = {};
  3288. function Html5Runtime() {
  3289. var pool = {},
  3290. me = this,
  3291. destroy = this.destroy;
  3292. Runtime.apply( me, arguments );
  3293. me.type = type;
  3294. // 这个方法的调用者,实际上是RuntimeClient
  3295. me.exec = function( comp, fn/*, args...*/) {
  3296. var client = this,
  3297. uid = client.uid,
  3298. args = Base.slice( arguments, 2 ),
  3299. instance;
  3300. if ( components[ comp ] ) {
  3301. instance = pool[ uid ] = pool[ uid ] ||
  3302. new components[ comp ]( client, me );
  3303. if ( instance[ fn ] ) {
  3304. return instance[ fn ].apply( instance, args );
  3305. }
  3306. }
  3307. };
  3308. me.destroy = function() {
  3309. // @todo 删除池子中的所有实例
  3310. return destroy && destroy.apply( this, arguments );
  3311. };
  3312. }
  3313. Base.inherits( Runtime, {
  3314. constructor: Html5Runtime,
  3315. // 不需要连接其他程序,直接执行callback
  3316. init: function() {
  3317. var me = this;
  3318. setTimeout(function() {
  3319. me.trigger('ready');
  3320. }, 1 );
  3321. }
  3322. });
  3323. // 注册Components
  3324. Html5Runtime.register = function( name, component ) {
  3325. var klass = components[ name ] = Base.inherits( CompBase, component );
  3326. return klass;
  3327. };
  3328. // 注册html5运行时。
  3329. // 只有在支持的前提下注册。
  3330. if ( window.Blob && window.FileReader && window.DataView ) {
  3331. Runtime.addRuntime( type, Html5Runtime );
  3332. }
  3333. return Html5Runtime;
  3334. });
  3335. /**
  3336. * @fileOverview Blob Html实现
  3337. */
  3338. define('runtime/html5/blob',[
  3339. 'runtime/html5/runtime',
  3340. 'lib/blob'
  3341. ], function( Html5Runtime, Blob ) {
  3342. return Html5Runtime.register( 'Blob', {
  3343. slice: function( start, end ) {
  3344. var blob = this.owner.source,
  3345. slice = blob.slice || blob.webkitSlice || blob.mozSlice;
  3346. blob = slice.call( blob, start, end );
  3347. return new Blob( this.getRuid(), blob );
  3348. }
  3349. });
  3350. });
  3351. /**
  3352. * @fileOverview FilePaste
  3353. */
  3354. define('runtime/html5/dnd',[
  3355. 'base',
  3356. 'runtime/html5/runtime',
  3357. 'lib/file'
  3358. ], function( Base, Html5Runtime, File ) {
  3359. var $ = Base.$,
  3360. prefix = 'webuploader-dnd-';
  3361. return Html5Runtime.register( 'DragAndDrop', {
  3362. init: function() {
  3363. var elem = this.elem = this.options.container;
  3364. this.dragEnterHandler = Base.bindFn( this._dragEnterHandler, this );
  3365. this.dragOverHandler = Base.bindFn( this._dragOverHandler, this );
  3366. this.dragLeaveHandler = Base.bindFn( this._dragLeaveHandler, this );
  3367. this.dropHandler = Base.bindFn( this._dropHandler, this );
  3368. this.dndOver = false;
  3369. elem.on( 'dragenter', this.dragEnterHandler );
  3370. elem.on( 'dragover', this.dragOverHandler );
  3371. elem.on( 'dragleave', this.dragLeaveHandler );
  3372. elem.on( 'drop', this.dropHandler );
  3373. if ( this.options.disableGlobalDnd ) {
  3374. $( document ).on( 'dragover', this.dragOverHandler );
  3375. $( document ).on( 'drop', this.dropHandler );
  3376. }
  3377. },
  3378. _dragEnterHandler: function( e ) {
  3379. var me = this,
  3380. denied = me._denied || false,
  3381. items;
  3382. e = e.originalEvent || e;
  3383. if ( !me.dndOver ) {
  3384. me.dndOver = true;
  3385. // 注意只有 chrome 支持。
  3386. items = e.dataTransfer.items;
  3387. if ( items && items.length ) {
  3388. me._denied = denied = !me.trigger( 'accept', items );
  3389. }
  3390. me.elem.addClass( prefix + 'over' );
  3391. me.elem[ denied ? 'addClass' :
  3392. 'removeClass' ]( prefix + 'denied' );
  3393. }
  3394. e.dataTransfer.dropEffect = denied ? 'none' : 'copy';
  3395. return false;
  3396. },
  3397. _dragOverHandler: function( e ) {
  3398. // 只处理框内的。
  3399. var parentElem = this.elem.parent().get( 0 );
  3400. if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) {
  3401. return false;
  3402. }
  3403. clearTimeout( this._leaveTimer );
  3404. this._dragEnterHandler.call( this, e );
  3405. return false;
  3406. },
  3407. _dragLeaveHandler: function() {
  3408. var me = this,
  3409. handler;
  3410. handler = function() {
  3411. me.dndOver = false;
  3412. me.elem.removeClass( prefix + 'over ' + prefix + 'denied' );
  3413. };
  3414. clearTimeout( me._leaveTimer );
  3415. me._leaveTimer = setTimeout( handler, 100 );
  3416. return false;
  3417. },
  3418. _dropHandler: function( e ) {
  3419. var me = this,
  3420. ruid = me.getRuid(),
  3421. parentElem = me.elem.parent().get( 0 ),
  3422. dataTransfer, data;
  3423. // 只处理框内的。
  3424. if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) {
  3425. return false;
  3426. }
  3427. e = e.originalEvent || e;
  3428. dataTransfer = e.dataTransfer;
  3429. // 如果是页面内拖拽,还不能处理,不阻止事件。
  3430. // 此处 ie11 下会报参数错误,
  3431. try {
  3432. data = dataTransfer.getData('text/html');
  3433. } catch( err ) {
  3434. }
  3435. if ( data ) {
  3436. return;
  3437. }
  3438. me._getTansferFiles( dataTransfer, function( results ) {
  3439. me.trigger( 'drop', $.map( results, function( file ) {
  3440. return new File( ruid, file );
  3441. }) );
  3442. });
  3443. me.dndOver = false;
  3444. me.elem.removeClass( prefix + 'over' );
  3445. return false;
  3446. },
  3447. // 如果传入 callback 则去查看文件夹,否则只管当前文件夹。
  3448. _getTansferFiles: function( dataTransfer, callback ) {
  3449. var results = [],
  3450. promises = [],
  3451. items, files, file, item, i, len, canAccessFolder;
  3452. items = dataTransfer.items;
  3453. files = dataTransfer.files;
  3454. canAccessFolder = !!(items && items[ 0 ].webkitGetAsEntry);
  3455. for ( i = 0, len = files.length; i < len; i++ ) {
  3456. file = files[ i ];
  3457. item = items && items[ i ];
  3458. if ( canAccessFolder && item.webkitGetAsEntry().isDirectory ) {
  3459. promises.push( this._traverseDirectoryTree(
  3460. item.webkitGetAsEntry(), results ) );
  3461. } else {
  3462. results.push( file );
  3463. }
  3464. }
  3465. Base.when.apply( Base, promises ).done(function() {
  3466. if ( !results.length ) {
  3467. return;
  3468. }
  3469. callback( results );
  3470. });
  3471. },
  3472. _traverseDirectoryTree: function( entry, results ) {
  3473. var deferred = Base.Deferred(),
  3474. me = this;
  3475. if ( entry.isFile ) {
  3476. entry.file(function( file ) {
  3477. results.push( file );
  3478. deferred.resolve();
  3479. });
  3480. } else if ( entry.isDirectory ) {
  3481. entry.createReader().readEntries(function( entries ) {
  3482. var len = entries.length,
  3483. promises = [],
  3484. arr = [], // 为了保证顺序。
  3485. i;
  3486. for ( i = 0; i < len; i++ ) {
  3487. promises.push( me._traverseDirectoryTree(
  3488. entries[ i ], arr ) );
  3489. }
  3490. Base.when.apply( Base, promises ).then(function() {
  3491. results.push.apply( results, arr );
  3492. deferred.resolve();
  3493. }, deferred.reject );
  3494. });
  3495. }
  3496. return deferred.promise();
  3497. },
  3498. destroy: function() {
  3499. var elem = this.elem;
  3500. // 还没 init 就调用 destroy
  3501. if (!elem) {
  3502. return;
  3503. }
  3504. elem.off( 'dragenter', this.dragEnterHandler );
  3505. elem.off( 'dragover', this.dragOverHandler );
  3506. elem.off( 'dragleave', this.dragLeaveHandler );
  3507. elem.off( 'drop', this.dropHandler );
  3508. if ( this.options.disableGlobalDnd ) {
  3509. $( document ).off( 'dragover', this.dragOverHandler );
  3510. $( document ).off( 'drop', this.dropHandler );
  3511. }
  3512. }
  3513. });
  3514. });
  3515. /**
  3516. * @fileOverview FilePaste
  3517. */
  3518. define('runtime/html5/filepaste',[
  3519. 'base',
  3520. 'runtime/html5/runtime',
  3521. 'lib/file'
  3522. ], function( Base, Html5Runtime, File ) {
  3523. return Html5Runtime.register( 'FilePaste', {
  3524. init: function() {
  3525. var opts = this.options,
  3526. elem = this.elem = opts.container,
  3527. accept = '.*',
  3528. arr, i, len, item;
  3529. // accetp的mimeTypes中生成匹配正则。
  3530. if ( opts.accept ) {
  3531. arr = [];
  3532. for ( i = 0, len = opts.accept.length; i < len; i++ ) {
  3533. item = opts.accept[ i ].mimeTypes;
  3534. item && arr.push( item );
  3535. }
  3536. if ( arr.length ) {
  3537. accept = arr.join(',');
  3538. accept = accept.replace( /,/g, '|' ).replace( /\*/g, '.*' );
  3539. }
  3540. }
  3541. this.accept = accept = new RegExp( accept, 'i' );
  3542. this.hander = Base.bindFn( this._pasteHander, this );
  3543. elem.on( 'paste', this.hander );
  3544. },
  3545. _pasteHander: function( e ) {
  3546. var allowed = [],
  3547. ruid = this.getRuid(),
  3548. items, item, blob, i, len;
  3549. e = e.originalEvent || e;
  3550. items = e.clipboardData.items;
  3551. for ( i = 0, len = items.length; i < len; i++ ) {
  3552. item = items[ i ];
  3553. if ( item.kind !== 'file' || !(blob = item.getAsFile()) ) {
  3554. continue;
  3555. }
  3556. allowed.push( new File( ruid, blob ) );
  3557. }
  3558. if ( allowed.length ) {
  3559. // 不阻止非文件粘贴(文字粘贴)的事件冒泡
  3560. e.preventDefault();
  3561. e.stopPropagation();
  3562. this.trigger( 'paste', allowed );
  3563. }
  3564. },
  3565. destroy: function() {
  3566. this.elem.off( 'paste', this.hander );
  3567. }
  3568. });
  3569. });
  3570. /**
  3571. * @fileOverview FilePicker
  3572. */
  3573. define('runtime/html5/filepicker',[
  3574. 'base',
  3575. 'runtime/html5/runtime'
  3576. ], function( Base, Html5Runtime ) {
  3577. var $ = Base.$;
  3578. return Html5Runtime.register( 'FilePicker', {
  3579. init: function() {
  3580. var container = this.getRuntime().getContainer(),
  3581. me = this,
  3582. owner = me.owner,
  3583. opts = me.options,
  3584. label = this.label = $( document.createElement('label') ),
  3585. input = this.input = $( document.createElement('input') ),
  3586. arr, i, len, mouseHandler;
  3587. input.attr( 'type', 'file' );
  3588. input.attr( 'name', opts.name );
  3589. input.addClass('webuploader-element-invisible');
  3590. label.on( 'click', function() {
  3591. input.trigger('click');
  3592. });
  3593. label.css({
  3594. opacity: 0,
  3595. width: '100%',
  3596. height: '100%',
  3597. display: 'block',
  3598. cursor: 'pointer',
  3599. background: '#ffffff'
  3600. });
  3601. if ( opts.multiple ) {
  3602. input.attr( 'multiple', 'multiple' );
  3603. }
  3604. // @todo Firefox不支持单独指定后缀
  3605. if ( opts.accept && opts.accept.length > 0 ) {
  3606. arr = [];
  3607. for ( i = 0, len = opts.accept.length; i < len; i++ ) {
  3608. arr.push( opts.accept[ i ].mimeTypes );
  3609. }
  3610. input.attr( 'accept', arr.join(',') );
  3611. }
  3612. container.append( input );
  3613. container.append( label );
  3614. mouseHandler = function( e ) {
  3615. owner.trigger( e.type );
  3616. };
  3617. input.on( 'change', function( e ) {
  3618. var fn = arguments.callee,
  3619. clone;
  3620. me.files = e.target.files;
  3621. // reset input
  3622. clone = this.cloneNode( true );
  3623. clone.value = null;
  3624. this.parentNode.replaceChild( clone, this );
  3625. input.off();
  3626. input = $( clone ).on( 'change', fn )
  3627. .on( 'mouseenter mouseleave', mouseHandler );
  3628. owner.trigger('change');
  3629. });
  3630. label.on( 'mouseenter mouseleave', mouseHandler );
  3631. },
  3632. getFiles: function() {
  3633. return this.files;
  3634. },
  3635. destroy: function() {
  3636. this.input.off();
  3637. this.label.off();
  3638. }
  3639. });
  3640. });
  3641. /**
  3642. * @fileOverview Transport
  3643. * @todo 支持chunked传输,优势:
  3644. * 可以将大文件分成小块,挨个传输,可以提高大文件成功率,当失败的时候,也只需要重传那小部分,
  3645. * 而不需要重头再传一次。另外断点续传也需要用chunked方式。
  3646. */
  3647. define('runtime/html5/transport',[
  3648. 'base',
  3649. 'runtime/html5/runtime'
  3650. ], function( Base, Html5Runtime ) {
  3651. var noop = Base.noop,
  3652. $ = Base.$;
  3653. return Html5Runtime.register( 'Transport', {
  3654. init: function() {
  3655. this._status = 0;
  3656. this._response = null;
  3657. },
  3658. send: function() {
  3659. var owner = this.owner,
  3660. opts = this.options,
  3661. xhr = this._initAjax(),
  3662. blob = owner._blob,
  3663. server = opts.server,
  3664. formData, binary, fr;
  3665. if ( opts.sendAsBinary ) {
  3666. server += (/\?/.test( server ) ? '&' : '?') +
  3667. $.param( owner._formData );
  3668. binary = blob.getSource();
  3669. } else {
  3670. formData = new FormData();
  3671. $.each( owner._formData, function( k, v ) {
  3672. formData.append( k, v );
  3673. });
  3674. formData.append( opts.fileVal, blob.getSource(),
  3675. opts.filename || owner._formData.name || '' );
  3676. }
  3677. if ( opts.withCredentials && 'withCredentials' in xhr ) {
  3678. xhr.open( opts.method, server, true );
  3679. xhr.withCredentials = true;
  3680. } else {
  3681. xhr.open( opts.method, server );
  3682. }
  3683. this._setRequestHeader( xhr, opts.headers );
  3684. if ( binary ) {
  3685. // 强制设置成 content-type 为文件流。
  3686. xhr.overrideMimeType &&
  3687. xhr.overrideMimeType('application/octet-stream');
  3688. // android直接发送blob会导致服务端接收到的是空文件。
  3689. // bug详情。
  3690. // https://code.google.com/p/android/issues/detail?id=39882
  3691. // 所以先用fileReader读取出来再通过arraybuffer的方式发送。
  3692. if ( Base.os.android ) {
  3693. fr = new FileReader();
  3694. fr.onload = function() {
  3695. xhr.send( this.result );
  3696. fr = fr.onload = null;
  3697. };
  3698. fr.readAsArrayBuffer( binary );
  3699. } else {
  3700. xhr.send( binary );
  3701. }
  3702. } else {
  3703. xhr.send( formData );
  3704. }
  3705. },
  3706. getResponse: function() {
  3707. return this._response;
  3708. },
  3709. getResponseAsJson: function() {
  3710. return this._parseJson( this._response );
  3711. },
  3712. getStatus: function() {
  3713. return this._status;
  3714. },
  3715. abort: function() {
  3716. var xhr = this._xhr;
  3717. if ( xhr ) {
  3718. xhr.upload.onprogress = noop;
  3719. xhr.onreadystatechange = noop;
  3720. xhr.abort();
  3721. this._xhr = xhr = null;
  3722. }
  3723. },
  3724. destroy: function() {
  3725. this.abort();
  3726. },
  3727. _initAjax: function() {
  3728. var me = this,
  3729. xhr = new XMLHttpRequest(),
  3730. opts = this.options;
  3731. if ( opts.withCredentials && !('withCredentials' in xhr) &&
  3732. typeof XDomainRequest !== 'undefined' ) {
  3733. xhr = new XDomainRequest();
  3734. }
  3735. xhr.upload.onprogress = function( e ) {
  3736. var percentage = 0;
  3737. if ( e.lengthComputable ) {
  3738. percentage = e.loaded / e.total;
  3739. }
  3740. return me.trigger( 'progress', percentage );
  3741. };
  3742. xhr.onreadystatechange = function() {
  3743. if ( xhr.readyState !== 4 ) {
  3744. return;
  3745. }
  3746. xhr.upload.onprogress = noop;
  3747. xhr.onreadystatechange = noop;
  3748. me._xhr = null;
  3749. me._status = xhr.status;
  3750. if ( xhr.status >= 200 && xhr.status < 300 ) {
  3751. me._response = xhr.responseText;
  3752. return me.trigger('load');
  3753. } else if ( xhr.status >= 500 && xhr.status < 600 ) {
  3754. me._response = xhr.responseText;
  3755. return me.trigger( 'error', 'server' );
  3756. }
  3757. return me.trigger( 'error', me._status ? 'http' : 'abort' );
  3758. };
  3759. me._xhr = xhr;
  3760. return xhr;
  3761. },
  3762. _setRequestHeader: function( xhr, headers ) {
  3763. $.each( headers, function( key, val ) {
  3764. xhr.setRequestHeader( key, val );
  3765. });
  3766. },
  3767. _parseJson: function( str ) {
  3768. var json;
  3769. try {
  3770. json = JSON.parse( str );
  3771. } catch ( ex ) {
  3772. json = {};
  3773. }
  3774. return json;
  3775. }
  3776. });
  3777. });
  3778. /**
  3779. * @fileOverview FlashRuntime
  3780. */
  3781. define('runtime/flash/runtime',[
  3782. 'base',
  3783. 'runtime/runtime',
  3784. 'runtime/compbase'
  3785. ], function( Base, Runtime, CompBase ) {
  3786. var $ = Base.$,
  3787. type = 'flash',
  3788. components = {};
  3789. function getFlashVersion() {
  3790. var version;
  3791. try {
  3792. version = navigator.plugins[ 'Shockwave Flash' ];
  3793. version = version.description;
  3794. } catch ( ex ) {
  3795. try {
  3796. version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash')
  3797. .GetVariable('$version');
  3798. } catch ( ex2 ) {
  3799. version = '0.0';
  3800. }
  3801. }
  3802. version = version.match( /\d+/g );
  3803. return parseFloat( version[ 0 ] + '.' + version[ 1 ], 10 );
  3804. }
  3805. function FlashRuntime() {
  3806. var pool = {},
  3807. clients = {},
  3808. destroy = this.destroy,
  3809. me = this,
  3810. jsreciver = Base.guid('webuploader_');
  3811. Runtime.apply( me, arguments );
  3812. me.type = type;
  3813. // 这个方法的调用者,实际上是RuntimeClient
  3814. me.exec = function( comp, fn/*, args...*/ ) {
  3815. var client = this,
  3816. uid = client.uid,
  3817. args = Base.slice( arguments, 2 ),
  3818. instance;
  3819. clients[ uid ] = client;
  3820. if ( components[ comp ] ) {
  3821. if ( !pool[ uid ] ) {
  3822. pool[ uid ] = new components[ comp ]( client, me );
  3823. }
  3824. instance = pool[ uid ];
  3825. if ( instance[ fn ] ) {
  3826. return instance[ fn ].apply( instance, args );
  3827. }
  3828. }
  3829. return me.flashExec.apply( client, arguments );
  3830. };
  3831. function handler( evt, obj ) {
  3832. var type = evt.type || evt,
  3833. parts, uid;
  3834. parts = type.split('::');
  3835. uid = parts[ 0 ];
  3836. type = parts[ 1 ];
  3837. // console.log.apply( console, arguments );
  3838. if ( type === 'Ready' && uid === me.uid ) {
  3839. me.trigger('ready');
  3840. } else if ( clients[ uid ] ) {
  3841. clients[ uid ].trigger( type.toLowerCase(), evt, obj );
  3842. }
  3843. // Base.log( evt, obj );
  3844. }
  3845. // flash的接受器。
  3846. window[ jsreciver ] = function() {
  3847. var args = arguments;
  3848. // 为了能捕获得到。
  3849. setTimeout(function() {
  3850. handler.apply( null, args );
  3851. }, 1 );
  3852. };
  3853. this.jsreciver = jsreciver;
  3854. this.destroy = function() {
  3855. // @todo 删除池子中的所有实例
  3856. return destroy && destroy.apply( this, arguments );
  3857. };
  3858. this.flashExec = function( comp, fn ) {
  3859. var flash = me.getFlash(),
  3860. args = Base.slice( arguments, 2 );
  3861. return flash.exec( this.uid, comp, fn, args );
  3862. };
  3863. // @todo
  3864. }
  3865. Base.inherits( Runtime, {
  3866. constructor: FlashRuntime,
  3867. init: function() {
  3868. var container = this.getContainer(),
  3869. opts = this.options,
  3870. html;
  3871. // if not the minimal height, shims are not initialized
  3872. // in older browsers (e.g FF3.6, IE6,7,8, Safari 4.0,5.0, etc)
  3873. container.css({
  3874. position: 'absolute',
  3875. top: '-8px',
  3876. left: '-8px',
  3877. width: '9px',
  3878. height: '9px',
  3879. overflow: 'hidden'
  3880. });
  3881. // insert flash object
  3882. html = '<object id="' + this.uid + '" type="application/' +
  3883. 'x-shockwave-flash" data="' + opts.swf + '" ';
  3884. if ( Base.browser.ie ) {
  3885. html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
  3886. }
  3887. html += 'width="100%" height="100%" style="outline:0">' +
  3888. '<param name="movie" value="' + opts.swf + '" />' +
  3889. '<param name="flashvars" value="uid=' + this.uid +
  3890. '&jsreciver=' + this.jsreciver + '" />' +
  3891. '<param name="wmode" value="transparent" />' +
  3892. '<param name="allowscriptaccess" value="always" />' +
  3893. '</object>';
  3894. container.html( html );
  3895. },
  3896. getFlash: function() {
  3897. if ( this._flash ) {
  3898. return this._flash;
  3899. }
  3900. this._flash = $( '#' + this.uid ).get( 0 );
  3901. return this._flash;
  3902. }
  3903. });
  3904. FlashRuntime.register = function( name, component ) {
  3905. component = components[ name ] = Base.inherits( CompBase, $.extend({
  3906. // @todo fix this later
  3907. flashExec: function() {
  3908. var owner = this.owner,
  3909. runtime = this.getRuntime();
  3910. return runtime.flashExec.apply( owner, arguments );
  3911. }
  3912. }, component ) );
  3913. return component;
  3914. };
  3915. if ( getFlashVersion() >= 11.4 ) {
  3916. Runtime.addRuntime( type, FlashRuntime );
  3917. }
  3918. return FlashRuntime;
  3919. });
  3920. /**
  3921. * @fileOverview FilePicker
  3922. */
  3923. define('runtime/flash/filepicker',[
  3924. 'base',
  3925. 'runtime/flash/runtime'
  3926. ], function( Base, FlashRuntime ) {
  3927. var $ = Base.$;
  3928. return FlashRuntime.register( 'FilePicker', {
  3929. init: function( opts ) {
  3930. var copy = $.extend({}, opts ),
  3931. len, i;
  3932. // 修复Flash再没有设置title的情况下无法弹出flash文件选择框的bug.
  3933. len = copy.accept && copy.accept.length;
  3934. for ( i = 0; i < len; i++ ) {
  3935. if ( !copy.accept[ i ].title ) {
  3936. copy.accept[ i ].title = 'Files';
  3937. }
  3938. }
  3939. delete copy.button;
  3940. delete copy.id;
  3941. delete copy.container;
  3942. this.flashExec( 'FilePicker', 'init', copy );
  3943. },
  3944. destroy: function() {
  3945. this.flashExec( 'FilePicker', 'destroy' );
  3946. }
  3947. });
  3948. });
  3949. /**
  3950. * @fileOverview Transport flash实现
  3951. */
  3952. define('runtime/flash/transport',[
  3953. 'base',
  3954. 'runtime/flash/runtime',
  3955. 'runtime/client'
  3956. ], function( Base, FlashRuntime, RuntimeClient ) {
  3957. var $ = Base.$;
  3958. return FlashRuntime.register( 'Transport', {
  3959. init: function() {
  3960. this._status = 0;
  3961. this._response = null;
  3962. this._responseJson = null;
  3963. },
  3964. send: function() {
  3965. var owner = this.owner,
  3966. opts = this.options,
  3967. xhr = this._initAjax(),
  3968. blob = owner._blob,
  3969. server = opts.server,
  3970. binary;
  3971. xhr.connectRuntime( blob.ruid );
  3972. if ( opts.sendAsBinary ) {
  3973. server += (/\?/.test( server ) ? '&' : '?') +
  3974. $.param( owner._formData );
  3975. binary = blob.uid;
  3976. } else {
  3977. $.each( owner._formData, function( k, v ) {
  3978. xhr.exec( 'append', k, v );
  3979. });
  3980. xhr.exec( 'appendBlob', opts.fileVal, blob.uid,
  3981. opts.filename || owner._formData.name || '' );
  3982. }
  3983. this._setRequestHeader( xhr, opts.headers );
  3984. xhr.exec( 'send', {
  3985. method: opts.method,
  3986. url: server,
  3987. forceURLStream: opts.forceURLStream,
  3988. mimeType: 'application/octet-stream'
  3989. }, binary );
  3990. },
  3991. getStatus: function() {
  3992. return this._status;
  3993. },
  3994. getResponse: function() {
  3995. return this._response || '';
  3996. },
  3997. getResponseAsJson: function() {
  3998. return this._responseJson;
  3999. },
  4000. abort: function() {
  4001. var xhr = this._xhr;
  4002. if ( xhr ) {
  4003. xhr.exec('abort');
  4004. xhr.destroy();
  4005. this._xhr = xhr = null;
  4006. }
  4007. },
  4008. destroy: function() {
  4009. this.abort();
  4010. },
  4011. _initAjax: function() {
  4012. var me = this,
  4013. xhr = new RuntimeClient('XMLHttpRequest');
  4014. xhr.on( 'uploadprogress progress', function( e ) {
  4015. var percent = e.loaded / e.total;
  4016. percent = Math.min( 1, Math.max( 0, percent ) );
  4017. return me.trigger( 'progress', percent );
  4018. });
  4019. xhr.on( 'load', function() {
  4020. var status = xhr.exec('getStatus'),
  4021. readBody = false,
  4022. err = '',
  4023. p;
  4024. xhr.off();
  4025. me._xhr = null;
  4026. if ( status >= 200 && status < 300 ) {
  4027. readBody = true;
  4028. } else if ( status >= 500 && status < 600 ) {
  4029. readBody = true;
  4030. err = 'server';
  4031. } else {
  4032. err = 'http';
  4033. }
  4034. if ( readBody ) {
  4035. me._response = xhr.exec('getResponse');
  4036. me._response = decodeURIComponent( me._response );
  4037. // flash 处理可能存在 bug, 没辙只能靠 js 了
  4038. // try {
  4039. // me._responseJson = xhr.exec('getResponseAsJson');
  4040. // } catch ( error ) {
  4041. p = window.JSON && window.JSON.parse || function( s ) {
  4042. try {
  4043. return new Function('return ' + s).call();
  4044. } catch ( err ) {
  4045. return {};
  4046. }
  4047. };
  4048. me._responseJson = me._response ? p(me._response) : {};
  4049. // }
  4050. }
  4051. xhr.destroy();
  4052. xhr = null;
  4053. return err ? me.trigger( 'error', err ) : me.trigger('load');
  4054. });
  4055. xhr.on( 'error', function() {
  4056. xhr.off();
  4057. me._xhr = null;
  4058. me.trigger( 'error', 'http' );
  4059. });
  4060. me._xhr = xhr;
  4061. return xhr;
  4062. },
  4063. _setRequestHeader: function( xhr, headers ) {
  4064. $.each( headers, function( key, val ) {
  4065. xhr.exec( 'setRequestHeader', key, val );
  4066. });
  4067. }
  4068. });
  4069. });
  4070. /**
  4071. * @fileOverview Blob Html实现
  4072. */
  4073. define('runtime/flash/blob',[
  4074. 'runtime/flash/runtime',
  4075. 'lib/blob'
  4076. ], function( FlashRuntime, Blob ) {
  4077. return FlashRuntime.register( 'Blob', {
  4078. slice: function( start, end ) {
  4079. var blob = this.flashExec( 'Blob', 'slice', start, end );
  4080. return new Blob( blob.uid, blob );
  4081. }
  4082. });
  4083. });
  4084. /**
  4085. * @fileOverview 没有图像处理的版本。
  4086. */
  4087. define('preset/withoutimage',[
  4088. 'base',
  4089. // widgets
  4090. 'widgets/filednd',
  4091. 'widgets/filepaste',
  4092. 'widgets/filepicker',
  4093. 'widgets/queue',
  4094. 'widgets/runtime',
  4095. 'widgets/upload',
  4096. 'widgets/validator',
  4097. // runtimes
  4098. // html5
  4099. 'runtime/html5/blob',
  4100. 'runtime/html5/dnd',
  4101. 'runtime/html5/filepaste',
  4102. 'runtime/html5/filepicker',
  4103. 'runtime/html5/transport',
  4104. // flash
  4105. 'runtime/flash/filepicker',
  4106. 'runtime/flash/transport',
  4107. 'runtime/flash/blob'
  4108. ], function( Base ) {
  4109. return Base;
  4110. });
  4111. define('webuploader',[
  4112. 'preset/withoutimage'
  4113. ], function( preset ) {
  4114. return preset;
  4115. });
  4116. return require('webuploader');
  4117. });