webuploader.withoutimage.js 120 KB

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