webuploader.withoutimage.js 157 KB

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