webuploader.withoutimage.js 148 KB

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