webuploader.flashonly.js 152 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623
  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 Blob
  973. */
  974. define('lib/blob',[
  975. 'base',
  976. 'runtime/client'
  977. ], function( Base, RuntimeClient ) {
  978. function Blob( ruid, source ) {
  979. var me = this;
  980. me.source = source;
  981. me.ruid = ruid;
  982. this.size = source.size || 0;
  983. // 如果没有指定 mimetype, 但是知道文件后缀。
  984. if ( !source.type && this.ext &&
  985. ~'jpg,jpeg,png,gif,bmp'.indexOf( this.ext ) ) {
  986. this.type = 'image/' + (this.ext === 'jpg' ? 'jpeg' : this.ext);
  987. } else {
  988. this.type = source.type || 'application/octet-stream';
  989. }
  990. RuntimeClient.call( me, 'Blob' );
  991. this.uid = source.uid || this.uid;
  992. if ( ruid ) {
  993. me.connectRuntime( ruid );
  994. }
  995. }
  996. Base.inherits( RuntimeClient, {
  997. constructor: Blob,
  998. slice: function( start, end ) {
  999. return this.exec( 'slice', start, end );
  1000. },
  1001. getSource: function() {
  1002. return this.source;
  1003. }
  1004. });
  1005. return Blob;
  1006. });
  1007. /**
  1008. * 为了统一化Flash的File和HTML5的File而存在。
  1009. * 以至于要调用Flash里面的File,也可以像调用HTML5版本的File一下。
  1010. * @fileOverview File
  1011. */
  1012. define('lib/file',[
  1013. 'base',
  1014. 'lib/blob'
  1015. ], function( Base, Blob ) {
  1016. var uid = 1,
  1017. rExt = /\.([^.]+)$/;
  1018. function File( ruid, file ) {
  1019. var ext;
  1020. this.name = file.name || ('untitled' + uid++);
  1021. ext = rExt.exec( file.name ) ? RegExp.$1.toLowerCase() : '';
  1022. // todo 支持其他类型文件的转换。
  1023. // 如果有 mimetype, 但是文件名里面没有找出后缀规律
  1024. if ( !ext && file.type ) {
  1025. ext = /\/(jpg|jpeg|png|gif|bmp)$/i.exec( file.type ) ?
  1026. RegExp.$1.toLowerCase() : '';
  1027. this.name += '.' + ext;
  1028. }
  1029. this.ext = ext;
  1030. this.lastModifiedDate = file.lastModifiedDate ||
  1031. (new Date()).toLocaleString();
  1032. Blob.apply( this, arguments );
  1033. }
  1034. return Base.inherits( Blob, File );
  1035. });
  1036. /**
  1037. * @fileOverview 错误信息
  1038. */
  1039. define('lib/filepicker',[
  1040. 'base',
  1041. 'runtime/client',
  1042. 'lib/file'
  1043. ], function( Base, RuntimeClent, File ) {
  1044. var $ = Base.$;
  1045. function FilePicker( opts ) {
  1046. opts = this.options = $.extend({}, FilePicker.options, opts );
  1047. opts.container = $( opts.id );
  1048. if ( !opts.container.length ) {
  1049. throw new Error('按钮指定错误');
  1050. }
  1051. opts.innerHTML = opts.innerHTML || opts.label ||
  1052. opts.container.html() || '';
  1053. opts.button = $( opts.button || document.createElement('div') );
  1054. opts.button.html( opts.innerHTML );
  1055. opts.container.html( opts.button );
  1056. RuntimeClent.call( this, 'FilePicker', true );
  1057. }
  1058. FilePicker.options = {
  1059. button: null,
  1060. container: null,
  1061. label: null,
  1062. innerHTML: null,
  1063. multiple: true,
  1064. accept: null,
  1065. name: 'file'
  1066. };
  1067. Base.inherits( RuntimeClent, {
  1068. constructor: FilePicker,
  1069. init: function() {
  1070. var me = this,
  1071. opts = me.options,
  1072. button = opts.button;
  1073. button.addClass('webuploader-pick');
  1074. me.on( 'all', function( type ) {
  1075. var files;
  1076. switch ( type ) {
  1077. case 'mouseenter':
  1078. button.addClass('webuploader-pick-hover');
  1079. break;
  1080. case 'mouseleave':
  1081. button.removeClass('webuploader-pick-hover');
  1082. break;
  1083. case 'change':
  1084. files = me.exec('getFiles');
  1085. me.trigger( 'select', $.map( files, function( file ) {
  1086. file = new File( me.getRuid(), file );
  1087. // 记录来源。
  1088. file._refer = opts.container;
  1089. return file;
  1090. }), opts.container );
  1091. break;
  1092. }
  1093. });
  1094. me.connectRuntime( opts, function() {
  1095. me.refresh();
  1096. me.exec( 'init', opts );
  1097. me.trigger('ready');
  1098. });
  1099. this._resizeHandler = Base.bindFn( this.refresh, this );
  1100. $( window ).on( 'resize', this._resizeHandler );
  1101. },
  1102. refresh: function() {
  1103. var shimContainer = this.getRuntime().getContainer(),
  1104. button = this.options.button,
  1105. width = button.outerWidth ?
  1106. button.outerWidth() : button.width(),
  1107. height = button.outerHeight ?
  1108. button.outerHeight() : button.height(),
  1109. pos = button.offset();
  1110. width && height && shimContainer.css({
  1111. bottom: 'auto',
  1112. right: 'auto',
  1113. width: width + 'px',
  1114. height: height + 'px'
  1115. }).offset( pos );
  1116. },
  1117. enable: function() {
  1118. var btn = this.options.button;
  1119. btn.removeClass('webuploader-pick-disable');
  1120. this.refresh();
  1121. },
  1122. disable: function() {
  1123. var btn = this.options.button;
  1124. this.getRuntime().getContainer().css({
  1125. top: '-99999px'
  1126. });
  1127. btn.addClass('webuploader-pick-disable');
  1128. },
  1129. destroy: function() {
  1130. var btn = this.options.button;
  1131. $( window ).off( 'resize', this._resizeHandler );
  1132. btn.removeClass('webuploader-pick-disable webuploader-pick-hover ' +
  1133. 'webuploader-pick');
  1134. }
  1135. });
  1136. return FilePicker;
  1137. });
  1138. /**
  1139. * @fileOverview 组件基类。
  1140. */
  1141. define('widgets/widget',[
  1142. 'base',
  1143. 'uploader'
  1144. ], function( Base, Uploader ) {
  1145. var $ = Base.$,
  1146. _init = Uploader.prototype._init,
  1147. _destroy = Uploader.prototype.destroy,
  1148. IGNORE = {},
  1149. widgetClass = [];
  1150. function isArrayLike( obj ) {
  1151. if ( !obj ) {
  1152. return false;
  1153. }
  1154. var length = obj.length,
  1155. type = $.type( obj );
  1156. if ( obj.nodeType === 1 && length ) {
  1157. return true;
  1158. }
  1159. return type === 'array' || type !== 'function' && type !== 'string' &&
  1160. (length === 0 || typeof length === 'number' && length > 0 &&
  1161. (length - 1) in obj);
  1162. }
  1163. function Widget( uploader ) {
  1164. this.owner = uploader;
  1165. this.options = uploader.options;
  1166. }
  1167. $.extend( Widget.prototype, {
  1168. init: Base.noop,
  1169. // 类Backbone的事件监听声明,监听uploader实例上的事件
  1170. // widget直接无法监听事件,事件只能通过uploader来传递
  1171. invoke: function( apiName, args ) {
  1172. /*
  1173. {
  1174. 'make-thumb': 'makeThumb'
  1175. }
  1176. */
  1177. var map = this.responseMap;
  1178. // 如果无API响应声明则忽略
  1179. if ( !map || !(apiName in map) || !(map[ apiName ] in this) ||
  1180. !$.isFunction( this[ map[ apiName ] ] ) ) {
  1181. return IGNORE;
  1182. }
  1183. return this[ map[ apiName ] ].apply( this, args );
  1184. },
  1185. /**
  1186. * 发送命令。当传入`callback`或者`handler`中返回`promise`时。返回一个当所有`handler`中的promise都完成后完成的新`promise`。
  1187. * @method request
  1188. * @grammar request( command, args ) => * | Promise
  1189. * @grammar request( command, args, callback ) => Promise
  1190. * @for Uploader
  1191. */
  1192. request: function() {
  1193. return this.owner.request.apply( this.owner, arguments );
  1194. }
  1195. });
  1196. // 扩展Uploader.
  1197. $.extend( Uploader.prototype, {
  1198. /**
  1199. * @property {String | Array} [disableWidgets=undefined]
  1200. * @namespace options
  1201. * @for Uploader
  1202. * @description 默认所有 Uploader.register 了的 widget 都会被加载,如果禁用某一部分,请通过此 option 指定黑名单。
  1203. */
  1204. // 覆写_init用来初始化widgets
  1205. _init: function() {
  1206. var me = this,
  1207. widgets = me._widgets = [],
  1208. deactives = me.options.disableWidgets || '';
  1209. $.each( widgetClass, function( _, klass ) {
  1210. (!deactives || !~deactives.indexOf( klass._name )) &&
  1211. widgets.push( new klass( me ) );
  1212. });
  1213. return _init.apply( me, arguments );
  1214. },
  1215. request: function( apiName, args, callback ) {
  1216. var i = 0,
  1217. widgets = this._widgets,
  1218. len = widgets && widgets.length,
  1219. rlts = [],
  1220. dfds = [],
  1221. widget, rlt, promise, key;
  1222. args = isArrayLike( args ) ? args : [ args ];
  1223. for ( ; i < len; i++ ) {
  1224. widget = widgets[ i ];
  1225. rlt = widget.invoke( apiName, args );
  1226. if ( rlt !== IGNORE ) {
  1227. // Deferred对象
  1228. if ( Base.isPromise( rlt ) ) {
  1229. dfds.push( rlt );
  1230. } else {
  1231. rlts.push( rlt );
  1232. }
  1233. }
  1234. }
  1235. // 如果有callback,则用异步方式。
  1236. if ( callback || dfds.length ) {
  1237. promise = Base.when.apply( Base, dfds );
  1238. key = promise.pipe ? 'pipe' : 'then';
  1239. // 很重要不能删除。删除了会死循环。
  1240. // 保证执行顺序。让callback总是在下一个 tick 中执行。
  1241. return promise[ key ](function() {
  1242. var deferred = Base.Deferred(),
  1243. args = arguments;
  1244. if ( args.length === 1 ) {
  1245. args = args[ 0 ];
  1246. }
  1247. setTimeout(function() {
  1248. deferred.resolve( args );
  1249. }, 1 );
  1250. return deferred.promise();
  1251. })[ callback ? key : 'done' ]( callback || Base.noop );
  1252. } else {
  1253. return rlts[ 0 ];
  1254. }
  1255. },
  1256. destroy: function() {
  1257. _destroy.apply( this, arguments );
  1258. this._widgets = null;
  1259. }
  1260. });
  1261. /**
  1262. * 添加组件
  1263. * @grammar Uploader.register(proto);
  1264. * @grammar Uploader.register(map, proto);
  1265. * @param {object} responseMap API 名称与函数实现的映射
  1266. * @param {object} proto 组件原型,构造函数通过 constructor 属性定义
  1267. * @method Uploader.register
  1268. * @for Uploader
  1269. * @example
  1270. * Uploader.register({
  1271. * 'make-thumb': 'makeThumb'
  1272. * }, {
  1273. * init: function( options ) {},
  1274. * makeThumb: function() {}
  1275. * });
  1276. *
  1277. * Uploader.register({
  1278. * 'make-thumb': function() {
  1279. *
  1280. * }
  1281. * });
  1282. */
  1283. Uploader.register = Widget.register = function( responseMap, widgetProto ) {
  1284. var map = { init: 'init', destroy: 'destroy', name: 'anonymous' },
  1285. klass;
  1286. if ( arguments.length === 1 ) {
  1287. widgetProto = responseMap;
  1288. // 自动生成 map 表。
  1289. $.each(widgetProto, function(key) {
  1290. if ( key[0] === '_' || key === 'name' ) {
  1291. key === 'name' && (map.name = widgetProto.name);
  1292. return;
  1293. }
  1294. map[key.replace(/[A-Z]/g, '-$&').toLowerCase()] = key;
  1295. });
  1296. } else {
  1297. map = $.extend( map, responseMap );
  1298. }
  1299. widgetProto.responseMap = map;
  1300. klass = Base.inherits( Widget, widgetProto );
  1301. klass._name = map.name;
  1302. widgetClass.push( klass );
  1303. return klass;
  1304. };
  1305. /**
  1306. * 删除插件,只有在注册时指定了名字的才能被删除。
  1307. * @grammar Uploader.unRegister(name);
  1308. * @param {string} name 组件名字
  1309. * @method Uploader.unRegister
  1310. * @for Uploader
  1311. * @example
  1312. *
  1313. * Uploader.register({
  1314. * name: 'custom',
  1315. *
  1316. * 'make-thumb': function() {
  1317. *
  1318. * }
  1319. * });
  1320. *
  1321. * Uploader.unRegister('custom');
  1322. */
  1323. Uploader.unRegister = Widget.unRegister = function( name ) {
  1324. if ( !name || name === 'anonymous' ) {
  1325. return;
  1326. }
  1327. // 删除指定的插件。
  1328. for ( var i = widgetClass.length; i--; ) {
  1329. if ( widgetClass[i]._name === name ) {
  1330. widgetClass.splice(i, 1)
  1331. }
  1332. }
  1333. };
  1334. return Widget;
  1335. });
  1336. /**
  1337. * @fileOverview 文件选择相关
  1338. */
  1339. define('widgets/filepicker',[
  1340. 'base',
  1341. 'uploader',
  1342. 'lib/filepicker',
  1343. 'widgets/widget'
  1344. ], function( Base, Uploader, FilePicker ) {
  1345. var $ = Base.$;
  1346. $.extend( Uploader.options, {
  1347. /**
  1348. * @property {Selector | Object} [pick=undefined]
  1349. * @namespace options
  1350. * @for Uploader
  1351. * @description 指定选择文件的按钮容器,不指定则不创建按钮。
  1352. *
  1353. * * `id` {Seletor|dom} 指定选择文件的按钮容器,不指定则不创建按钮。**注意** 这里虽然写的是 id, 但是不是只支持 id, 还支持 class, 或者 dom 节点。
  1354. * * `label` {String} 请采用 `innerHTML` 代替
  1355. * * `innerHTML` {String} 指定按钮文字。不指定时优先从指定的容器中看是否自带文字。
  1356. * * `multiple` {Boolean} 是否开起同时选择多个文件能力。
  1357. */
  1358. pick: null,
  1359. /**
  1360. * @property {Arroy} [accept=null]
  1361. * @namespace options
  1362. * @for Uploader
  1363. * @description 指定接受哪些类型的文件。 由于目前还有ext转mimeType表,所以这里需要分开指定。
  1364. *
  1365. * * `title` {String} 文字描述
  1366. * * `extensions` {String} 允许的文件后缀,不带点,多个用逗号分割。
  1367. * * `mimeTypes` {String} 多个用逗号分割。
  1368. *
  1369. * 如:
  1370. *
  1371. * ```
  1372. * {
  1373. * title: 'Images',
  1374. * extensions: 'gif,jpg,jpeg,bmp,png',
  1375. * mimeTypes: 'image/*'
  1376. * }
  1377. * ```
  1378. */
  1379. accept: null/*{
  1380. title: 'Images',
  1381. extensions: 'gif,jpg,jpeg,bmp,png',
  1382. mimeTypes: 'image/*'
  1383. }*/
  1384. });
  1385. return Uploader.register({
  1386. name: 'picker',
  1387. init: function( opts ) {
  1388. this.pickers = [];
  1389. return opts.pick && this.addBtn( opts.pick );
  1390. },
  1391. refresh: function() {
  1392. $.each( this.pickers, function() {
  1393. this.refresh();
  1394. });
  1395. },
  1396. /**
  1397. * @method addButton
  1398. * @for Uploader
  1399. * @grammar addButton( pick ) => Promise
  1400. * @description
  1401. * 添加文件选择按钮,如果一个按钮不够,需要调用此方法来添加。参数跟[options.pick](#WebUploader:Uploader:options)一致。
  1402. * @example
  1403. * uploader.addButton({
  1404. * id: '#btnContainer',
  1405. * innerHTML: '选择文件'
  1406. * });
  1407. */
  1408. addBtn: function( pick ) {
  1409. var me = this,
  1410. opts = me.options,
  1411. accept = opts.accept,
  1412. promises = [];
  1413. if ( !pick ) {
  1414. return;
  1415. }
  1416. $.isPlainObject( pick ) || (pick = {
  1417. id: pick
  1418. });
  1419. $( pick.id ).each(function() {
  1420. var options, picker, deferred;
  1421. deferred = Base.Deferred();
  1422. options = $.extend({}, pick, {
  1423. accept: $.isPlainObject( accept ) ? [ accept ] : accept,
  1424. swf: opts.swf,
  1425. runtimeOrder: opts.runtimeOrder,
  1426. id: this
  1427. });
  1428. picker = new FilePicker( options );
  1429. picker.once( 'ready', deferred.resolve );
  1430. picker.on( 'select', function( files ) {
  1431. me.owner.request( 'add-file', [ files ]);
  1432. });
  1433. picker.init();
  1434. me.pickers.push( picker );
  1435. promises.push( deferred.promise() );
  1436. });
  1437. return Base.when.apply( Base, promises );
  1438. },
  1439. disable: function() {
  1440. $.each( this.pickers, function() {
  1441. this.disable();
  1442. });
  1443. },
  1444. enable: function() {
  1445. $.each( this.pickers, function() {
  1446. this.enable();
  1447. });
  1448. },
  1449. destroy: function() {
  1450. $.each( this.pickers, function() {
  1451. this.destroy();
  1452. });
  1453. this.pickers = null;
  1454. }
  1455. });
  1456. });
  1457. /**
  1458. * @fileOverview Image
  1459. */
  1460. define('lib/image',[
  1461. 'base',
  1462. 'runtime/client',
  1463. 'lib/blob'
  1464. ], function( Base, RuntimeClient, Blob ) {
  1465. var $ = Base.$;
  1466. // 构造器。
  1467. function Image( opts ) {
  1468. this.options = $.extend({}, Image.options, opts );
  1469. RuntimeClient.call( this, 'Image' );
  1470. this.on( 'load', function() {
  1471. this._info = this.exec('info');
  1472. this._meta = this.exec('meta');
  1473. });
  1474. }
  1475. // 默认选项。
  1476. Image.options = {
  1477. // 默认的图片处理质量
  1478. quality: 90,
  1479. // 是否裁剪
  1480. crop: false,
  1481. // 是否保留头部信息
  1482. preserveHeaders: false,
  1483. // 是否允许放大。
  1484. allowMagnify: false
  1485. };
  1486. // 继承RuntimeClient.
  1487. Base.inherits( RuntimeClient, {
  1488. constructor: Image,
  1489. info: function( val ) {
  1490. // setter
  1491. if ( val ) {
  1492. this._info = val;
  1493. return this;
  1494. }
  1495. // getter
  1496. return this._info;
  1497. },
  1498. meta: function( val ) {
  1499. // setter
  1500. if ( val ) {
  1501. this._meta = val;
  1502. return this;
  1503. }
  1504. // getter
  1505. return this._meta;
  1506. },
  1507. loadFromBlob: function( blob ) {
  1508. var me = this,
  1509. ruid = blob.getRuid();
  1510. this.connectRuntime( ruid, function() {
  1511. me.exec( 'init', me.options );
  1512. me.exec( 'loadFromBlob', blob );
  1513. });
  1514. },
  1515. resize: function() {
  1516. var args = Base.slice( arguments );
  1517. return this.exec.apply( this, [ 'resize' ].concat( args ) );
  1518. },
  1519. crop: function() {
  1520. var args = Base.slice( arguments );
  1521. return this.exec.apply( this, [ 'crop' ].concat( args ) );
  1522. },
  1523. getAsDataUrl: function( type ) {
  1524. return this.exec( 'getAsDataUrl', type );
  1525. },
  1526. getAsBlob: function( type ) {
  1527. var blob = this.exec( 'getAsBlob', type );
  1528. return new Blob( this.getRuid(), blob );
  1529. }
  1530. });
  1531. return Image;
  1532. });
  1533. /**
  1534. * @fileOverview 图片操作, 负责预览图片和上传前压缩图片
  1535. */
  1536. define('widgets/image',[
  1537. 'base',
  1538. 'uploader',
  1539. 'lib/image',
  1540. 'widgets/widget'
  1541. ], function( Base, Uploader, Image ) {
  1542. var $ = Base.$,
  1543. throttle;
  1544. // 根据要处理的文件大小来节流,一次不能处理太多,会卡。
  1545. throttle = (function( max ) {
  1546. var occupied = 0,
  1547. waiting = [],
  1548. tick = function() {
  1549. var item;
  1550. while ( waiting.length && occupied < max ) {
  1551. item = waiting.shift();
  1552. occupied += item[ 0 ];
  1553. item[ 1 ]();
  1554. }
  1555. };
  1556. return function( emiter, size, cb ) {
  1557. waiting.push([ size, cb ]);
  1558. emiter.once( 'destroy', function() {
  1559. occupied -= size;
  1560. setTimeout( tick, 1 );
  1561. });
  1562. setTimeout( tick, 1 );
  1563. };
  1564. })( 5 * 1024 * 1024 );
  1565. $.extend( Uploader.options, {
  1566. /**
  1567. * @property {Object} [thumb]
  1568. * @namespace options
  1569. * @for Uploader
  1570. * @description 配置生成缩略图的选项。
  1571. *
  1572. * 默认为:
  1573. *
  1574. * ```javascript
  1575. * {
  1576. * width: 110,
  1577. * height: 110,
  1578. *
  1579. * // 图片质量,只有type为`image/jpeg`的时候才有效。
  1580. * quality: 70,
  1581. *
  1582. * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
  1583. * allowMagnify: true,
  1584. *
  1585. * // 是否允许裁剪。
  1586. * crop: true,
  1587. *
  1588. * // 为空的话则保留原有图片格式。
  1589. * // 否则强制转换成指定的类型。
  1590. * type: 'image/jpeg'
  1591. * }
  1592. * ```
  1593. */
  1594. thumb: {
  1595. width: 110,
  1596. height: 110,
  1597. quality: 70,
  1598. allowMagnify: true,
  1599. crop: true,
  1600. preserveHeaders: false,
  1601. // 为空的话则保留原有图片格式。
  1602. // 否则强制转换成指定的类型。
  1603. // IE 8下面 base64 大小不能超过 32K 否则预览失败,而非 jpeg 编码的图片很可
  1604. // 能会超过 32k, 所以这里设置成预览的时候都是 image/jpeg
  1605. type: 'image/jpeg'
  1606. },
  1607. /**
  1608. * @property {Object} [compress]
  1609. * @namespace options
  1610. * @for Uploader
  1611. * @description 配置压缩的图片的选项。如果此选项为`false`, 则图片在上传前不进行压缩。
  1612. *
  1613. * 默认为:
  1614. *
  1615. * ```javascript
  1616. * {
  1617. * width: 1600,
  1618. * height: 1600,
  1619. *
  1620. * // 图片质量,只有type为`image/jpeg`的时候才有效。
  1621. * quality: 90,
  1622. *
  1623. * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
  1624. * allowMagnify: false,
  1625. *
  1626. * // 是否允许裁剪。
  1627. * crop: false,
  1628. *
  1629. * // 是否保留头部meta信息。
  1630. * preserveHeaders: true,
  1631. *
  1632. * // 如果发现压缩后文件大小比原来还大,则使用原来图片
  1633. * // 此属性可能会影响图片自动纠正功能
  1634. * noCompressIfLarger: false,
  1635. *
  1636. * // 单位字节,如果图片大小小于此值,不会采用压缩。
  1637. * compressSize: 0
  1638. * }
  1639. * ```
  1640. */
  1641. compress: {
  1642. width: 1600,
  1643. height: 1600,
  1644. quality: 90,
  1645. allowMagnify: false,
  1646. crop: false,
  1647. preserveHeaders: true
  1648. }
  1649. });
  1650. return Uploader.register({
  1651. name: 'image',
  1652. /**
  1653. * 生成缩略图,此过程为异步,所以需要传入`callback`。
  1654. * 通常情况在图片加入队里后调用此方法来生成预览图以增强交互效果。
  1655. *
  1656. * 当 width 或者 height 的值介于 0 - 1 时,被当成百分比使用。
  1657. *
  1658. * `callback`中可以接收到两个参数。
  1659. * * 第一个为error,如果生成缩略图有错误,此error将为真。
  1660. * * 第二个为ret, 缩略图的Data URL值。
  1661. *
  1662. * **注意**
  1663. * Date URL在IE6/7中不支持,所以不用调用此方法了,直接显示一张暂不支持预览图片好了。
  1664. * 也可以借助服务端,将 base64 数据传给服务端,生成一个临时文件供预览。
  1665. *
  1666. * @method makeThumb
  1667. * @grammar makeThumb( file, callback ) => undefined
  1668. * @grammar makeThumb( file, callback, width, height ) => undefined
  1669. * @for Uploader
  1670. * @example
  1671. *
  1672. * uploader.on( 'fileQueued', function( file ) {
  1673. * var $li = ...;
  1674. *
  1675. * uploader.makeThumb( file, function( error, ret ) {
  1676. * if ( error ) {
  1677. * $li.text('预览错误');
  1678. * } else {
  1679. * $li.append('<img alt="" src="' + ret + '" />');
  1680. * }
  1681. * });
  1682. *
  1683. * });
  1684. */
  1685. makeThumb: function( file, cb, width, height ) {
  1686. var opts, image;
  1687. file = this.request( 'get-file', file );
  1688. // 只预览图片格式。
  1689. if ( !file.type.match( /^image/ ) ) {
  1690. cb( true );
  1691. return;
  1692. }
  1693. opts = $.extend({}, this.options.thumb );
  1694. // 如果传入的是object.
  1695. if ( $.isPlainObject( width ) ) {
  1696. opts = $.extend( opts, width );
  1697. width = null;
  1698. }
  1699. width = width || opts.width;
  1700. height = height || opts.height;
  1701. image = new Image( opts );
  1702. image.once( 'load', function() {
  1703. file._info = file._info || image.info();
  1704. file._meta = file._meta || image.meta();
  1705. // 如果 width 的值介于 0 - 1
  1706. // 说明设置的是百分比。
  1707. if ( width <= 1 && width > 0 ) {
  1708. width = file._info.width * width;
  1709. }
  1710. // 同样的规则应用于 height
  1711. if ( height <= 1 && height > 0 ) {
  1712. height = file._info.height * height;
  1713. }
  1714. image.resize( width, height );
  1715. });
  1716. // 当 resize 完后
  1717. image.once( 'complete', function() {
  1718. cb( false, image.getAsDataUrl( opts.type ) );
  1719. image.destroy();
  1720. });
  1721. image.once( 'error', function( reason ) {
  1722. cb( reason || true );
  1723. image.destroy();
  1724. });
  1725. throttle( image, file.source.size, function() {
  1726. file._info && image.info( file._info );
  1727. file._meta && image.meta( file._meta );
  1728. image.loadFromBlob( file.source );
  1729. });
  1730. },
  1731. beforeSendFile: function( file ) {
  1732. var opts = this.options.compress || this.options.resize,
  1733. compressSize = opts && opts.compressSize || 0,
  1734. noCompressIfLarger = opts && opts.noCompressIfLarger || false,
  1735. image, deferred;
  1736. file = this.request( 'get-file', file );
  1737. // 只压缩 jpeg 图片格式。
  1738. // gif 可能会丢失针
  1739. // bmp png 基本上尺寸都不大,且压缩比比较小。
  1740. if ( !opts || !~'image/jpeg,image/jpg'.indexOf( file.type ) ||
  1741. file.size < compressSize ||
  1742. file._compressed ) {
  1743. return;
  1744. }
  1745. opts = $.extend({}, opts );
  1746. deferred = Base.Deferred();
  1747. image = new Image( opts );
  1748. deferred.always(function() {
  1749. image.destroy();
  1750. image = null;
  1751. });
  1752. image.once( 'error', deferred.reject );
  1753. image.once( 'load', function() {
  1754. var width = opts.width,
  1755. height = opts.height;
  1756. file._info = file._info || image.info();
  1757. file._meta = file._meta || image.meta();
  1758. // 如果 width 的值介于 0 - 1
  1759. // 说明设置的是百分比。
  1760. if ( width <= 1 && width > 0 ) {
  1761. width = file._info.width * width;
  1762. }
  1763. // 同样的规则应用于 height
  1764. if ( height <= 1 && height > 0 ) {
  1765. height = file._info.height * height;
  1766. }
  1767. image.resize( width, height );
  1768. });
  1769. image.once( 'complete', function() {
  1770. var blob, size;
  1771. // 移动端 UC / qq 浏览器的无图模式下
  1772. // ctx.getImageData 处理大图的时候会报 Exception
  1773. // INDEX_SIZE_ERR: DOM Exception 1
  1774. try {
  1775. blob = image.getAsBlob( opts.type );
  1776. size = file.size;
  1777. // 如果压缩后,比原来还大则不用压缩后的。
  1778. if ( !noCompressIfLarger || blob.size < size ) {
  1779. // file.source.destroy && file.source.destroy();
  1780. file.source = blob;
  1781. file.size = blob.size;
  1782. file.trigger( 'resize', blob.size, size );
  1783. }
  1784. // 标记,避免重复压缩。
  1785. file._compressed = true;
  1786. deferred.resolve();
  1787. } catch ( e ) {
  1788. // 出错了直接继续,让其上传原始图片
  1789. deferred.resolve();
  1790. }
  1791. });
  1792. file._info && image.info( file._info );
  1793. file._meta && image.meta( file._meta );
  1794. image.loadFromBlob( file.source );
  1795. return deferred.promise();
  1796. }
  1797. });
  1798. });
  1799. /**
  1800. * @fileOverview 文件属性封装
  1801. */
  1802. define('file',[
  1803. 'base',
  1804. 'mediator'
  1805. ], function( Base, Mediator ) {
  1806. var $ = Base.$,
  1807. idPrefix = 'WU_FILE_',
  1808. idSuffix = 0,
  1809. rExt = /\.([^.]+)$/,
  1810. statusMap = {};
  1811. function gid() {
  1812. return idPrefix + idSuffix++;
  1813. }
  1814. /**
  1815. * 文件类
  1816. * @class File
  1817. * @constructor 构造函数
  1818. * @grammar new File( source ) => File
  1819. * @param {Lib.File} source [lib.File](#Lib.File)实例, 此source对象是带有Runtime信息的。
  1820. */
  1821. function WUFile( source ) {
  1822. /**
  1823. * 文件名,包括扩展名(后缀)
  1824. * @property name
  1825. * @type {string}
  1826. */
  1827. this.name = source.name || 'Untitled';
  1828. /**
  1829. * 文件体积(字节)
  1830. * @property size
  1831. * @type {uint}
  1832. * @default 0
  1833. */
  1834. this.size = source.size || 0;
  1835. /**
  1836. * 文件MIMETYPE类型,与文件类型的对应关系请参考[http://t.cn/z8ZnFny](http://t.cn/z8ZnFny)
  1837. * @property type
  1838. * @type {string}
  1839. * @default 'application/octet-stream'
  1840. */
  1841. this.type = source.type || 'application/octet-stream';
  1842. /**
  1843. * 文件最后修改日期
  1844. * @property lastModifiedDate
  1845. * @type {int}
  1846. * @default 当前时间戳
  1847. */
  1848. this.lastModifiedDate = source.lastModifiedDate || (new Date() * 1);
  1849. /**
  1850. * 文件ID,每个对象具有唯一ID,与文件名无关
  1851. * @property id
  1852. * @type {string}
  1853. */
  1854. this.id = gid();
  1855. /**
  1856. * 文件扩展名,通过文件名获取,例如test.png的扩展名为png
  1857. * @property ext
  1858. * @type {string}
  1859. */
  1860. this.ext = rExt.exec( this.name ) ? RegExp.$1 : '';
  1861. /**
  1862. * 状态文字说明。在不同的status语境下有不同的用途。
  1863. * @property statusText
  1864. * @type {string}
  1865. */
  1866. this.statusText = '';
  1867. // 存储文件状态,防止通过属性直接修改
  1868. statusMap[ this.id ] = WUFile.Status.INITED;
  1869. this.source = source;
  1870. this.loaded = 0;
  1871. this.on( 'error', function( msg ) {
  1872. this.setStatus( WUFile.Status.ERROR, msg );
  1873. });
  1874. }
  1875. $.extend( WUFile.prototype, {
  1876. /**
  1877. * 设置状态,状态变化时会触发`change`事件。
  1878. * @method setStatus
  1879. * @grammar setStatus( status[, statusText] );
  1880. * @param {File.Status|String} status [文件状态值](#WebUploader:File:File.Status)
  1881. * @param {String} [statusText=''] 状态说明,常在error时使用,用http, abort,server等来标记是由于什么原因导致文件错误。
  1882. */
  1883. setStatus: function( status, text ) {
  1884. var prevStatus = statusMap[ this.id ];
  1885. typeof text !== 'undefined' && (this.statusText = text);
  1886. if ( status !== prevStatus ) {
  1887. statusMap[ this.id ] = status;
  1888. /**
  1889. * 文件状态变化
  1890. * @event statuschange
  1891. */
  1892. this.trigger( 'statuschange', status, prevStatus );
  1893. }
  1894. },
  1895. /**
  1896. * 获取文件状态
  1897. * @return {File.Status}
  1898. * @example
  1899. 文件状态具体包括以下几种类型:
  1900. {
  1901. // 初始化
  1902. INITED: 0,
  1903. // 已入队列
  1904. QUEUED: 1,
  1905. // 正在上传
  1906. PROGRESS: 2,
  1907. // 上传出错
  1908. ERROR: 3,
  1909. // 上传成功
  1910. COMPLETE: 4,
  1911. // 上传取消
  1912. CANCELLED: 5
  1913. }
  1914. */
  1915. getStatus: function() {
  1916. return statusMap[ this.id ];
  1917. },
  1918. /**
  1919. * 获取文件原始信息。
  1920. * @return {*}
  1921. */
  1922. getSource: function() {
  1923. return this.source;
  1924. },
  1925. destroy: function() {
  1926. this.off();
  1927. delete statusMap[ this.id ];
  1928. }
  1929. });
  1930. Mediator.installTo( WUFile.prototype );
  1931. /**
  1932. * 文件状态值,具体包括以下几种类型:
  1933. * * `inited` 初始状态
  1934. * * `queued` 已经进入队列, 等待上传
  1935. * * `progress` 上传中
  1936. * * `complete` 上传完成。
  1937. * * `error` 上传出错,可重试
  1938. * * `interrupt` 上传中断,可续传。
  1939. * * `invalid` 文件不合格,不能重试上传。会自动从队列中移除。
  1940. * * `cancelled` 文件被移除。
  1941. * @property {Object} Status
  1942. * @namespace File
  1943. * @class File
  1944. * @static
  1945. */
  1946. WUFile.Status = {
  1947. INITED: 'inited', // 初始状态
  1948. QUEUED: 'queued', // 已经进入队列, 等待上传
  1949. PROGRESS: 'progress', // 上传中
  1950. ERROR: 'error', // 上传出错,可重试
  1951. COMPLETE: 'complete', // 上传完成。
  1952. CANCELLED: 'cancelled', // 上传取消。
  1953. INTERRUPT: 'interrupt', // 上传中断,可续传。
  1954. INVALID: 'invalid' // 文件不合格,不能重试上传。
  1955. };
  1956. return WUFile;
  1957. });
  1958. /**
  1959. * @fileOverview 文件队列
  1960. */
  1961. define('queue',[
  1962. 'base',
  1963. 'mediator',
  1964. 'file'
  1965. ], function( Base, Mediator, WUFile ) {
  1966. var $ = Base.$,
  1967. STATUS = WUFile.Status;
  1968. /**
  1969. * 文件队列, 用来存储各个状态中的文件。
  1970. * @class Queue
  1971. * @extends Mediator
  1972. */
  1973. function Queue() {
  1974. /**
  1975. * 统计文件数。
  1976. * * `numOfQueue` 队列中的文件数。
  1977. * * `numOfSuccess` 上传成功的文件数
  1978. * * `numOfCancel` 被取消的文件数
  1979. * * `numOfProgress` 正在上传中的文件数
  1980. * * `numOfUploadFailed` 上传错误的文件数。
  1981. * * `numOfInvalid` 无效的文件数。
  1982. * * `numofDeleted` 被移除的文件数。
  1983. * @property {Object} stats
  1984. */
  1985. this.stats = {
  1986. numOfQueue: 0,
  1987. numOfSuccess: 0,
  1988. numOfCancel: 0,
  1989. numOfProgress: 0,
  1990. numOfUploadFailed: 0,
  1991. numOfInvalid: 0,
  1992. numofDeleted: 0,
  1993. numofInterrupt: 0
  1994. };
  1995. // 上传队列,仅包括等待上传的文件
  1996. this._queue = [];
  1997. // 存储所有文件
  1998. this._map = {};
  1999. }
  2000. $.extend( Queue.prototype, {
  2001. /**
  2002. * 将新文件加入对队列尾部
  2003. *
  2004. * @method append
  2005. * @param {File} file 文件对象
  2006. */
  2007. append: function( file ) {
  2008. this._queue.push( file );
  2009. this._fileAdded( file );
  2010. return this;
  2011. },
  2012. /**
  2013. * 将新文件加入对队列头部
  2014. *
  2015. * @method prepend
  2016. * @param {File} file 文件对象
  2017. */
  2018. prepend: function( file ) {
  2019. this._queue.unshift( file );
  2020. this._fileAdded( file );
  2021. return this;
  2022. },
  2023. /**
  2024. * 获取文件对象
  2025. *
  2026. * @method getFile
  2027. * @param {String} fileId 文件ID
  2028. * @return {File}
  2029. */
  2030. getFile: function( fileId ) {
  2031. if ( typeof fileId !== 'string' ) {
  2032. return fileId;
  2033. }
  2034. return this._map[ fileId ];
  2035. },
  2036. /**
  2037. * 从队列中取出一个指定状态的文件。
  2038. * @grammar fetch( status ) => File
  2039. * @method fetch
  2040. * @param {String} status [文件状态值](#WebUploader:File:File.Status)
  2041. * @return {File} [File](#WebUploader:File)
  2042. */
  2043. fetch: function( status ) {
  2044. var len = this._queue.length,
  2045. i, file;
  2046. status = status || STATUS.QUEUED;
  2047. for ( i = 0; i < len; i++ ) {
  2048. file = this._queue[ i ];
  2049. if ( status === file.getStatus() ) {
  2050. return file;
  2051. }
  2052. }
  2053. return null;
  2054. },
  2055. /**
  2056. * 对队列进行排序,能够控制文件上传顺序。
  2057. * @grammar sort( fn ) => undefined
  2058. * @method sort
  2059. * @param {Function} fn 排序方法
  2060. */
  2061. sort: function( fn ) {
  2062. if ( typeof fn === 'function' ) {
  2063. this._queue.sort( fn );
  2064. }
  2065. },
  2066. /**
  2067. * 获取指定类型的文件列表, 列表中每一个成员为[File](#WebUploader:File)对象。
  2068. * @grammar getFiles( [status1[, status2 ...]] ) => Array
  2069. * @method getFiles
  2070. * @param {String} [status] [文件状态值](#WebUploader:File:File.Status)
  2071. */
  2072. getFiles: function() {
  2073. var sts = [].slice.call( arguments, 0 ),
  2074. ret = [],
  2075. i = 0,
  2076. len = this._queue.length,
  2077. file;
  2078. for ( ; i < len; i++ ) {
  2079. file = this._queue[ i ];
  2080. if ( sts.length && !~$.inArray( file.getStatus(), sts ) ) {
  2081. continue;
  2082. }
  2083. ret.push( file );
  2084. }
  2085. return ret;
  2086. },
  2087. /**
  2088. * 在队列中删除文件。
  2089. * @grammar removeFile( file ) => Array
  2090. * @method removeFile
  2091. * @param {File} 文件对象。
  2092. */
  2093. removeFile: function( file ) {
  2094. var me = this,
  2095. existing = this._map[ file.id ];
  2096. if ( existing ) {
  2097. delete this._map[ file.id ];
  2098. file.destroy();
  2099. this.stats.numofDeleted++;
  2100. }
  2101. },
  2102. _fileAdded: function( file ) {
  2103. var me = this,
  2104. existing = this._map[ file.id ];
  2105. if ( !existing ) {
  2106. this._map[ file.id ] = file;
  2107. file.on( 'statuschange', function( cur, pre ) {
  2108. me._onFileStatusChange( cur, pre );
  2109. });
  2110. }
  2111. },
  2112. _onFileStatusChange: function( curStatus, preStatus ) {
  2113. var stats = this.stats;
  2114. switch ( preStatus ) {
  2115. case STATUS.PROGRESS:
  2116. stats.numOfProgress--;
  2117. break;
  2118. case STATUS.QUEUED:
  2119. stats.numOfQueue --;
  2120. break;
  2121. case STATUS.ERROR:
  2122. stats.numOfUploadFailed--;
  2123. break;
  2124. case STATUS.INVALID:
  2125. stats.numOfInvalid--;
  2126. break;
  2127. case STATUS.INTERRUPT:
  2128. stats.numofInterrupt--;
  2129. break;
  2130. }
  2131. switch ( curStatus ) {
  2132. case STATUS.QUEUED:
  2133. stats.numOfQueue++;
  2134. break;
  2135. case STATUS.PROGRESS:
  2136. stats.numOfProgress++;
  2137. break;
  2138. case STATUS.ERROR:
  2139. stats.numOfUploadFailed++;
  2140. break;
  2141. case STATUS.COMPLETE:
  2142. stats.numOfSuccess++;
  2143. break;
  2144. case STATUS.CANCELLED:
  2145. stats.numOfCancel++;
  2146. break;
  2147. case STATUS.INVALID:
  2148. stats.numOfInvalid++;
  2149. break;
  2150. case STATUS.INTERRUPT:
  2151. stats.numofInterrupt++;
  2152. break;
  2153. }
  2154. }
  2155. });
  2156. Mediator.installTo( Queue.prototype );
  2157. return Queue;
  2158. });
  2159. /**
  2160. * @fileOverview 队列
  2161. */
  2162. define('widgets/queue',[
  2163. 'base',
  2164. 'uploader',
  2165. 'queue',
  2166. 'file',
  2167. 'lib/file',
  2168. 'runtime/client',
  2169. 'widgets/widget'
  2170. ], function( Base, Uploader, Queue, WUFile, File, RuntimeClient ) {
  2171. var $ = Base.$,
  2172. rExt = /\.\w+$/,
  2173. Status = WUFile.Status;
  2174. return Uploader.register({
  2175. name: 'queue',
  2176. init: function( opts ) {
  2177. var me = this,
  2178. deferred, len, i, item, arr, accept, runtime;
  2179. if ( $.isPlainObject( opts.accept ) ) {
  2180. opts.accept = [ opts.accept ];
  2181. }
  2182. // accept中的中生成匹配正则。
  2183. if ( opts.accept ) {
  2184. arr = [];
  2185. for ( i = 0, len = opts.accept.length; i < len; i++ ) {
  2186. item = opts.accept[ i ].extensions;
  2187. item && arr.push( item );
  2188. }
  2189. if ( arr.length ) {
  2190. accept = '\\.' + arr.join(',')
  2191. .replace( /,/g, '$|\\.' )
  2192. .replace( /\*/g, '.*' ) + '$';
  2193. }
  2194. me.accept = new RegExp( accept, 'i' );
  2195. }
  2196. me.queue = new Queue();
  2197. me.stats = me.queue.stats;
  2198. // 如果当前不是html5运行时,那就算了。
  2199. // 不执行后续操作
  2200. if ( this.request('predict-runtime-type') !== 'html5' ) {
  2201. return;
  2202. }
  2203. // 创建一个 html5 运行时的 placeholder
  2204. // 以至于外部添加原生 File 对象的时候能正确包裹一下供 webuploader 使用。
  2205. deferred = Base.Deferred();
  2206. this.placeholder = runtime = new RuntimeClient('Placeholder');
  2207. runtime.connectRuntime({
  2208. runtimeOrder: 'html5'
  2209. }, function() {
  2210. me._ruid = runtime.getRuid();
  2211. deferred.resolve();
  2212. });
  2213. return deferred.promise();
  2214. },
  2215. // 为了支持外部直接添加一个原生File对象。
  2216. _wrapFile: function( file ) {
  2217. if ( !(file instanceof WUFile) ) {
  2218. if ( !(file instanceof File) ) {
  2219. if ( !this._ruid ) {
  2220. throw new Error('Can\'t add external files.');
  2221. }
  2222. file = new File( this._ruid, file );
  2223. }
  2224. file = new WUFile( file );
  2225. }
  2226. return file;
  2227. },
  2228. // 判断文件是否可以被加入队列
  2229. acceptFile: function( file ) {
  2230. var invalid = !file || !file.size || this.accept &&
  2231. // 如果名字中有后缀,才做后缀白名单处理。
  2232. rExt.exec( file.name ) && !this.accept.test( file.name );
  2233. return !invalid;
  2234. },
  2235. /**
  2236. * @event beforeFileQueued
  2237. * @param {File} file File对象
  2238. * @description 当文件被加入队列之前触发,此事件的handler返回值为`false`,则此文件不会被添加进入队列。
  2239. * @for Uploader
  2240. */
  2241. /**
  2242. * @event fileQueued
  2243. * @param {File} file File对象
  2244. * @description 当文件被加入队列以后触发。
  2245. * @for Uploader
  2246. */
  2247. _addFile: function( file ) {
  2248. var me = this;
  2249. file = me._wrapFile( file );
  2250. // 不过类型判断允许不允许,先派送 `beforeFileQueued`
  2251. if ( !me.owner.trigger( 'beforeFileQueued', file ) ) {
  2252. return;
  2253. }
  2254. // 类型不匹配,则派送错误事件,并返回。
  2255. if ( !me.acceptFile( file ) ) {
  2256. me.owner.trigger( 'error', 'Q_TYPE_DENIED', file );
  2257. return;
  2258. }
  2259. me.queue.append( file );
  2260. me.owner.trigger( 'fileQueued', file );
  2261. return file;
  2262. },
  2263. getFile: function( fileId ) {
  2264. return this.queue.getFile( fileId );
  2265. },
  2266. /**
  2267. * @event filesQueued
  2268. * @param {File} files 数组,内容为原始File(lib/File)对象。
  2269. * @description 当一批文件添加进队列以后触发。
  2270. * @for Uploader
  2271. */
  2272. /**
  2273. * @property {Boolean} [auto=false]
  2274. * @namespace options
  2275. * @for Uploader
  2276. * @description 设置为 true 后,不需要手动调用上传,有文件选择即开始上传。
  2277. *
  2278. */
  2279. /**
  2280. * @method addFiles
  2281. * @grammar addFiles( file ) => undefined
  2282. * @grammar addFiles( [file1, file2 ...] ) => undefined
  2283. * @param {Array of File or File} [files] Files 对象 数组
  2284. * @description 添加文件到队列
  2285. * @for Uploader
  2286. */
  2287. addFile: function( files ) {
  2288. var me = this;
  2289. if ( !files.length ) {
  2290. files = [ files ];
  2291. }
  2292. files = $.map( files, function( file ) {
  2293. return me._addFile( file );
  2294. });
  2295. me.owner.trigger( 'filesQueued', files );
  2296. if ( me.options.auto ) {
  2297. setTimeout(function() {
  2298. me.request('start-upload');
  2299. }, 20 );
  2300. }
  2301. },
  2302. getStats: function() {
  2303. return this.stats;
  2304. },
  2305. /**
  2306. * @event fileDequeued
  2307. * @param {File} file File对象
  2308. * @description 当文件被移除队列后触发。
  2309. * @for Uploader
  2310. */
  2311. /**
  2312. * @method removeFile
  2313. * @grammar removeFile( file ) => undefined
  2314. * @grammar removeFile( id ) => undefined
  2315. * @grammar removeFile( file, true ) => undefined
  2316. * @grammar removeFile( id, true ) => undefined
  2317. * @param {File|id} file File对象或这File对象的id
  2318. * @description 移除某一文件, 默认只会标记文件状态为已取消,如果第二个参数为 `true` 则会从 queue 中移除。
  2319. * @for Uploader
  2320. * @example
  2321. *
  2322. * $li.on('click', '.remove-this', function() {
  2323. * uploader.removeFile( file );
  2324. * })
  2325. */
  2326. removeFile: function( file, remove ) {
  2327. var me = this;
  2328. file = file.id ? file : me.queue.getFile( file );
  2329. this.request( 'cancel-file', file );
  2330. if ( remove ) {
  2331. this.queue.removeFile( file );
  2332. }
  2333. },
  2334. /**
  2335. * @method getFiles
  2336. * @grammar getFiles() => Array
  2337. * @grammar getFiles( status1, status2, status... ) => Array
  2338. * @description 返回指定状态的文件集合,不传参数将返回所有状态的文件。
  2339. * @for Uploader
  2340. * @example
  2341. * console.log( uploader.getFiles() ); // => all files
  2342. * console.log( uploader.getFiles('error') ) // => all error files.
  2343. */
  2344. getFiles: function() {
  2345. return this.queue.getFiles.apply( this.queue, arguments );
  2346. },
  2347. fetchFile: function() {
  2348. return this.queue.fetch.apply( this.queue, arguments );
  2349. },
  2350. /**
  2351. * @method retry
  2352. * @grammar retry() => undefined
  2353. * @grammar retry( file ) => undefined
  2354. * @description 重试上传,重试指定文件,或者从出错的文件开始重新上传。
  2355. * @for Uploader
  2356. * @example
  2357. * function retry() {
  2358. * uploader.retry();
  2359. * }
  2360. */
  2361. retry: function( file, noForceStart ) {
  2362. var me = this,
  2363. files, i, len;
  2364. if ( file ) {
  2365. file = file.id ? file : me.queue.getFile( file );
  2366. file.setStatus( Status.QUEUED );
  2367. noForceStart || me.request('start-upload');
  2368. return;
  2369. }
  2370. files = me.queue.getFiles( Status.ERROR );
  2371. i = 0;
  2372. len = files.length;
  2373. for ( ; i < len; i++ ) {
  2374. file = files[ i ];
  2375. file.setStatus( Status.QUEUED );
  2376. }
  2377. me.request('start-upload');
  2378. },
  2379. /**
  2380. * @method sort
  2381. * @grammar sort( fn ) => undefined
  2382. * @description 排序队列中的文件,在上传之前调整可以控制上传顺序。
  2383. * @for Uploader
  2384. */
  2385. sortFiles: function() {
  2386. return this.queue.sort.apply( this.queue, arguments );
  2387. },
  2388. /**
  2389. * @event reset
  2390. * @description 当 uploader 被重置的时候触发。
  2391. * @for Uploader
  2392. */
  2393. /**
  2394. * @method reset
  2395. * @grammar reset() => undefined
  2396. * @description 重置uploader。目前只重置了队列。
  2397. * @for Uploader
  2398. * @example
  2399. * uploader.reset();
  2400. */
  2401. reset: function() {
  2402. this.owner.trigger('reset');
  2403. this.queue = new Queue();
  2404. this.stats = this.queue.stats;
  2405. },
  2406. destroy: function() {
  2407. this.reset();
  2408. this.placeholder && this.placeholder.destroy();
  2409. }
  2410. });
  2411. });
  2412. /**
  2413. * @fileOverview 添加获取Runtime相关信息的方法。
  2414. */
  2415. define('widgets/runtime',[
  2416. 'uploader',
  2417. 'runtime/runtime',
  2418. 'widgets/widget'
  2419. ], function( Uploader, Runtime ) {
  2420. Uploader.support = function() {
  2421. return Runtime.hasRuntime.apply( Runtime, arguments );
  2422. };
  2423. /**
  2424. * @property {Object} [runtimeOrder=html5,flash]
  2425. * @namespace options
  2426. * @for Uploader
  2427. * @description 指定运行时启动顺序。默认会想尝试 html5 是否支持,如果支持则使用 html5, 否则则使用 flash.
  2428. *
  2429. * 可以将此值设置成 `flash`,来强制使用 flash 运行时。
  2430. */
  2431. return Uploader.register({
  2432. name: 'runtime',
  2433. init: function() {
  2434. if ( !this.predictRuntimeType() ) {
  2435. throw Error('Runtime Error');
  2436. }
  2437. },
  2438. /**
  2439. * 预测Uploader将采用哪个`Runtime`
  2440. * @grammar predictRuntimeType() => String
  2441. * @method predictRuntimeType
  2442. * @for Uploader
  2443. */
  2444. predictRuntimeType: function() {
  2445. var orders = this.options.runtimeOrder || Runtime.orders,
  2446. type = this.type,
  2447. i, len;
  2448. if ( !type ) {
  2449. orders = orders.split( /\s*,\s*/g );
  2450. for ( i = 0, len = orders.length; i < len; i++ ) {
  2451. if ( Runtime.hasRuntime( orders[ i ] ) ) {
  2452. this.type = type = orders[ i ];
  2453. break;
  2454. }
  2455. }
  2456. }
  2457. return type;
  2458. }
  2459. });
  2460. });
  2461. /**
  2462. * @fileOverview Transport
  2463. */
  2464. define('lib/transport',[
  2465. 'base',
  2466. 'runtime/client',
  2467. 'mediator'
  2468. ], function( Base, RuntimeClient, Mediator ) {
  2469. var $ = Base.$;
  2470. function Transport( opts ) {
  2471. var me = this;
  2472. opts = me.options = $.extend( true, {}, Transport.options, opts || {} );
  2473. RuntimeClient.call( this, 'Transport' );
  2474. this._blob = null;
  2475. this._formData = opts.formData || {};
  2476. this._headers = opts.headers || {};
  2477. this.on( 'progress', this._timeout );
  2478. this.on( 'load error', function() {
  2479. me.trigger( 'progress', 1 );
  2480. clearTimeout( me._timer );
  2481. });
  2482. }
  2483. Transport.options = {
  2484. server: '',
  2485. method: 'POST',
  2486. // 跨域时,是否允许携带cookie, 只有html5 runtime才有效
  2487. withCredentials: false,
  2488. fileVal: 'file',
  2489. timeout: 2 * 60 * 1000, // 2分钟
  2490. formData: {},
  2491. headers: {},
  2492. sendAsBinary: false
  2493. };
  2494. $.extend( Transport.prototype, {
  2495. // 添加Blob, 只能添加一次,最后一次有效。
  2496. appendBlob: function( key, blob, filename ) {
  2497. var me = this,
  2498. opts = me.options;
  2499. if ( me.getRuid() ) {
  2500. me.disconnectRuntime();
  2501. }
  2502. // 连接到blob归属的同一个runtime.
  2503. me.connectRuntime( blob.ruid, function() {
  2504. me.exec('init');
  2505. });
  2506. me._blob = blob;
  2507. opts.fileVal = key || opts.fileVal;
  2508. opts.filename = filename || opts.filename;
  2509. },
  2510. // 添加其他字段
  2511. append: function( key, value ) {
  2512. if ( typeof key === 'object' ) {
  2513. $.extend( this._formData, key );
  2514. } else {
  2515. this._formData[ key ] = value;
  2516. }
  2517. },
  2518. setRequestHeader: function( key, value ) {
  2519. if ( typeof key === 'object' ) {
  2520. $.extend( this._headers, key );
  2521. } else {
  2522. this._headers[ key ] = value;
  2523. }
  2524. },
  2525. send: function( method ) {
  2526. this.exec( 'send', method );
  2527. this._timeout();
  2528. },
  2529. abort: function() {
  2530. clearTimeout( this._timer );
  2531. return this.exec('abort');
  2532. },
  2533. destroy: function() {
  2534. this.trigger('destroy');
  2535. this.off();
  2536. this.exec('destroy');
  2537. this.disconnectRuntime();
  2538. },
  2539. getResponse: function() {
  2540. return this.exec('getResponse');
  2541. },
  2542. getResponseAsJson: function() {
  2543. return this.exec('getResponseAsJson');
  2544. },
  2545. getStatus: function() {
  2546. return this.exec('getStatus');
  2547. },
  2548. _timeout: function() {
  2549. var me = this,
  2550. duration = me.options.timeout;
  2551. if ( !duration ) {
  2552. return;
  2553. }
  2554. clearTimeout( me._timer );
  2555. me._timer = setTimeout(function() {
  2556. me.abort();
  2557. me.trigger( 'error', 'timeout' );
  2558. }, duration );
  2559. }
  2560. });
  2561. // 让Transport具备事件功能。
  2562. Mediator.installTo( Transport.prototype );
  2563. return Transport;
  2564. });
  2565. /**
  2566. * @fileOverview 负责文件上传相关。
  2567. */
  2568. define('widgets/upload',[
  2569. 'base',
  2570. 'uploader',
  2571. 'file',
  2572. 'lib/transport',
  2573. 'widgets/widget'
  2574. ], function( Base, Uploader, WUFile, Transport ) {
  2575. var $ = Base.$,
  2576. isPromise = Base.isPromise,
  2577. Status = WUFile.Status;
  2578. // 添加默认配置项
  2579. $.extend( Uploader.options, {
  2580. /**
  2581. * @property {Boolean} [prepareNextFile=false]
  2582. * @namespace options
  2583. * @for Uploader
  2584. * @description 是否允许在文件传输时提前把下一个文件准备好。
  2585. * 对于一个文件的准备工作比较耗时,比如图片压缩,md5序列化。
  2586. * 如果能提前在当前文件传输期处理,可以节省总体耗时。
  2587. */
  2588. prepareNextFile: false,
  2589. /**
  2590. * @property {Boolean} [chunked=false]
  2591. * @namespace options
  2592. * @for Uploader
  2593. * @description 是否要分片处理大文件上传。
  2594. */
  2595. chunked: false,
  2596. /**
  2597. * @property {Boolean} [chunkSize=5242880]
  2598. * @namespace options
  2599. * @for Uploader
  2600. * @description 如果要分片,分多大一片? 默认大小为5M.
  2601. */
  2602. chunkSize: 5 * 1024 * 1024,
  2603. /**
  2604. * @property {Boolean} [chunkRetry=2]
  2605. * @namespace options
  2606. * @for Uploader
  2607. * @description 如果某个分片由于网络问题出错,允许自动重传多少次?
  2608. */
  2609. chunkRetry: 2,
  2610. /**
  2611. * @property {Boolean} [threads=3]
  2612. * @namespace options
  2613. * @for Uploader
  2614. * @description 上传并发数。允许同时最大上传进程数。
  2615. */
  2616. threads: 3,
  2617. /**
  2618. * @property {Object} [formData={}]
  2619. * @namespace options
  2620. * @for Uploader
  2621. * @description 文件上传请求的参数表,每次发送都会发送此对象中的参数。
  2622. */
  2623. formData: {}
  2624. /**
  2625. * @property {Object} [fileVal='file']
  2626. * @namespace options
  2627. * @for Uploader
  2628. * @description 设置文件上传域的name。
  2629. */
  2630. /**
  2631. * @property {Object} [method='POST']
  2632. * @namespace options
  2633. * @for Uploader
  2634. * @description 文件上传方式,`POST`或者`GET`。
  2635. */
  2636. /**
  2637. * @property {Object} [sendAsBinary=false]
  2638. * @namespace options
  2639. * @for Uploader
  2640. * @description 是否已二进制的流的方式发送文件,这样整个上传内容`php://input`都为文件内容,
  2641. * 其他参数在$_GET数组中。
  2642. */
  2643. });
  2644. // 负责将文件切片。
  2645. function CuteFile( file, chunkSize ) {
  2646. var pending = [],
  2647. blob = file.source,
  2648. total = blob.size,
  2649. chunks = chunkSize ? Math.ceil( total / chunkSize ) : 1,
  2650. start = 0,
  2651. index = 0,
  2652. len, api;
  2653. api = {
  2654. file: file,
  2655. has: function() {
  2656. return !!pending.length;
  2657. },
  2658. shift: function() {
  2659. return pending.shift();
  2660. },
  2661. unshift: function( block ) {
  2662. pending.unshift( block );
  2663. }
  2664. };
  2665. while ( index < chunks ) {
  2666. len = Math.min( chunkSize, total - start );
  2667. pending.push({
  2668. file: file,
  2669. start: start,
  2670. end: chunkSize ? (start + len) : total,
  2671. total: total,
  2672. chunks: chunks,
  2673. chunk: index++,
  2674. cuted: api
  2675. });
  2676. start += len;
  2677. }
  2678. file.blocks = pending.concat();
  2679. file.remaning = pending.length;
  2680. return api;
  2681. }
  2682. Uploader.register({
  2683. name: 'upload',
  2684. init: function() {
  2685. var owner = this.owner,
  2686. me = this;
  2687. this.runing = false;
  2688. this.progress = false;
  2689. owner
  2690. .on( 'startUpload', function() {
  2691. me.progress = true;
  2692. })
  2693. .on( 'uploadFinished', function() {
  2694. me.progress = false;
  2695. });
  2696. // 记录当前正在传的数据,跟threads相关
  2697. this.pool = [];
  2698. // 缓存分好片的文件。
  2699. this.stack = [];
  2700. // 缓存即将上传的文件。
  2701. this.pending = [];
  2702. // 跟踪还有多少分片在上传中但是没有完成上传。
  2703. this.remaning = 0;
  2704. this.__tick = Base.bindFn( this._tick, this );
  2705. owner.on( 'uploadComplete', function( file ) {
  2706. // 把其他块取消了。
  2707. file.blocks && $.each( file.blocks, function( _, v ) {
  2708. v.transport && (v.transport.abort(), v.transport.destroy());
  2709. delete v.transport;
  2710. });
  2711. delete file.blocks;
  2712. delete file.remaning;
  2713. });
  2714. },
  2715. reset: function() {
  2716. this.request( 'stop-upload', true );
  2717. this.runing = false;
  2718. this.pool = [];
  2719. this.stack = [];
  2720. this.pending = [];
  2721. this.remaning = 0;
  2722. this._trigged = false;
  2723. this._promise = null;
  2724. },
  2725. /**
  2726. * @event startUpload
  2727. * @description 当开始上传流程时触发。
  2728. * @for Uploader
  2729. */
  2730. /**
  2731. * 开始上传。此方法可以从初始状态调用开始上传流程,也可以从暂停状态调用,继续上传流程。
  2732. *
  2733. * 可以指定开始某一个文件。
  2734. * @grammar upload() => undefined
  2735. * @grammar upload( file | fileId) => undefined
  2736. * @method upload
  2737. * @for Uploader
  2738. */
  2739. startUpload: function(file) {
  2740. var me = this;
  2741. // 移出invalid的文件
  2742. $.each( me.request( 'get-files', Status.INVALID ), function() {
  2743. me.request( 'remove-file', this );
  2744. });
  2745. // 如果指定了开始某个文件,则只开始指定文件。
  2746. if ( file ) {
  2747. file = file.id ? file : me.request( 'get-file', file );
  2748. if (file.getStatus() === Status.INTERRUPT) {
  2749. $.each( me.pool, function( _, v ) {
  2750. // 之前暂停过。
  2751. if (v.file !== file) {
  2752. return;
  2753. }
  2754. v.transport && v.transport.send();
  2755. });
  2756. file.setStatus( Status.QUEUED );
  2757. } else if (file.getStatus() === Status.PROGRESS) {
  2758. return;
  2759. } else {
  2760. file.setStatus( Status.QUEUED );
  2761. }
  2762. } else {
  2763. $.each( me.request( 'get-files', [ Status.INITED ] ), function() {
  2764. this.setStatus( Status.QUEUED );
  2765. });
  2766. }
  2767. if ( me.runing ) {
  2768. return;
  2769. }
  2770. me.runing = true;
  2771. var files = [];
  2772. // 如果有暂停的,则续传
  2773. $.each( me.pool, function( _, v ) {
  2774. var file = v.file;
  2775. if ( file.getStatus() === Status.INTERRUPT ) {
  2776. files.push(file);
  2777. me._trigged = false;
  2778. v.transport && v.transport.send();
  2779. }
  2780. });
  2781. var file;
  2782. while ( (file = files.shift()) ) {
  2783. file.setStatus( Status.PROGRESS );
  2784. }
  2785. file || $.each( me.request( 'get-files',
  2786. Status.INTERRUPT ), function() {
  2787. this.setStatus( Status.PROGRESS );
  2788. });
  2789. me._trigged = false;
  2790. Base.nextTick( me.__tick );
  2791. me.owner.trigger('startUpload');
  2792. },
  2793. /**
  2794. * @event stopUpload
  2795. * @description 当开始上传流程暂停时触发。
  2796. * @for Uploader
  2797. */
  2798. /**
  2799. * 暂停上传。第一个参数为是否中断上传当前正在上传的文件。
  2800. *
  2801. * 如果第一个参数是文件,则只暂停指定文件。
  2802. * @grammar stop() => undefined
  2803. * @grammar stop( true ) => undefined
  2804. * @grammar stop( file ) => undefined
  2805. * @method stop
  2806. * @for Uploader
  2807. */
  2808. stopUpload: function( file, interrupt ) {
  2809. var me = this;
  2810. if (file === true) {
  2811. interrupt = file;
  2812. file = null;
  2813. }
  2814. if ( me.runing === false ) {
  2815. return;
  2816. }
  2817. // 如果只是暂停某个文件。
  2818. if ( file ) {
  2819. file = file.id ? file : me.request( 'get-file', file );
  2820. if ( file.getStatus() !== Status.PROGRESS &&
  2821. file.getStatus() !== Status.QUEUED ) {
  2822. return;
  2823. }
  2824. file.setStatus( Status.INTERRUPT );
  2825. $.each( me.pool, function( _, v ) {
  2826. // 只 abort 指定的文件。
  2827. if (v.file !== file) {
  2828. return;
  2829. }
  2830. v.transport && v.transport.abort();
  2831. me._putback(v);
  2832. me._popBlock(v);
  2833. });
  2834. return Base.nextTick( me.__tick );
  2835. }
  2836. me.runing = false;
  2837. if (this._promise && this._promise.file) {
  2838. this._promise.file.setStatus( Status.INTERRUPT );
  2839. }
  2840. interrupt && $.each( me.pool, function( _, v ) {
  2841. v.transport && v.transport.abort();
  2842. v.file.setStatus( Status.INTERRUPT );
  2843. });
  2844. me.owner.trigger('stopUpload');
  2845. },
  2846. /**
  2847. * @method cancelFile
  2848. * @grammar cancelFile( file ) => undefined
  2849. * @grammar cancelFile( id ) => undefined
  2850. * @param {File|id} file File对象或这File对象的id
  2851. * @description 标记文件状态为已取消, 同时将中断文件传输。
  2852. * @for Uploader
  2853. * @example
  2854. *
  2855. * $li.on('click', '.remove-this', function() {
  2856. * uploader.cancelFile( file );
  2857. * })
  2858. */
  2859. cancelFile: function( file ) {
  2860. file = file.id ? file : this.request( 'get-file', file );
  2861. // 如果正在上传。
  2862. file.blocks && $.each( file.blocks, function( _, v ) {
  2863. var _tr = v.transport;
  2864. if ( _tr ) {
  2865. _tr.abort();
  2866. _tr.destroy();
  2867. delete v.transport;
  2868. }
  2869. });
  2870. file.setStatus( Status.CANCELLED );
  2871. this.owner.trigger( 'fileDequeued', file );
  2872. },
  2873. /**
  2874. * 判断`Uplaode`r是否正在上传中。
  2875. * @grammar isInProgress() => Boolean
  2876. * @method isInProgress
  2877. * @for Uploader
  2878. */
  2879. isInProgress: function() {
  2880. return !!this.progress;
  2881. },
  2882. _getStats: function() {
  2883. return this.request('get-stats');
  2884. },
  2885. /**
  2886. * 掉过一个文件上传,直接标记指定文件为已上传状态。
  2887. * @grammar skipFile( file ) => undefined
  2888. * @method skipFile
  2889. * @for Uploader
  2890. */
  2891. skipFile: function( file, status ) {
  2892. file = file.id ? file : this.request( 'get-file', file );
  2893. file.setStatus( status || Status.COMPLETE );
  2894. file.skipped = true;
  2895. // 如果正在上传。
  2896. file.blocks && $.each( file.blocks, function( _, v ) {
  2897. var _tr = v.transport;
  2898. if ( _tr ) {
  2899. _tr.abort();
  2900. _tr.destroy();
  2901. delete v.transport;
  2902. }
  2903. });
  2904. this.owner.trigger( 'uploadSkip', file );
  2905. },
  2906. /**
  2907. * @event uploadFinished
  2908. * @description 当所有文件上传结束时触发。
  2909. * @for Uploader
  2910. */
  2911. _tick: function() {
  2912. var me = this,
  2913. opts = me.options,
  2914. fn, val;
  2915. // 上一个promise还没有结束,则等待完成后再执行。
  2916. if ( me._promise ) {
  2917. return me._promise.always( me.__tick );
  2918. }
  2919. // 还有位置,且还有文件要处理的话。
  2920. if ( me.pool.length < opts.threads && (val = me._nextBlock()) ) {
  2921. me._trigged = false;
  2922. fn = function( val ) {
  2923. me._promise = null;
  2924. // 有可能是reject过来的,所以要检测val的类型。
  2925. val && val.file && me._startSend( val );
  2926. Base.nextTick( me.__tick );
  2927. };
  2928. me._promise = isPromise( val ) ? val.always( fn ) : fn( val );
  2929. // 没有要上传的了,且没有正在传输的了。
  2930. } else if ( !me.remaning && !me._getStats().numOfQueue &&
  2931. !me._getStats().numofInterrupt ) {
  2932. me.runing = false;
  2933. me._trigged || Base.nextTick(function() {
  2934. me.owner.trigger('uploadFinished');
  2935. });
  2936. me._trigged = true;
  2937. }
  2938. },
  2939. _putback: function(block) {
  2940. var idx;
  2941. block.cuted.unshift(block);
  2942. idx = this.stack.indexOf(block.cuted);
  2943. if (!~idx) {
  2944. this.stack.unshift(block.cuted);
  2945. }
  2946. },
  2947. _getStack: function() {
  2948. var i = 0,
  2949. act;
  2950. while ( (act = this.stack[ i++ ]) ) {
  2951. if ( act.has() && act.file.getStatus() === Status.PROGRESS ) {
  2952. return act;
  2953. } else if (!act.has() ||
  2954. act.file.getStatus() !== Status.PROGRESS &&
  2955. act.file.getStatus() !== Status.INTERRUPT ) {
  2956. // 把已经处理完了的,或者,状态为非 progress(上传中)、
  2957. // interupt(暂停中) 的移除。
  2958. this.stack.splice( --i, 1 );
  2959. }
  2960. }
  2961. return null;
  2962. },
  2963. _nextBlock: function() {
  2964. var me = this,
  2965. opts = me.options,
  2966. act, next, done, preparing;
  2967. // 如果当前文件还有没有需要传输的,则直接返回剩下的。
  2968. if ( (act = this._getStack()) ) {
  2969. // 是否提前准备下一个文件
  2970. if ( opts.prepareNextFile && !me.pending.length ) {
  2971. me._prepareNextFile();
  2972. }
  2973. return act.shift();
  2974. // 否则,如果正在运行,则准备下一个文件,并等待完成后返回下个分片。
  2975. } else if ( me.runing ) {
  2976. // 如果缓存中有,则直接在缓存中取,没有则去queue中取。
  2977. if ( !me.pending.length && me._getStats().numOfQueue ) {
  2978. me._prepareNextFile();
  2979. }
  2980. next = me.pending.shift();
  2981. done = function( file ) {
  2982. if ( !file ) {
  2983. return null;
  2984. }
  2985. act = CuteFile( file, opts.chunked ? opts.chunkSize : 0 );
  2986. me.stack.push(act);
  2987. return act.shift();
  2988. };
  2989. // 文件可能还在prepare中,也有可能已经完全准备好了。
  2990. if ( isPromise( next) ) {
  2991. preparing = next.file;
  2992. next = next[ next.pipe ? 'pipe' : 'then' ]( done );
  2993. next.file = preparing;
  2994. return next;
  2995. }
  2996. return done( next );
  2997. }
  2998. },
  2999. /**
  3000. * @event uploadStart
  3001. * @param {File} file File对象
  3002. * @description 某个文件开始上传前触发,一个文件只会触发一次。
  3003. * @for Uploader
  3004. */
  3005. _prepareNextFile: function() {
  3006. var me = this,
  3007. file = me.request('fetch-file'),
  3008. pending = me.pending,
  3009. promise;
  3010. if ( file ) {
  3011. promise = me.request( 'before-send-file', file, function() {
  3012. // 有可能文件被skip掉了。文件被skip掉后,状态坑定不是Queued.
  3013. if ( file.getStatus() === Status.PROGRESS ||
  3014. file.getStatus() === Status.INTERRUPT ) {
  3015. return file;
  3016. }
  3017. return me._finishFile( file );
  3018. });
  3019. me.owner.trigger( 'uploadStart', file );
  3020. file.setStatus( Status.PROGRESS );
  3021. promise.file = file;
  3022. // 如果还在pending中,则替换成文件本身。
  3023. promise.done(function() {
  3024. var idx = $.inArray( promise, pending );
  3025. ~idx && pending.splice( idx, 1, file );
  3026. });
  3027. // befeore-send-file的钩子就有错误发生。
  3028. promise.fail(function( reason ) {
  3029. file.setStatus( Status.ERROR, reason );
  3030. me.owner.trigger( 'uploadError', file, reason );
  3031. me.owner.trigger( 'uploadComplete', file );
  3032. });
  3033. pending.push( promise );
  3034. }
  3035. },
  3036. // 让出位置了,可以让其他分片开始上传
  3037. _popBlock: function( block ) {
  3038. var idx = $.inArray( block, this.pool );
  3039. this.pool.splice( idx, 1 );
  3040. block.file.remaning--;
  3041. this.remaning--;
  3042. },
  3043. // 开始上传,可以被掉过。如果promise被reject了,则表示跳过此分片。
  3044. _startSend: function( block ) {
  3045. var me = this,
  3046. file = block.file,
  3047. promise;
  3048. // 有可能在 before-send-file 的 promise 期间改变了文件状态。
  3049. // 如:暂停,取消
  3050. // 我们不能中断 promise, 但是可以在 promise 完后,不做上传操作。
  3051. if ( file.getStatus() !== Status.PROGRESS ) {
  3052. // 如果是中断,则还需要放回去。
  3053. if (file.getStatus() === Status.INTERRUPT) {
  3054. me._putback(block);
  3055. }
  3056. return;
  3057. }
  3058. me.pool.push( block );
  3059. me.remaning++;
  3060. // 如果没有分片,则直接使用原始的。
  3061. // 不会丢失content-type信息。
  3062. block.blob = block.chunks === 1 ? file.source :
  3063. file.source.slice( block.start, block.end );
  3064. // hook, 每个分片发送之前可能要做些异步的事情。
  3065. promise = me.request( 'before-send', block, function() {
  3066. // 有可能文件已经上传出错了,所以不需要再传输了。
  3067. if ( file.getStatus() === Status.PROGRESS ) {
  3068. me._doSend( block );
  3069. } else {
  3070. me._popBlock( block );
  3071. Base.nextTick( me.__tick );
  3072. }
  3073. });
  3074. // 如果为fail了,则跳过此分片。
  3075. promise.fail(function() {
  3076. if ( file.remaning === 1 ) {
  3077. me._finishFile( file ).always(function() {
  3078. block.percentage = 1;
  3079. me._popBlock( block );
  3080. me.owner.trigger( 'uploadComplete', file );
  3081. Base.nextTick( me.__tick );
  3082. });
  3083. } else {
  3084. block.percentage = 1;
  3085. me.updateFileProgress( file );
  3086. me._popBlock( block );
  3087. Base.nextTick( me.__tick );
  3088. }
  3089. });
  3090. },
  3091. /**
  3092. * @event uploadBeforeSend
  3093. * @param {Object} object
  3094. * @param {Object} data 默认的上传参数,可以扩展此对象来控制上传参数。
  3095. * @param {Object} headers 可以扩展此对象来控制上传头部。
  3096. * @description 当某个文件的分块在发送前触发,主要用来询问是否要添加附带参数,大文件在开起分片上传的前提下此事件可能会触发多次。
  3097. * @for Uploader
  3098. */
  3099. /**
  3100. * @event uploadAccept
  3101. * @param {Object} object
  3102. * @param {Object} ret 服务端的返回数据,json格式,如果服务端不是json格式,从ret._raw中取数据,自行解析。
  3103. * @description 当某个文件上传到服务端响应后,会派送此事件来询问服务端响应是否有效。如果此事件handler返回值为`false`, 则此文件将派送`server`类型的`uploadError`事件。
  3104. * @for Uploader
  3105. */
  3106. /**
  3107. * @event uploadProgress
  3108. * @param {File} file File对象
  3109. * @param {Number} percentage 上传进度
  3110. * @description 上传过程中触发,携带上传进度。
  3111. * @for Uploader
  3112. */
  3113. /**
  3114. * @event uploadError
  3115. * @param {File} file File对象
  3116. * @param {String} reason 出错的code
  3117. * @description 当文件上传出错时触发。
  3118. * @for Uploader
  3119. */
  3120. /**
  3121. * @event uploadSuccess
  3122. * @param {File} file File对象
  3123. * @param {Object} response 服务端返回的数据
  3124. * @description 当文件上传成功时触发。
  3125. * @for Uploader
  3126. */
  3127. /**
  3128. * @event uploadComplete
  3129. * @param {File} [file] File对象
  3130. * @description 不管成功或者失败,文件上传完成时触发。
  3131. * @for Uploader
  3132. */
  3133. // 做上传操作。
  3134. _doSend: function( block ) {
  3135. var me = this,
  3136. owner = me.owner,
  3137. opts = me.options,
  3138. file = block.file,
  3139. tr = new Transport( opts ),
  3140. data = $.extend({}, opts.formData ),
  3141. headers = $.extend({}, opts.headers ),
  3142. requestAccept, ret;
  3143. block.transport = tr;
  3144. tr.on( 'destroy', function() {
  3145. delete block.transport;
  3146. me._popBlock( block );
  3147. Base.nextTick( me.__tick );
  3148. });
  3149. // 广播上传进度。以文件为单位。
  3150. tr.on( 'progress', function( percentage ) {
  3151. block.percentage = percentage;
  3152. me.updateFileProgress( file );
  3153. });
  3154. // 用来询问,是否返回的结果是有错误的。
  3155. requestAccept = function( reject ) {
  3156. var fn;
  3157. ret = tr.getResponseAsJson() || {};
  3158. ret._raw = tr.getResponse();
  3159. fn = function( value ) {
  3160. reject = value;
  3161. };
  3162. // 服务端响应了,不代表成功了,询问是否响应正确。
  3163. if ( !owner.trigger( 'uploadAccept', block, ret, fn ) ) {
  3164. reject = reject || 'server';
  3165. }
  3166. return reject;
  3167. };
  3168. // 尝试重试,然后广播文件上传出错。
  3169. tr.on( 'error', function( type, flag ) {
  3170. block.retried = block.retried || 0;
  3171. // 自动重试
  3172. if ( block.chunks > 1 && ~'http,abort'.indexOf( type ) &&
  3173. block.retried < opts.chunkRetry ) {
  3174. block.retried++;
  3175. tr.send();
  3176. } else {
  3177. // http status 500 ~ 600
  3178. if ( !flag && type === 'server' ) {
  3179. type = requestAccept( type );
  3180. }
  3181. file.setStatus( Status.ERROR, type );
  3182. owner.trigger( 'uploadError', file, type );
  3183. owner.trigger( 'uploadComplete', file );
  3184. }
  3185. });
  3186. // 上传成功
  3187. tr.on( 'load', function() {
  3188. var reason;
  3189. // 如果非预期,转向上传出错。
  3190. if ( (reason = requestAccept()) ) {
  3191. tr.trigger( 'error', reason, true );
  3192. return;
  3193. }
  3194. // 全部上传完成。
  3195. if ( file.remaning === 1 ) {
  3196. me._finishFile( file, ret );
  3197. } else {
  3198. tr.destroy();
  3199. }
  3200. });
  3201. // 配置默认的上传字段。
  3202. data = $.extend( data, {
  3203. id: file.id,
  3204. name: file.name,
  3205. type: file.type,
  3206. lastModifiedDate: file.lastModifiedDate,
  3207. size: file.size
  3208. });
  3209. block.chunks > 1 && $.extend( data, {
  3210. chunks: block.chunks,
  3211. chunk: block.chunk
  3212. });
  3213. // 在发送之间可以添加字段什么的。。。
  3214. // 如果默认的字段不够使用,可以通过监听此事件来扩展
  3215. owner.trigger( 'uploadBeforeSend', block, data, headers );
  3216. // 开始发送。
  3217. tr.appendBlob( opts.fileVal, block.blob, file.name );
  3218. tr.append( data );
  3219. tr.setRequestHeader( headers );
  3220. tr.send();
  3221. },
  3222. // 完成上传。
  3223. _finishFile: function( file, ret, hds ) {
  3224. var owner = this.owner;
  3225. return owner
  3226. .request( 'after-send-file', arguments, function() {
  3227. file.setStatus( Status.COMPLETE );
  3228. owner.trigger( 'uploadSuccess', file, ret, hds );
  3229. })
  3230. .fail(function( reason ) {
  3231. // 如果外部已经标记为invalid什么的,不再改状态。
  3232. if ( file.getStatus() === Status.PROGRESS ) {
  3233. file.setStatus( Status.ERROR, reason );
  3234. }
  3235. owner.trigger( 'uploadError', file, reason );
  3236. })
  3237. .always(function() {
  3238. owner.trigger( 'uploadComplete', file );
  3239. });
  3240. },
  3241. updateFileProgress: function(file) {
  3242. var totalPercent = 0,
  3243. uploaded = 0;
  3244. if (!file.blocks) {
  3245. return;
  3246. }
  3247. $.each( file.blocks, function( _, v ) {
  3248. uploaded += (v.percentage || 0) * (v.end - v.start);
  3249. });
  3250. totalPercent = uploaded / file.size;
  3251. this.owner.trigger( 'uploadProgress', file, totalPercent || 0 );
  3252. }
  3253. });
  3254. });
  3255. /**
  3256. * @fileOverview 各种验证,包括文件总大小是否超出、单文件是否超出和文件是否重复。
  3257. */
  3258. define('widgets/validator',[
  3259. 'base',
  3260. 'uploader',
  3261. 'file',
  3262. 'widgets/widget'
  3263. ], function( Base, Uploader, WUFile ) {
  3264. var $ = Base.$,
  3265. validators = {},
  3266. api;
  3267. /**
  3268. * @event error
  3269. * @param {String} type 错误类型。
  3270. * @description 当validate不通过时,会以派送错误事件的形式通知调用者。通过`upload.on('error', handler)`可以捕获到此类错误,目前有以下错误会在特定的情况下派送错来。
  3271. *
  3272. * * `Q_EXCEED_NUM_LIMIT` 在设置了`fileNumLimit`且尝试给`uploader`添加的文件数量超出这个值时派送。
  3273. * * `Q_EXCEED_SIZE_LIMIT` 在设置了`Q_EXCEED_SIZE_LIMIT`且尝试给`uploader`添加的文件总大小超出这个值时派送。
  3274. * * `Q_TYPE_DENIED` 当文件类型不满足时触发。。
  3275. * @for Uploader
  3276. */
  3277. // 暴露给外面的api
  3278. api = {
  3279. // 添加验证器
  3280. addValidator: function( type, cb ) {
  3281. validators[ type ] = cb;
  3282. },
  3283. // 移除验证器
  3284. removeValidator: function( type ) {
  3285. delete validators[ type ];
  3286. }
  3287. };
  3288. // 在Uploader初始化的时候启动Validators的初始化
  3289. Uploader.register({
  3290. name: 'validator',
  3291. init: function() {
  3292. var me = this;
  3293. Base.nextTick(function() {
  3294. $.each( validators, function() {
  3295. this.call( me.owner );
  3296. });
  3297. });
  3298. }
  3299. });
  3300. /**
  3301. * @property {int} [fileNumLimit=undefined]
  3302. * @namespace options
  3303. * @for Uploader
  3304. * @description 验证文件总数量, 超出则不允许加入队列。
  3305. */
  3306. api.addValidator( 'fileNumLimit', function() {
  3307. var uploader = this,
  3308. opts = uploader.options,
  3309. count = 0,
  3310. max = parseInt( opts.fileNumLimit, 10 ),
  3311. flag = true;
  3312. if ( !max ) {
  3313. return;
  3314. }
  3315. uploader.on( 'beforeFileQueued', function( file ) {
  3316. if ( count >= max && flag ) {
  3317. flag = false;
  3318. this.trigger( 'error', 'Q_EXCEED_NUM_LIMIT', max, file );
  3319. setTimeout(function() {
  3320. flag = true;
  3321. }, 1 );
  3322. }
  3323. return count >= max ? false : true;
  3324. });
  3325. uploader.on( 'fileQueued', function() {
  3326. count++;
  3327. });
  3328. uploader.on( 'fileDequeued', function() {
  3329. count--;
  3330. });
  3331. uploader.on( 'reset', function() {
  3332. count = 0;
  3333. });
  3334. });
  3335. /**
  3336. * @property {int} [fileSizeLimit=undefined]
  3337. * @namespace options
  3338. * @for Uploader
  3339. * @description 验证文件总大小是否超出限制, 超出则不允许加入队列。
  3340. */
  3341. api.addValidator( 'fileSizeLimit', function() {
  3342. var uploader = this,
  3343. opts = uploader.options,
  3344. count = 0,
  3345. max = parseInt( opts.fileSizeLimit, 10 ),
  3346. flag = true;
  3347. if ( !max ) {
  3348. return;
  3349. }
  3350. uploader.on( 'beforeFileQueued', function( file ) {
  3351. var invalid = count + file.size > max;
  3352. if ( invalid && flag ) {
  3353. flag = false;
  3354. this.trigger( 'error', 'Q_EXCEED_SIZE_LIMIT', max, file );
  3355. setTimeout(function() {
  3356. flag = true;
  3357. }, 1 );
  3358. }
  3359. return invalid ? false : true;
  3360. });
  3361. uploader.on( 'fileQueued', function( file ) {
  3362. count += file.size;
  3363. });
  3364. uploader.on( 'fileDequeued', function( file ) {
  3365. count -= file.size;
  3366. });
  3367. uploader.on( 'reset', function() {
  3368. count = 0;
  3369. });
  3370. });
  3371. /**
  3372. * @property {int} [fileSingleSizeLimit=undefined]
  3373. * @namespace options
  3374. * @for Uploader
  3375. * @description 验证单个文件大小是否超出限制, 超出则不允许加入队列。
  3376. */
  3377. api.addValidator( 'fileSingleSizeLimit', function() {
  3378. var uploader = this,
  3379. opts = uploader.options,
  3380. max = opts.fileSingleSizeLimit;
  3381. if ( !max ) {
  3382. return;
  3383. }
  3384. uploader.on( 'beforeFileQueued', function( file ) {
  3385. if ( file.size > max ) {
  3386. file.setStatus( WUFile.Status.INVALID, 'exceed_size' );
  3387. this.trigger( 'error', 'F_EXCEED_SIZE', max, file );
  3388. return false;
  3389. }
  3390. });
  3391. });
  3392. /**
  3393. * @property {Boolean} [duplicate=undefined]
  3394. * @namespace options
  3395. * @for Uploader
  3396. * @description 去重, 根据文件名字、文件大小和最后修改时间来生成hash Key.
  3397. */
  3398. api.addValidator( 'duplicate', function() {
  3399. var uploader = this,
  3400. opts = uploader.options,
  3401. mapping = {};
  3402. if ( opts.duplicate ) {
  3403. return;
  3404. }
  3405. function hashString( str ) {
  3406. var hash = 0,
  3407. i = 0,
  3408. len = str.length,
  3409. _char;
  3410. for ( ; i < len; i++ ) {
  3411. _char = str.charCodeAt( i );
  3412. hash = _char + (hash << 6) + (hash << 16) - hash;
  3413. }
  3414. return hash;
  3415. }
  3416. uploader.on( 'beforeFileQueued', function( file ) {
  3417. var hash = file.__hash || (file.__hash = hashString( file.name +
  3418. file.size + file.lastModifiedDate ));
  3419. // 已经重复了
  3420. if ( mapping[ hash ] ) {
  3421. this.trigger( 'error', 'F_DUPLICATE', file );
  3422. return false;
  3423. }
  3424. });
  3425. uploader.on( 'fileQueued', function( file ) {
  3426. var hash = file.__hash;
  3427. hash && (mapping[ hash ] = true);
  3428. });
  3429. uploader.on( 'fileDequeued', function( file ) {
  3430. var hash = file.__hash;
  3431. hash && (delete mapping[ hash ]);
  3432. });
  3433. uploader.on( 'reset', function() {
  3434. mapping = {};
  3435. });
  3436. });
  3437. return api;
  3438. });
  3439. /**
  3440. * @fileOverview Runtime管理器,负责Runtime的选择, 连接
  3441. */
  3442. define('runtime/compbase',[],function() {
  3443. function CompBase( owner, runtime ) {
  3444. this.owner = owner;
  3445. this.options = owner.options;
  3446. this.getRuntime = function() {
  3447. return runtime;
  3448. };
  3449. this.getRuid = function() {
  3450. return runtime.uid;
  3451. };
  3452. this.trigger = function() {
  3453. return owner.trigger.apply( owner, arguments );
  3454. };
  3455. }
  3456. return CompBase;
  3457. });
  3458. /**
  3459. * @fileOverview FlashRuntime
  3460. */
  3461. define('runtime/flash/runtime',[
  3462. 'base',
  3463. 'runtime/runtime',
  3464. 'runtime/compbase'
  3465. ], function( Base, Runtime, CompBase ) {
  3466. var $ = Base.$,
  3467. type = 'flash',
  3468. components = {};
  3469. function getFlashVersion() {
  3470. var version;
  3471. try {
  3472. version = navigator.plugins[ 'Shockwave Flash' ];
  3473. version = version.description;
  3474. } catch ( ex ) {
  3475. try {
  3476. version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash')
  3477. .GetVariable('$version');
  3478. } catch ( ex2 ) {
  3479. version = '0.0';
  3480. }
  3481. }
  3482. version = version.match( /\d+/g );
  3483. return parseFloat( version[ 0 ] + '.' + version[ 1 ], 10 );
  3484. }
  3485. function FlashRuntime() {
  3486. var pool = {},
  3487. clients = {},
  3488. destroy = this.destroy,
  3489. me = this,
  3490. jsreciver = Base.guid('webuploader_');
  3491. Runtime.apply( me, arguments );
  3492. me.type = type;
  3493. // 这个方法的调用者,实际上是RuntimeClient
  3494. me.exec = function( comp, fn/*, args...*/ ) {
  3495. var client = this,
  3496. uid = client.uid,
  3497. args = Base.slice( arguments, 2 ),
  3498. instance;
  3499. clients[ uid ] = client;
  3500. if ( components[ comp ] ) {
  3501. if ( !pool[ uid ] ) {
  3502. pool[ uid ] = new components[ comp ]( client, me );
  3503. }
  3504. instance = pool[ uid ];
  3505. if ( instance[ fn ] ) {
  3506. return instance[ fn ].apply( instance, args );
  3507. }
  3508. }
  3509. return me.flashExec.apply( client, arguments );
  3510. };
  3511. function handler( evt, obj ) {
  3512. var type = evt.type || evt,
  3513. parts, uid;
  3514. parts = type.split('::');
  3515. uid = parts[ 0 ];
  3516. type = parts[ 1 ];
  3517. // console.log.apply( console, arguments );
  3518. if ( type === 'Ready' && uid === me.uid ) {
  3519. me.trigger('ready');
  3520. } else if ( clients[ uid ] ) {
  3521. clients[ uid ].trigger( type.toLowerCase(), evt, obj );
  3522. }
  3523. // Base.log( evt, obj );
  3524. }
  3525. // flash的接受器。
  3526. window[ jsreciver ] = function() {
  3527. var args = arguments;
  3528. // 为了能捕获得到。
  3529. setTimeout(function() {
  3530. handler.apply( null, args );
  3531. }, 1 );
  3532. };
  3533. this.jsreciver = jsreciver;
  3534. this.destroy = function() {
  3535. // @todo 删除池子中的所有实例
  3536. return destroy && destroy.apply( this, arguments );
  3537. };
  3538. this.flashExec = function( comp, fn ) {
  3539. var flash = me.getFlash(),
  3540. args = Base.slice( arguments, 2 );
  3541. return flash.exec( this.uid, comp, fn, args );
  3542. };
  3543. // @todo
  3544. }
  3545. Base.inherits( Runtime, {
  3546. constructor: FlashRuntime,
  3547. init: function() {
  3548. var container = this.getContainer(),
  3549. opts = this.options,
  3550. html;
  3551. // if not the minimal height, shims are not initialized
  3552. // in older browsers (e.g FF3.6, IE6,7,8, Safari 4.0,5.0, etc)
  3553. container.css({
  3554. position: 'absolute',
  3555. top: '-8px',
  3556. left: '-8px',
  3557. width: '9px',
  3558. height: '9px',
  3559. overflow: 'hidden'
  3560. });
  3561. // insert flash object
  3562. html = '<object id="' + this.uid + '" type="application/' +
  3563. 'x-shockwave-flash" data="' + opts.swf + '" ';
  3564. if ( Base.browser.ie ) {
  3565. html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
  3566. }
  3567. html += 'width="100%" height="100%" style="outline:0">' +
  3568. '<param name="movie" value="' + opts.swf + '" />' +
  3569. '<param name="flashvars" value="uid=' + this.uid +
  3570. '&jsreciver=' + this.jsreciver + '" />' +
  3571. '<param name="wmode" value="transparent" />' +
  3572. '<param name="allowscriptaccess" value="always" />' +
  3573. '</object>';
  3574. container.html( html );
  3575. },
  3576. getFlash: function() {
  3577. if ( this._flash ) {
  3578. return this._flash;
  3579. }
  3580. this._flash = $( '#' + this.uid ).get( 0 );
  3581. return this._flash;
  3582. }
  3583. });
  3584. FlashRuntime.register = function( name, component ) {
  3585. component = components[ name ] = Base.inherits( CompBase, $.extend({
  3586. // @todo fix this later
  3587. flashExec: function() {
  3588. var owner = this.owner,
  3589. runtime = this.getRuntime();
  3590. return runtime.flashExec.apply( owner, arguments );
  3591. }
  3592. }, component ) );
  3593. return component;
  3594. };
  3595. if ( getFlashVersion() >= 11.4 ) {
  3596. Runtime.addRuntime( type, FlashRuntime );
  3597. }
  3598. return FlashRuntime;
  3599. });
  3600. /**
  3601. * @fileOverview FilePicker
  3602. */
  3603. define('runtime/flash/filepicker',[
  3604. 'base',
  3605. 'runtime/flash/runtime'
  3606. ], function( Base, FlashRuntime ) {
  3607. var $ = Base.$;
  3608. return FlashRuntime.register( 'FilePicker', {
  3609. init: function( opts ) {
  3610. var copy = $.extend({}, opts ),
  3611. len, i;
  3612. // 修复Flash再没有设置title的情况下无法弹出flash文件选择框的bug.
  3613. len = copy.accept && copy.accept.length;
  3614. for ( i = 0; i < len; i++ ) {
  3615. if ( !copy.accept[ i ].title ) {
  3616. copy.accept[ i ].title = 'Files';
  3617. }
  3618. }
  3619. delete copy.button;
  3620. delete copy.id;
  3621. delete copy.container;
  3622. this.flashExec( 'FilePicker', 'init', copy );
  3623. },
  3624. destroy: function() {
  3625. this.flashExec( 'FilePicker', 'destroy' );
  3626. }
  3627. });
  3628. });
  3629. /**
  3630. * @fileOverview 图片压缩
  3631. */
  3632. define('runtime/flash/image',[
  3633. 'runtime/flash/runtime'
  3634. ], function( FlashRuntime ) {
  3635. return FlashRuntime.register( 'Image', {
  3636. // init: function( options ) {
  3637. // var owner = this.owner;
  3638. // this.flashExec( 'Image', 'init', options );
  3639. // owner.on( 'load', function() {
  3640. // debugger;
  3641. // });
  3642. // },
  3643. loadFromBlob: function( blob ) {
  3644. var owner = this.owner;
  3645. owner.info() && this.flashExec( 'Image', 'info', owner.info() );
  3646. owner.meta() && this.flashExec( 'Image', 'meta', owner.meta() );
  3647. this.flashExec( 'Image', 'loadFromBlob', blob.uid );
  3648. }
  3649. });
  3650. });
  3651. /**
  3652. * @fileOverview Blob Html实现
  3653. */
  3654. define('runtime/flash/blob',[
  3655. 'runtime/flash/runtime',
  3656. 'lib/blob'
  3657. ], function( FlashRuntime, Blob ) {
  3658. return FlashRuntime.register( 'Blob', {
  3659. slice: function( start, end ) {
  3660. var blob = this.flashExec( 'Blob', 'slice', start, end );
  3661. return new Blob( blob.uid, blob );
  3662. }
  3663. });
  3664. });
  3665. /**
  3666. * @fileOverview Transport flash实现
  3667. */
  3668. define('runtime/flash/transport',[
  3669. 'base',
  3670. 'runtime/flash/runtime',
  3671. 'runtime/client'
  3672. ], function( Base, FlashRuntime, RuntimeClient ) {
  3673. var $ = Base.$;
  3674. return FlashRuntime.register( 'Transport', {
  3675. init: function() {
  3676. this._status = 0;
  3677. this._response = null;
  3678. this._responseJson = null;
  3679. },
  3680. send: function() {
  3681. var owner = this.owner,
  3682. opts = this.options,
  3683. xhr = this._initAjax(),
  3684. blob = owner._blob,
  3685. server = opts.server,
  3686. binary;
  3687. xhr.connectRuntime( blob.ruid );
  3688. if ( opts.sendAsBinary ) {
  3689. server += (/\?/.test( server ) ? '&' : '?') +
  3690. $.param( owner._formData );
  3691. binary = blob.uid;
  3692. } else {
  3693. $.each( owner._formData, function( k, v ) {
  3694. xhr.exec( 'append', k, v );
  3695. });
  3696. xhr.exec( 'appendBlob', opts.fileVal, blob.uid,
  3697. opts.filename || owner._formData.name || '' );
  3698. }
  3699. this._setRequestHeader( xhr, opts.headers );
  3700. xhr.exec( 'send', {
  3701. method: opts.method,
  3702. url: server,
  3703. forceURLStream: opts.forceURLStream,
  3704. mimeType: 'application/octet-stream'
  3705. }, binary );
  3706. },
  3707. getStatus: function() {
  3708. return this._status;
  3709. },
  3710. getResponse: function() {
  3711. return this._response || '';
  3712. },
  3713. getResponseAsJson: function() {
  3714. return this._responseJson;
  3715. },
  3716. abort: function() {
  3717. var xhr = this._xhr;
  3718. if ( xhr ) {
  3719. xhr.exec('abort');
  3720. xhr.destroy();
  3721. this._xhr = xhr = null;
  3722. }
  3723. },
  3724. destroy: function() {
  3725. this.abort();
  3726. },
  3727. _initAjax: function() {
  3728. var me = this,
  3729. xhr = new RuntimeClient('XMLHttpRequest');
  3730. xhr.on( 'uploadprogress progress', function( e ) {
  3731. var percent = e.loaded / e.total;
  3732. percent = Math.min( 1, Math.max( 0, percent ) );
  3733. return me.trigger( 'progress', percent );
  3734. });
  3735. xhr.on( 'load', function() {
  3736. var status = xhr.exec('getStatus'),
  3737. readBody = false,
  3738. err = '',
  3739. p;
  3740. xhr.off();
  3741. me._xhr = null;
  3742. if ( status >= 200 && status < 300 ) {
  3743. readBody = true;
  3744. } else if ( status >= 500 && status < 600 ) {
  3745. readBody = true;
  3746. err = 'server';
  3747. } else {
  3748. err = 'http';
  3749. }
  3750. if ( readBody ) {
  3751. me._response = xhr.exec('getResponse');
  3752. me._response = decodeURIComponent( me._response );
  3753. // flash 处理可能存在 bug, 没辙只能靠 js 了
  3754. // try {
  3755. // me._responseJson = xhr.exec('getResponseAsJson');
  3756. // } catch ( error ) {
  3757. p = window.JSON && window.JSON.parse || function( s ) {
  3758. try {
  3759. return new Function('return ' + s).call();
  3760. } catch ( err ) {
  3761. return {};
  3762. }
  3763. };
  3764. me._responseJson = me._response ? p(me._response) : {};
  3765. // }
  3766. }
  3767. xhr.destroy();
  3768. xhr = null;
  3769. return err ? me.trigger( 'error', err ) : me.trigger('load');
  3770. });
  3771. xhr.on( 'error', function() {
  3772. xhr.off();
  3773. me._xhr = null;
  3774. me.trigger( 'error', 'http' );
  3775. });
  3776. me._xhr = xhr;
  3777. return xhr;
  3778. },
  3779. _setRequestHeader: function( xhr, headers ) {
  3780. $.each( headers, function( key, val ) {
  3781. xhr.exec( 'setRequestHeader', key, val );
  3782. });
  3783. }
  3784. });
  3785. });
  3786. /**
  3787. * @fileOverview 只有flash实现的文件版本。
  3788. */
  3789. define('preset/flashonly',[
  3790. 'base',
  3791. // widgets
  3792. 'widgets/filepicker',
  3793. 'widgets/image',
  3794. 'widgets/queue',
  3795. 'widgets/runtime',
  3796. 'widgets/upload',
  3797. 'widgets/validator',
  3798. // runtimes
  3799. // flash
  3800. 'runtime/flash/filepicker',
  3801. 'runtime/flash/image',
  3802. 'runtime/flash/blob',
  3803. 'runtime/flash/transport'
  3804. ], function( Base ) {
  3805. return Base;
  3806. });
  3807. define('webuploader',[
  3808. 'preset/flashonly'
  3809. ], function( preset ) {
  3810. return preset;
  3811. });
  3812. return require('webuploader');
  3813. });