webuploader.withoutimage.js 148KB

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