三元财务UI

webuploader.noimage.js 167KB

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