webuploader.flashonly.js 136 KB

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