webuploader.withoutimage.js 143 KB

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