webuploader.flashonly.js 131 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178
  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 Blob
  953. */
  954. define('lib/blob', [
  955. 'base',
  956. 'runtime/client'
  957. ], function (Base, RuntimeClient) {
  958. function Blob(ruid, source) {
  959. var me = this;
  960. me.source = source;
  961. me.ruid = ruid;
  962. RuntimeClient.call(me, 'Blob');
  963. this.uid = source.uid || this.uid;
  964. this.type = source.type || '';
  965. this.size = source.size || 0;
  966. if (ruid) {
  967. me.connectRuntime(ruid);
  968. }
  969. }
  970. Base.inherits(RuntimeClient, {
  971. constructor: Blob,
  972. slice: function (start, end) {
  973. return this.exec('slice', start, end);
  974. },
  975. getSource: function () {
  976. return this.source;
  977. }
  978. });
  979. return Blob;
  980. });
  981. /**
  982. * 为了统一化Flash的File和HTML5的File而存在。
  983. * 以至于要调用Flash里面的File,也可以像调用HTML5版本的File一下。
  984. * @fileOverview File
  985. */
  986. define('lib/file', [
  987. 'base',
  988. 'lib/blob'
  989. ], function (Base, Blob) {
  990. var uid = 1,
  991. rExt = /\.([^.]+)$/;
  992. function File(ruid, file) {
  993. var ext;
  994. Blob.apply(this, arguments);
  995. this.name = file.name || ('untitled' + uid++);
  996. ext = rExt.exec(file.name) ? RegExp.$1.toLowerCase() : '';
  997. // todo 支持其他类型文件的转换。
  998. // 如果有mimetype, 但是文件名里面没有找出后缀规律
  999. if (!ext && this.type) {
  1000. ext = /\/(jpg|jpeg|png|gif|bmp)$/i.exec(this.type) ?
  1001. RegExp.$1.toLowerCase() : '';
  1002. this.name += '.' + ext;
  1003. }
  1004. // 如果没有指定mimetype, 但是知道文件后缀。
  1005. if (!this.type && ~'jpg,jpeg,png,gif,bmp'.indexOf(ext)) {
  1006. this.type = 'image/' + (ext === 'jpg' ? 'jpeg' : ext);
  1007. }
  1008. this.ext = ext;
  1009. this.lastModifiedDate = file.lastModifiedDate ||
  1010. (new Date()).toLocaleString();
  1011. }
  1012. return Base.inherits(Blob, File);
  1013. });
  1014. /**
  1015. * @fileOverview 错误信息
  1016. */
  1017. define('lib/filepicker', [
  1018. 'base',
  1019. 'runtime/client',
  1020. 'lib/file'
  1021. ], function (Base, RuntimeClent, File) {
  1022. var $ = Base.$;
  1023. function FilePicker(opts) {
  1024. opts = this.options = $.extend({}, FilePicker.options, opts);
  1025. opts.container = $(opts.id);
  1026. if (!opts.container.length) {
  1027. throw new Error('按钮指定错误');
  1028. }
  1029. opts.innerHTML = opts.innerHTML || opts.label ||
  1030. opts.container.html() || '';
  1031. opts.button = $(opts.button || document.createElement('div'));
  1032. opts.button.html(opts.innerHTML);
  1033. opts.container.html(opts.button);
  1034. RuntimeClent.call(this, 'FilePicker', true);
  1035. }
  1036. FilePicker.options = {
  1037. button: null,
  1038. container: null,
  1039. label: null,
  1040. innerHTML: null,
  1041. multiple: true,
  1042. accept: null,
  1043. name: 'file'
  1044. };
  1045. Base.inherits(RuntimeClent, {
  1046. constructor: FilePicker,
  1047. init: function () {
  1048. var me = this,
  1049. opts = me.options,
  1050. button = opts.button;
  1051. button.addClass('webuploader-pick');
  1052. me.on('all', function (type) {
  1053. var files;
  1054. switch (type) {
  1055. case 'mouseenter':
  1056. button.addClass('webuploader-pick-hover');
  1057. break;
  1058. case 'mouseleave':
  1059. button.removeClass('webuploader-pick-hover');
  1060. break;
  1061. case 'change':
  1062. files = me.exec('getFiles');
  1063. me.trigger('select', $.map(files, function (file) {
  1064. file = new File(me.getRuid(), file);
  1065. // 记录来源。
  1066. file._refer = opts.container;
  1067. return file;
  1068. }), opts.container);
  1069. break;
  1070. }
  1071. });
  1072. me.connectRuntime(opts, function () {
  1073. me.refresh();
  1074. me.exec('init', opts);
  1075. me.trigger('ready');
  1076. });
  1077. $(window).on('resize', function () {
  1078. me.refresh();
  1079. });
  1080. },
  1081. refresh: function () {
  1082. var shimContainer = this.getRuntime().getContainer(),
  1083. button = this.options.button,
  1084. width = button.outerWidth ?
  1085. button.outerWidth() : button.width(),
  1086. height = button.outerHeight ?
  1087. button.outerHeight() : button.height(),
  1088. pos = button.offset();
  1089. width && height && shimContainer.css({
  1090. bottom: 'auto',
  1091. right: 'auto',
  1092. width: width + 'px',
  1093. height: height + 'px'
  1094. }).offset(pos);
  1095. },
  1096. enable: function () {
  1097. var btn = this.options.button;
  1098. btn.removeClass('webuploader-pick-disable');
  1099. this.refresh();
  1100. },
  1101. disable: function () {
  1102. var btn = this.options.button;
  1103. this.getRuntime().getContainer().css({
  1104. top: '-99999px'
  1105. });
  1106. btn.addClass('webuploader-pick-disable');
  1107. },
  1108. destroy: function () {
  1109. if (this.runtime) {
  1110. this.exec('destroy');
  1111. this.disconnectRuntime();
  1112. }
  1113. }
  1114. });
  1115. return FilePicker;
  1116. });
  1117. /**
  1118. * @fileOverview 组件基类。
  1119. */
  1120. define('widgets/widget', [
  1121. 'base',
  1122. 'uploader'
  1123. ], function (Base, Uploader) {
  1124. var $ = Base.$,
  1125. _init = Uploader.prototype._init,
  1126. IGNORE = {},
  1127. widgetClass = [];
  1128. function isArrayLike(obj) {
  1129. if (!obj) {
  1130. return false;
  1131. }
  1132. var length = obj.length,
  1133. type = $.type(obj);
  1134. if (obj.nodeType === 1 && length) {
  1135. return true;
  1136. }
  1137. return type === 'array' || type !== 'function' && type !== 'string' &&
  1138. (length === 0 || typeof length === 'number' && length > 0 &&
  1139. (length - 1) in obj);
  1140. }
  1141. function Widget(uploader) {
  1142. this.owner = uploader;
  1143. this.options = uploader.options;
  1144. }
  1145. $.extend(Widget.prototype, {
  1146. init: Base.noop,
  1147. // 类Backbone的事件监听声明,监听uploader实例上的事件
  1148. // widget直接无法监听事件,事件只能通过uploader来传递
  1149. invoke: function (apiName, args) {
  1150. /*
  1151. {
  1152. 'make-thumb': 'makeThumb'
  1153. }
  1154. */
  1155. var map = this.responseMap;
  1156. // 如果无API响应声明则忽略
  1157. if (!map || !(apiName in map) || !(map[apiName] in this) ||
  1158. !$.isFunction(this[map[apiName]])) {
  1159. return IGNORE;
  1160. }
  1161. return this[map[apiName]].apply(this, args);
  1162. },
  1163. /**
  1164. * 发送命令。当传入`callback`或者`handler`中返回`promise`时。返回一个当所有`handler`中的promise都完成后完成的新`promise`。
  1165. * @method request
  1166. * @grammar request( command, args ) => * | Promise
  1167. * @grammar request( command, args, callback ) => Promise
  1168. * @for Uploader
  1169. */
  1170. request: function () {
  1171. return this.owner.request.apply(this.owner, arguments);
  1172. }
  1173. });
  1174. // 扩展Uploader.
  1175. $.extend(Uploader.prototype, {
  1176. // 覆写_init用来初始化widgets
  1177. _init: function () {
  1178. var me = this,
  1179. widgets = me._widgets = [];
  1180. $.each(widgetClass, function (_, klass) {
  1181. widgets.push(new klass(me));
  1182. });
  1183. return _init.apply(me, arguments);
  1184. },
  1185. request: function (apiName, args, callback) {
  1186. var i = 0,
  1187. widgets = this._widgets,
  1188. len = widgets.length,
  1189. rlts = [],
  1190. dfds = [],
  1191. widget, rlt, promise, key;
  1192. args = isArrayLike(args) ? args : [args];
  1193. for (; i < len; i++) {
  1194. widget = widgets[i];
  1195. rlt = widget.invoke(apiName, args);
  1196. if (rlt !== IGNORE) {
  1197. // Deferred对象
  1198. if (Base.isPromise(rlt)) {
  1199. dfds.push(rlt);
  1200. } else {
  1201. rlts.push(rlt);
  1202. }
  1203. }
  1204. }
  1205. // 如果有callback,则用异步方式。
  1206. if (callback || dfds.length) {
  1207. promise = Base.when.apply(Base, dfds);
  1208. key = promise.pipe ? 'pipe' : 'then';
  1209. // 很重要不能删除。删除了会死循环。
  1210. // 保证执行顺序。让callback总是在下一个tick中执行。
  1211. return promise[key](function () {
  1212. var deferred = Base.Deferred(),
  1213. args = arguments;
  1214. setTimeout(function () {
  1215. deferred.resolve.apply(deferred, args);
  1216. }, 1);
  1217. return deferred.promise();
  1218. })[key](callback || Base.noop);
  1219. } else {
  1220. return rlts[0];
  1221. }
  1222. }
  1223. });
  1224. /**
  1225. * 添加组件
  1226. * @param {object} widgetProto 组件原型,构造函数通过constructor属性定义
  1227. * @param {object} responseMap API名称与函数实现的映射
  1228. * @example
  1229. * Uploader.register( {
  1230. * init: function( options ) {},
  1231. * makeThumb: function() {}
  1232. * }, {
  1233. * 'make-thumb': 'makeThumb'
  1234. * } );
  1235. */
  1236. Uploader.register = Widget.register = function (responseMap, widgetProto) {
  1237. var map = {init: 'init'},
  1238. klass;
  1239. if (arguments.length === 1) {
  1240. widgetProto = responseMap;
  1241. widgetProto.responseMap = map;
  1242. } else {
  1243. widgetProto.responseMap = $.extend(map, responseMap);
  1244. }
  1245. klass = Base.inherits(Widget, widgetProto);
  1246. widgetClass.push(klass);
  1247. return klass;
  1248. };
  1249. return Widget;
  1250. });
  1251. /**
  1252. * @fileOverview 文件选择相关
  1253. */
  1254. define('widgets/filepicker', [
  1255. 'base',
  1256. 'uploader',
  1257. 'lib/filepicker',
  1258. 'widgets/widget'
  1259. ], function (Base, Uploader, FilePicker) {
  1260. var $ = Base.$;
  1261. $.extend(Uploader.options, {
  1262. /**
  1263. * @property {Selector | Object} [pick=undefined]
  1264. * @namespace options
  1265. * @for Uploader
  1266. * @description 指定选择文件的按钮容器,不指定则不创建按钮。
  1267. *
  1268. * * `id` {Seletor} 指定选择文件的按钮容器,不指定则不创建按钮。
  1269. * * `label` {String} 请采用 `innerHTML` 代替
  1270. * * `innerHTML` {String} 指定按钮文字。不指定时优先从指定的容器中看是否自带文字。
  1271. * * `multiple` {Boolean} 是否开起同时选择多个文件能力。
  1272. */
  1273. pick: null,
  1274. /**
  1275. * @property {Arroy} [accept=null]
  1276. * @namespace options
  1277. * @for Uploader
  1278. * @description 指定接受哪些类型的文件。 由于目前还有ext转mimeType表,所以这里需要分开指定。
  1279. *
  1280. * * `title` {String} 文字描述
  1281. * * `extensions` {String} 允许的文件后缀,不带点,多个用逗号分割。
  1282. * * `mimeTypes` {String} 多个用逗号分割。
  1283. *
  1284. * 如:
  1285. *
  1286. * ```
  1287. * {
  1288. * title: 'Images',
  1289. * extensions: 'gif,jpg,jpeg,bmp,png',
  1290. * mimeTypes: 'image/*'
  1291. * }
  1292. * ```
  1293. */
  1294. accept: null/*{
  1295. title: 'Images',
  1296. extensions: 'gif,jpg,jpeg,bmp,png',
  1297. mimeTypes: 'image/*'
  1298. }*/
  1299. });
  1300. return Uploader.register({
  1301. 'add-btn': 'addButton',
  1302. refresh: 'refresh',
  1303. disable: 'disable',
  1304. enable: 'enable'
  1305. }, {
  1306. init: function (opts) {
  1307. this.pickers = [];
  1308. return opts.pick && this.addButton(opts.pick);
  1309. },
  1310. refresh: function () {
  1311. $.each(this.pickers, function () {
  1312. this.refresh();
  1313. });
  1314. },
  1315. /**
  1316. * @method addButton
  1317. * @for Uploader
  1318. * @grammar addButton( pick ) => Promise
  1319. * @description
  1320. * 添加文件选择按钮,如果一个按钮不够,需要调用此方法来添加。参数跟[options.pick](#WebUploader:Uploader:options)一致。
  1321. * @example
  1322. * uploader.addButton({
  1323. * id: '#btnContainer',
  1324. * innerHTML: '选择文件'
  1325. * });
  1326. */
  1327. addButton: function (pick) {
  1328. var me = this,
  1329. opts = me.options,
  1330. accept = opts.accept,
  1331. options, picker, deferred;
  1332. if (!pick) {
  1333. return;
  1334. }
  1335. deferred = Base.Deferred();
  1336. $.isPlainObject(pick) || (pick = {
  1337. id: pick
  1338. });
  1339. options = $.extend({}, pick, {
  1340. accept: $.isPlainObject(accept) ? [accept] : accept,
  1341. swf: opts.swf,
  1342. runtimeOrder: opts.runtimeOrder
  1343. });
  1344. picker = new FilePicker(options);
  1345. picker.once('ready', deferred.resolve);
  1346. picker.on('select', function (files) {
  1347. me.owner.request('add-file', [files]);
  1348. });
  1349. picker.init();
  1350. this.pickers.push(picker);
  1351. return deferred.promise();
  1352. },
  1353. disable: function () {
  1354. $.each(this.pickers, function () {
  1355. this.disable();
  1356. });
  1357. },
  1358. enable: function () {
  1359. $.each(this.pickers, function () {
  1360. this.enable();
  1361. });
  1362. }
  1363. });
  1364. });
  1365. /**
  1366. * @fileOverview Image
  1367. */
  1368. define('lib/image', [
  1369. 'base',
  1370. 'runtime/client',
  1371. 'lib/blob'
  1372. ], function (Base, RuntimeClient, Blob) {
  1373. var $ = Base.$;
  1374. // 构造器。
  1375. function Image(opts) {
  1376. this.options = $.extend({}, Image.options, opts);
  1377. RuntimeClient.call(this, 'Image');
  1378. this.on('load', function () {
  1379. this._info = this.exec('info');
  1380. this._meta = this.exec('meta');
  1381. });
  1382. }
  1383. // 默认选项。
  1384. Image.options = {
  1385. // 默认的图片处理质量
  1386. quality: 90,
  1387. // 是否裁剪
  1388. crop: false,
  1389. // 是否保留头部信息
  1390. preserveHeaders: true,
  1391. // 是否允许放大。
  1392. allowMagnify: true
  1393. };
  1394. // 继承RuntimeClient.
  1395. Base.inherits(RuntimeClient, {
  1396. constructor: Image,
  1397. info: function (val) {
  1398. // setter
  1399. if (val) {
  1400. this._info = val;
  1401. return this;
  1402. }
  1403. // getter
  1404. return this._info;
  1405. },
  1406. meta: function (val) {
  1407. // setter
  1408. if (val) {
  1409. this._meta = val;
  1410. return this;
  1411. }
  1412. // getter
  1413. return this._meta;
  1414. },
  1415. loadFromBlob: function (blob) {
  1416. var me = this,
  1417. ruid = blob.getRuid();
  1418. this.connectRuntime(ruid, function () {
  1419. me.exec('init', me.options);
  1420. me.exec('loadFromBlob', blob);
  1421. });
  1422. },
  1423. resize: function () {
  1424. var args = Base.slice(arguments);
  1425. return this.exec.apply(this, ['resize'].concat(args));
  1426. },
  1427. getAsDataUrl: function (type) {
  1428. return this.exec('getAsDataUrl', type);
  1429. },
  1430. getAsBlob: function (type) {
  1431. var blob = this.exec('getAsBlob', type);
  1432. return new Blob(this.getRuid(), blob);
  1433. }
  1434. });
  1435. return Image;
  1436. });
  1437. /**
  1438. * @fileOverview 图片操作, 负责预览图片和上传前压缩图片
  1439. */
  1440. define('widgets/image', [
  1441. 'base',
  1442. 'uploader',
  1443. 'lib/image',
  1444. 'widgets/widget'
  1445. ], function (Base, Uploader, Image) {
  1446. var $ = Base.$,
  1447. throttle;
  1448. // 根据要处理的文件大小来节流,一次不能处理太多,会卡。
  1449. throttle = (function (max) {
  1450. var occupied = 0,
  1451. waiting = [],
  1452. tick = function () {
  1453. var item;
  1454. while (waiting.length && occupied < max) {
  1455. item = waiting.shift();
  1456. occupied += item[0];
  1457. item[1]();
  1458. }
  1459. };
  1460. return function (emiter, size, cb) {
  1461. waiting.push([size, cb]);
  1462. emiter.once('destroy', function () {
  1463. occupied -= size;
  1464. setTimeout(tick, 1);
  1465. });
  1466. setTimeout(tick, 1);
  1467. };
  1468. })(5 * 1024 * 1024);
  1469. $.extend(Uploader.options, {
  1470. /**
  1471. * @property {Object} [thumb]
  1472. * @namespace options
  1473. * @for Uploader
  1474. * @description 配置生成缩略图的选项。
  1475. *
  1476. * 默认为:
  1477. *
  1478. * ```javascript
  1479. * {
  1480. * width: 110,
  1481. * height: 110,
  1482. *
  1483. * // 图片质量,只有type为`image/jpeg`的时候才有效。
  1484. * quality: 70,
  1485. *
  1486. * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
  1487. * allowMagnify: true,
  1488. *
  1489. * // 是否允许裁剪。
  1490. * crop: true,
  1491. *
  1492. * // 是否保留头部meta信息。
  1493. * preserveHeaders: false,
  1494. *
  1495. * // 为空的话则保留原有图片格式。
  1496. * // 否则强制转换成指定的类型。
  1497. * type: 'image/jpeg'
  1498. * }
  1499. * ```
  1500. */
  1501. thumb: {
  1502. width: 110,
  1503. height: 110,
  1504. quality: 70,
  1505. allowMagnify: true,
  1506. crop: true,
  1507. preserveHeaders: false,
  1508. // 为空的话则保留原有图片格式。
  1509. // 否则强制转换成指定的类型。
  1510. // IE 8下面 base64 大小不能超过 32K 否则预览失败,而非 jpeg 编码的图片很可
  1511. // 能会超过 32k, 所以这里设置成预览的时候都是 image/jpeg
  1512. type: 'image/jpeg'
  1513. },
  1514. /**
  1515. * @property {Object} [compress]
  1516. * @namespace options
  1517. * @for Uploader
  1518. * @description 配置压缩的图片的选项。如果此选项为`false`, 则图片在上传前不进行压缩。
  1519. *
  1520. * 默认为:
  1521. *
  1522. * ```javascript
  1523. * {
  1524. * width: 1600,
  1525. * height: 1600,
  1526. *
  1527. * // 图片质量,只有type为`image/jpeg`的时候才有效。
  1528. * quality: 90,
  1529. *
  1530. * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
  1531. * allowMagnify: false,
  1532. *
  1533. * // 是否允许裁剪。
  1534. * crop: false,
  1535. *
  1536. * // 是否保留头部meta信息。
  1537. * preserveHeaders: true
  1538. * }
  1539. * ```
  1540. */
  1541. compress: {
  1542. width: 1600,
  1543. height: 1600,
  1544. quality: 90,
  1545. allowMagnify: false,
  1546. crop: false,
  1547. preserveHeaders: true
  1548. }
  1549. });
  1550. return Uploader.register({
  1551. 'make-thumb': 'makeThumb',
  1552. 'before-send-file': 'compressImage'
  1553. }, {
  1554. /**
  1555. * 生成缩略图,此过程为异步,所以需要传入`callback`。
  1556. * 通常情况在图片加入队里后调用此方法来生成预览图以增强交互效果。
  1557. *
  1558. * `callback`中可以接收到两个参数。
  1559. * * 第一个为error,如果生成缩略图有错误,此error将为真。
  1560. * * 第二个为ret, 缩略图的Data URL值。
  1561. *
  1562. * **注意**
  1563. * Date URL在IE6/7中不支持,所以不用调用此方法了,直接显示一张暂不支持预览图片好了。
  1564. *
  1565. *
  1566. * @method makeThumb
  1567. * @grammar makeThumb( file, callback ) => undefined
  1568. * @grammar makeThumb( file, callback, width, height ) => undefined
  1569. * @for Uploader
  1570. * @example
  1571. *
  1572. * uploader.on( 'fileQueued', function( file ) {
  1573. * var $li = ...;
  1574. *
  1575. * uploader.makeThumb( file, function( error, ret ) {
  1576. * if ( error ) {
  1577. * $li.text('预览错误');
  1578. * } else {
  1579. * $li.append('<img alt="" src="' + ret + '" />');
  1580. * }
  1581. * });
  1582. *
  1583. * });
  1584. */
  1585. makeThumb: function (file, cb, width, height) {
  1586. var opts, image;
  1587. file = this.request('get-file', file);
  1588. // 只预览图片格式。
  1589. if (!file.type.match(/^image/)) {
  1590. cb(true);
  1591. return;
  1592. }
  1593. opts = $.extend({}, this.options.thumb);
  1594. // 如果传入的是object.
  1595. if ($.isPlainObject(width)) {
  1596. opts = $.extend(opts, width);
  1597. width = null;
  1598. }
  1599. width = width || opts.width;
  1600. height = height || opts.height;
  1601. image = new Image(opts);
  1602. image.once('load', function () {
  1603. file._info = file._info || image.info();
  1604. file._meta = file._meta || image.meta();
  1605. image.resize(width, height);
  1606. });
  1607. image.once('complete', function () {
  1608. cb(false, image.getAsDataUrl(opts.type));
  1609. image.destroy();
  1610. });
  1611. image.once('error', function () {
  1612. cb(true);
  1613. image.destroy();
  1614. });
  1615. throttle(image, file.source.size, function () {
  1616. file._info && image.info(file._info);
  1617. file._meta && image.meta(file._meta);
  1618. image.loadFromBlob(file.source);
  1619. });
  1620. },
  1621. compressImage: function (file) {
  1622. var opts = this.options.compress || this.options.resize,
  1623. compressSize = opts && opts.compressSize || 300 * 1024,
  1624. image, deferred;
  1625. file = this.request('get-file', file);
  1626. // 只预览图片格式。
  1627. if (!opts || !~'image/jpeg,image/jpg'.indexOf(file.type) ||
  1628. file.size < compressSize ||
  1629. file._compressed) {
  1630. return;
  1631. }
  1632. opts = $.extend({}, opts);
  1633. deferred = Base.Deferred();
  1634. image = new Image(opts);
  1635. deferred.always(function () {
  1636. image.destroy();
  1637. image = null;
  1638. });
  1639. image.once('error', deferred.reject);
  1640. image.once('load', function () {
  1641. file._info = file._info || image.info();
  1642. file._meta = file._meta || image.meta();
  1643. image.resize(opts.width, opts.height);
  1644. });
  1645. image.once('complete', function () {
  1646. var blob, size;
  1647. // 移动端 UC / qq 浏览器的无图模式下
  1648. // ctx.getImageData 处理大图的时候会报 Exception
  1649. // INDEX_SIZE_ERR: DOM Exception 1
  1650. try {
  1651. blob = image.getAsBlob(opts.type);
  1652. size = file.size;
  1653. // 如果压缩后,比原来还大则不用压缩后的。
  1654. if (blob.size < size) {
  1655. // file.source.destroy && file.source.destroy();
  1656. file.source = blob;
  1657. file.size = blob.size;
  1658. file.trigger('resize', blob.size, size);
  1659. }
  1660. // 标记,避免重复压缩。
  1661. file._compressed = true;
  1662. deferred.resolve();
  1663. } catch (e) {
  1664. // 出错了直接继续,让其上传原始图片
  1665. deferred.resolve();
  1666. }
  1667. });
  1668. file._info && image.info(file._info);
  1669. file._meta && image.meta(file._meta);
  1670. image.loadFromBlob(file.source);
  1671. return deferred.promise();
  1672. }
  1673. });
  1674. });
  1675. /**
  1676. * @fileOverview 文件属性封装
  1677. */
  1678. define('file', [
  1679. 'base',
  1680. 'mediator'
  1681. ], function (Base, Mediator) {
  1682. var $ = Base.$,
  1683. idPrefix = 'WU_FILE_',
  1684. idSuffix = 0,
  1685. rExt = /\.([^.]+)$/,
  1686. statusMap = {};
  1687. function gid() {
  1688. return idPrefix + idSuffix++;
  1689. }
  1690. /**
  1691. * 文件类
  1692. * @class File
  1693. * @constructor 构造函数
  1694. * @grammar new File( source ) => File
  1695. * @param {Lib.File} source [lib.File](#Lib.File)实例, 此source对象是带有Runtime信息的。
  1696. */
  1697. function WUFile(source) {
  1698. /**
  1699. * 文件名,包括扩展名(后缀)
  1700. * @property name
  1701. * @type {string}
  1702. */
  1703. this.name = source.name || 'Untitled';
  1704. /**
  1705. * 文件体积(字节)
  1706. * @property size
  1707. * @type {uint}
  1708. * @default 0
  1709. */
  1710. this.size = source.size || 0;
  1711. /**
  1712. * 文件MIMETYPE类型,与文件类型的对应关系请参考[http://t.cn/z8ZnFny](http://t.cn/z8ZnFny)
  1713. * @property type
  1714. * @type {string}
  1715. * @default 'application'
  1716. */
  1717. this.type = source.type || 'application';
  1718. /**
  1719. * 文件最后修改日期
  1720. * @property lastModifiedDate
  1721. * @type {int}
  1722. * @default 当前时间戳
  1723. */
  1724. this.lastModifiedDate = source.lastModifiedDate || (new Date() * 1);
  1725. /**
  1726. * 文件ID,每个对象具有唯一ID,与文件名无关
  1727. * @property id
  1728. * @type {string}
  1729. */
  1730. this.id = gid();
  1731. /**
  1732. * 文件扩展名,通过文件名获取,例如test.png的扩展名为png
  1733. * @property ext
  1734. * @type {string}
  1735. */
  1736. this.ext = rExt.exec(this.name) ? RegExp.$1 : '';
  1737. /**
  1738. * 状态文字说明。在不同的status语境下有不同的用途。
  1739. * @property statusText
  1740. * @type {string}
  1741. */
  1742. this.statusText = '';
  1743. // 存储文件状态,防止通过属性直接修改
  1744. statusMap[this.id] = WUFile.Status.INITED;
  1745. this.source = source;
  1746. this.loaded = 0;
  1747. this.on('error', function (msg) {
  1748. this.setStatus(WUFile.Status.ERROR, msg);
  1749. });
  1750. }
  1751. $.extend(WUFile.prototype, {
  1752. /**
  1753. * 设置状态,状态变化时会触发`change`事件。
  1754. * @method setStatus
  1755. * @grammar setStatus( status[, statusText] );
  1756. * @param {File.Status|String} status [文件状态值](#WebUploader:File:File.Status)
  1757. * @param {String} [statusText=''] 状态说明,常在error时使用,用http, abort,server等来标记是由于什么原因导致文件错误。
  1758. */
  1759. setStatus: function (status, text) {
  1760. var prevStatus = statusMap[this.id];
  1761. typeof text !== 'undefined' && (this.statusText = text);
  1762. if (status !== prevStatus) {
  1763. statusMap[this.id] = status;
  1764. /**
  1765. * 文件状态变化
  1766. * @event statuschange
  1767. */
  1768. this.trigger('statuschange', status, prevStatus);
  1769. }
  1770. },
  1771. /**
  1772. * 获取文件状态
  1773. * @return {File.Status}
  1774. * @example
  1775. 文件状态具体包括以下几种类型:
  1776. {
  1777. // 初始化
  1778. INITED: 0,
  1779. // 已入队列
  1780. QUEUED: 1,
  1781. // 正在上传
  1782. PROGRESS: 2,
  1783. // 上传出错
  1784. ERROR: 3,
  1785. // 上传成功
  1786. COMPLETE: 4,
  1787. // 上传取消
  1788. CANCELLED: 5
  1789. }
  1790. */
  1791. getStatus: function () {
  1792. return statusMap[this.id];
  1793. },
  1794. /**
  1795. * 获取文件原始信息。
  1796. * @return {*}
  1797. */
  1798. getSource: function () {
  1799. return this.source;
  1800. },
  1801. destory: function () {
  1802. delete statusMap[this.id];
  1803. }
  1804. });
  1805. Mediator.installTo(WUFile.prototype);
  1806. /**
  1807. * 文件状态值,具体包括以下几种类型:
  1808. * * `inited` 初始状态
  1809. * * `queued` 已经进入队列, 等待上传
  1810. * * `progress` 上传中
  1811. * * `complete` 上传完成。
  1812. * * `error` 上传出错,可重试
  1813. * * `interrupt` 上传中断,可续传。
  1814. * * `invalid` 文件不合格,不能重试上传。会自动从队列中移除。
  1815. * * `cancelled` 文件被移除。
  1816. * @property {Object} Status
  1817. * @namespace File
  1818. * @class File
  1819. * @static
  1820. */
  1821. WUFile.Status = {
  1822. INITED: 'inited', // 初始状态
  1823. QUEUED: 'queued', // 已经进入队列, 等待上传
  1824. PROGRESS: 'progress', // 上传中
  1825. ERROR: 'error', // 上传出错,可重试
  1826. COMPLETE: 'complete', // 上传完成。
  1827. CANCELLED: 'cancelled', // 上传取消。
  1828. INTERRUPT: 'interrupt', // 上传中断,可续传。
  1829. INVALID: 'invalid' // 文件不合格,不能重试上传。
  1830. };
  1831. return WUFile;
  1832. });
  1833. /**
  1834. * @fileOverview 文件队列
  1835. */
  1836. define('queue', [
  1837. 'base',
  1838. 'mediator',
  1839. 'file'
  1840. ], function (Base, Mediator, WUFile) {
  1841. var $ = Base.$,
  1842. STATUS = WUFile.Status;
  1843. /**
  1844. * 文件队列, 用来存储各个状态中的文件。
  1845. * @class Queue
  1846. * @extends Mediator
  1847. */
  1848. function Queue() {
  1849. /**
  1850. * 统计文件数。
  1851. * * `numOfQueue` 队列中的文件数。
  1852. * * `numOfSuccess` 上传成功的文件数
  1853. * * `numOfCancel` 被移除的文件数
  1854. * * `numOfProgress` 正在上传中的文件数
  1855. * * `numOfUploadFailed` 上传错误的文件数。
  1856. * * `numOfInvalid` 无效的文件数。
  1857. * @property {Object} stats
  1858. */
  1859. this.stats = {
  1860. numOfQueue: 0,
  1861. numOfSuccess: 0,
  1862. numOfCancel: 0,
  1863. numOfProgress: 0,
  1864. numOfUploadFailed: 0,
  1865. numOfInvalid: 0
  1866. };
  1867. // 上传队列,仅包括等待上传的文件
  1868. this._queue = [];
  1869. // 存储所有文件
  1870. this._map = {};
  1871. }
  1872. $.extend(Queue.prototype, {
  1873. /**
  1874. * 将新文件加入对队列尾部
  1875. *
  1876. * @method append
  1877. * @param {File} file 文件对象
  1878. */
  1879. append: function (file) {
  1880. this._queue.push(file);
  1881. this._fileAdded(file);
  1882. return this;
  1883. },
  1884. /**
  1885. * 将新文件加入对队列头部
  1886. *
  1887. * @method prepend
  1888. * @param {File} file 文件对象
  1889. */
  1890. prepend: function (file) {
  1891. this._queue.unshift(file);
  1892. this._fileAdded(file);
  1893. return this;
  1894. },
  1895. /**
  1896. * 获取文件对象
  1897. *
  1898. * @method getFile
  1899. * @param {String} fileId 文件ID
  1900. * @return {File}
  1901. */
  1902. getFile: function (fileId) {
  1903. if (typeof fileId !== 'string') {
  1904. return fileId;
  1905. }
  1906. return this._map[fileId];
  1907. },
  1908. /**
  1909. * 从队列中取出一个指定状态的文件。
  1910. * @grammar fetch( status ) => File
  1911. * @method fetch
  1912. * @param {String} status [文件状态值](#WebUploader:File:File.Status)
  1913. * @return {File} [File](#WebUploader:File)
  1914. */
  1915. fetch: function (status) {
  1916. var len = this._queue.length,
  1917. i, file;
  1918. status = status || STATUS.QUEUED;
  1919. for (i = 0; i < len; i++) {
  1920. file = this._queue[i];
  1921. if (status === file.getStatus()) {
  1922. return file;
  1923. }
  1924. }
  1925. return null;
  1926. },
  1927. /**
  1928. * 对队列进行排序,能够控制文件上传顺序。
  1929. * @grammar sort( fn ) => undefined
  1930. * @method sort
  1931. * @param {Function} fn 排序方法
  1932. */
  1933. sort: function (fn) {
  1934. if (typeof fn === 'function') {
  1935. this._queue.sort(fn);
  1936. }
  1937. },
  1938. /**
  1939. * 获取指定类型的文件列表, 列表中每一个成员为[File](#WebUploader:File)对象。
  1940. * @grammar getFiles( [status1[, status2 ...]] ) => Array
  1941. * @method getFiles
  1942. * @param {String} [status] [文件状态值](#WebUploader:File:File.Status)
  1943. */
  1944. getFiles: function () {
  1945. var sts = [].slice.call(arguments, 0),
  1946. ret = [],
  1947. i = 0,
  1948. len = this._queue.length,
  1949. file;
  1950. for (; i < len; i++) {
  1951. file = this._queue[i];
  1952. if (sts.length && !~$.inArray(file.getStatus(), sts)) {
  1953. continue;
  1954. }
  1955. ret.push(file);
  1956. }
  1957. return ret;
  1958. },
  1959. _fileAdded: function (file) {
  1960. var me = this,
  1961. existing = this._map[file.id];
  1962. if (!existing) {
  1963. this._map[file.id] = file;
  1964. file.on('statuschange', function (cur, pre) {
  1965. me._onFileStatusChange(cur, pre);
  1966. });
  1967. }
  1968. file.setStatus(STATUS.QUEUED);
  1969. },
  1970. _onFileStatusChange: function (curStatus, preStatus) {
  1971. var stats = this.stats;
  1972. switch (preStatus) {
  1973. case STATUS.PROGRESS:
  1974. stats.numOfProgress--;
  1975. break;
  1976. case STATUS.QUEUED:
  1977. stats.numOfQueue--;
  1978. break;
  1979. case STATUS.ERROR:
  1980. stats.numOfUploadFailed--;
  1981. break;
  1982. case STATUS.INVALID:
  1983. stats.numOfInvalid--;
  1984. break;
  1985. }
  1986. switch (curStatus) {
  1987. case STATUS.QUEUED:
  1988. stats.numOfQueue++;
  1989. break;
  1990. case STATUS.PROGRESS:
  1991. stats.numOfProgress++;
  1992. break;
  1993. case STATUS.ERROR:
  1994. stats.numOfUploadFailed++;
  1995. break;
  1996. case STATUS.COMPLETE:
  1997. stats.numOfSuccess++;
  1998. break;
  1999. case STATUS.CANCELLED:
  2000. stats.numOfCancel++;
  2001. break;
  2002. case STATUS.INVALID:
  2003. stats.numOfInvalid++;
  2004. break;
  2005. }
  2006. }
  2007. });
  2008. Mediator.installTo(Queue.prototype);
  2009. return Queue;
  2010. });
  2011. /**
  2012. * @fileOverview 队列
  2013. */
  2014. define('widgets/queue', [
  2015. 'base',
  2016. 'uploader',
  2017. 'queue',
  2018. 'file',
  2019. 'lib/file',
  2020. 'runtime/client',
  2021. 'widgets/widget'
  2022. ], function (Base, Uploader, Queue, WUFile, File, RuntimeClient) {
  2023. var $ = Base.$,
  2024. rExt = /\.\w+$/,
  2025. Status = WUFile.Status;
  2026. return Uploader.register({
  2027. 'sort-files': 'sortFiles',
  2028. 'add-file': 'addFiles',
  2029. 'get-file': 'getFile',
  2030. 'fetch-file': 'fetchFile',
  2031. 'get-stats': 'getStats',
  2032. 'get-files': 'getFiles',
  2033. 'remove-file': 'removeFile',
  2034. 'retry': 'retry',
  2035. 'reset': 'reset',
  2036. 'accept-file': 'acceptFile'
  2037. }, {
  2038. init: function (opts) {
  2039. var me = this,
  2040. deferred, len, i, item, arr, accept, runtime;
  2041. if ($.isPlainObject(opts.accept)) {
  2042. opts.accept = [opts.accept];
  2043. }
  2044. // accept中的中生成匹配正则。
  2045. if (opts.accept) {
  2046. arr = [];
  2047. for (i = 0, len = opts.accept.length; i < len; i++) {
  2048. item = opts.accept[i].extensions;
  2049. item && arr.push(item);
  2050. }
  2051. if (arr.length) {
  2052. accept = '\\.' + arr.join(',')
  2053. .replace(/,/g, '$|\\.')
  2054. .replace(/\*/g, '.*') + '$';
  2055. }
  2056. me.accept = new RegExp(accept, 'i');
  2057. }
  2058. me.queue = new Queue();
  2059. me.stats = me.queue.stats;
  2060. // 如果当前不是html5运行时,那就算了。
  2061. // 不执行后续操作
  2062. if (this.request('predict-runtime-type') !== 'html5') {
  2063. return;
  2064. }
  2065. // 创建一个 html5 运行时的 placeholder
  2066. // 以至于外部添加原生 File 对象的时候能正确包裹一下供 webuploader 使用。
  2067. deferred = Base.Deferred();
  2068. runtime = new RuntimeClient('Placeholder');
  2069. runtime.connectRuntime({
  2070. runtimeOrder: 'html5'
  2071. }, function () {
  2072. me._ruid = runtime.getRuid();
  2073. deferred.resolve();
  2074. });
  2075. return deferred.promise();
  2076. },
  2077. // 为了支持外部直接添加一个原生File对象。
  2078. _wrapFile: function (file) {
  2079. if (!(file instanceof WUFile)) {
  2080. if (!(file instanceof File)) {
  2081. if (!this._ruid) {
  2082. throw new Error('Can\'t add external files.');
  2083. }
  2084. file = new File(this._ruid, file);
  2085. }
  2086. file = new WUFile(file);
  2087. }
  2088. return file;
  2089. },
  2090. // 判断文件是否可以被加入队列
  2091. acceptFile: function (file) {
  2092. var invalid = !file || file.size < 6 || this.accept &&
  2093. // 如果名字中有后缀,才做后缀白名单处理。
  2094. rExt.exec(file.name) && !this.accept.test(file.name);
  2095. return !invalid;
  2096. },
  2097. /**
  2098. * @event beforeFileQueued
  2099. * @param {File} file File对象
  2100. * @description 当文件被加入队列之前触发,此事件的handler返回值为`false`,则此文件不会被添加进入队列。
  2101. * @for Uploader
  2102. */
  2103. /**
  2104. * @event fileQueued
  2105. * @param {File} file File对象
  2106. * @description 当文件被加入队列以后触发。
  2107. * @for Uploader
  2108. */
  2109. _addFile: function (file) {
  2110. var me = this;
  2111. file = me._wrapFile(file);
  2112. // 不过类型判断允许不允许,先派送 `beforeFileQueued`
  2113. if (!me.owner.trigger('beforeFileQueued', file)) {
  2114. return;
  2115. }
  2116. // 类型不匹配,则派送错误事件,并返回。
  2117. if (!me.acceptFile(file)) {
  2118. me.owner.trigger('error', 'Q_TYPE_DENIED', file);
  2119. return;
  2120. }
  2121. me.queue.append(file);
  2122. me.owner.trigger('fileQueued', file);
  2123. return file;
  2124. },
  2125. getFile: function (fileId) {
  2126. return this.queue.getFile(fileId);
  2127. },
  2128. /**
  2129. * @event filesQueued
  2130. * @param {File} files 数组,内容为原始File(lib/File)对象。
  2131. * @description 当一批文件添加进队列以后触发。
  2132. * @for Uploader
  2133. */
  2134. /**
  2135. * @method addFiles
  2136. * @grammar addFiles( file ) => undefined
  2137. * @grammar addFiles( [file1, file2 ...] ) => undefined
  2138. * @param {Array of File or File} [files] Files 对象 数组
  2139. * @description 添加文件到队列
  2140. * @for Uploader
  2141. */
  2142. addFiles: function (files) {
  2143. var me = this;
  2144. if (!files.length) {
  2145. files = [files];
  2146. }
  2147. files = $.map(files, function (file) {
  2148. return me._addFile(file);
  2149. });
  2150. me.owner.trigger('filesQueued', files);
  2151. if (me.options.auto) {
  2152. me.request('start-upload');
  2153. }
  2154. },
  2155. getStats: function () {
  2156. return this.stats;
  2157. },
  2158. /**
  2159. * @event fileDequeued
  2160. * @param {File} file File对象
  2161. * @description 当文件被移除队列后触发。
  2162. * @for Uploader
  2163. */
  2164. /**
  2165. * @method removeFile
  2166. * @grammar removeFile( file ) => undefined
  2167. * @grammar removeFile( id ) => undefined
  2168. * @param {File|id} file File对象或这File对象的id
  2169. * @description 移除某一文件。
  2170. * @for Uploader
  2171. * @example
  2172. *
  2173. * $li.on('click', '.remove-this', function() {
  2174. * uploader.removeFile( file );
  2175. * })
  2176. */
  2177. removeFile: function (file) {
  2178. var me = this;
  2179. file = file.id ? file : me.queue.getFile(file);
  2180. file.setStatus(Status.CANCELLED);
  2181. me.owner.trigger('fileDequeued', file);
  2182. },
  2183. /**
  2184. * @method getFiles
  2185. * @grammar getFiles() => Array
  2186. * @grammar getFiles( status1, status2, status... ) => Array
  2187. * @description 返回指定状态的文件集合,不传参数将返回所有状态的文件。
  2188. * @for Uploader
  2189. * @example
  2190. * console.log( uploader.getFiles() ); // => all files
  2191. * console.log( uploader.getFiles('error') ) // => all error files.
  2192. */
  2193. getFiles: function () {
  2194. return this.queue.getFiles.apply(this.queue, arguments);
  2195. },
  2196. fetchFile: function () {
  2197. return this.queue.fetch.apply(this.queue, arguments);
  2198. },
  2199. /**
  2200. * @method retry
  2201. * @grammar retry() => undefined
  2202. * @grammar retry( file ) => undefined
  2203. * @description 重试上传,重试指定文件,或者从出错的文件开始重新上传。
  2204. * @for Uploader
  2205. * @example
  2206. * function retry() {
  2207. * uploader.retry();
  2208. * }
  2209. */
  2210. retry: function (file, noForceStart) {
  2211. var me = this,
  2212. files, i, len;
  2213. if (file) {
  2214. file = file.id ? file : me.queue.getFile(file);
  2215. file.setStatus(Status.QUEUED);
  2216. noForceStart || me.request('start-upload');
  2217. return;
  2218. }
  2219. files = me.queue.getFiles(Status.ERROR);
  2220. i = 0;
  2221. len = files.length;
  2222. for (; i < len; i++) {
  2223. file = files[i];
  2224. file.setStatus(Status.QUEUED);
  2225. }
  2226. me.request('start-upload');
  2227. },
  2228. /**
  2229. * @method sort
  2230. * @grammar sort( fn ) => undefined
  2231. * @description 排序队列中的文件,在上传之前调整可以控制上传顺序。
  2232. * @for Uploader
  2233. */
  2234. sortFiles: function () {
  2235. return this.queue.sort.apply(this.queue, arguments);
  2236. },
  2237. /**
  2238. * @method reset
  2239. * @grammar reset() => undefined
  2240. * @description 重置uploader。目前只重置了队列。
  2241. * @for Uploader
  2242. * @example
  2243. * uploader.reset();
  2244. */
  2245. reset: function () {
  2246. this.queue = new Queue();
  2247. this.stats = this.queue.stats;
  2248. }
  2249. });
  2250. });
  2251. /**
  2252. * @fileOverview 添加获取Runtime相关信息的方法。
  2253. */
  2254. define('widgets/runtime', [
  2255. 'uploader',
  2256. 'runtime/runtime',
  2257. 'widgets/widget'
  2258. ], function (Uploader, Runtime) {
  2259. Uploader.support = function () {
  2260. return Runtime.hasRuntime.apply(Runtime, arguments);
  2261. };
  2262. return Uploader.register({
  2263. 'predict-runtime-type': 'predictRuntmeType'
  2264. }, {
  2265. init: function () {
  2266. if (!this.predictRuntmeType()) {
  2267. throw Error('Runtime Error');
  2268. }
  2269. },
  2270. /**
  2271. * 预测Uploader将采用哪个`Runtime`
  2272. * @grammar predictRuntmeType() => String
  2273. * @method predictRuntmeType
  2274. * @for Uploader
  2275. */
  2276. predictRuntmeType: function () {
  2277. var orders = this.options.runtimeOrder || Runtime.orders,
  2278. type = this.type,
  2279. i, len;
  2280. if (!type) {
  2281. orders = orders.split(/\s*,\s*/g);
  2282. for (i = 0, len = orders.length; i < len; i++) {
  2283. if (Runtime.hasRuntime(orders[i])) {
  2284. this.type = type = orders[i];
  2285. break;
  2286. }
  2287. }
  2288. }
  2289. return type;
  2290. }
  2291. });
  2292. });
  2293. /**
  2294. * @fileOverview Transport
  2295. */
  2296. define('lib/transport', [
  2297. 'base',
  2298. 'runtime/client',
  2299. 'mediator'
  2300. ], function (Base, RuntimeClient, Mediator) {
  2301. var $ = Base.$;
  2302. function Transport(opts) {
  2303. var me = this;
  2304. opts = me.options = $.extend(true, {}, Transport.options, opts || {});
  2305. RuntimeClient.call(this, 'Transport');
  2306. this._blob = null;
  2307. this._formData = opts.formData || {};
  2308. this._headers = opts.headers || {};
  2309. this.on('progress', this._timeout);
  2310. this.on('load error', function () {
  2311. me.trigger('progress', 1);
  2312. clearTimeout(me._timer);
  2313. });
  2314. }
  2315. Transport.options = {
  2316. server: '',
  2317. method: 'POST',
  2318. // 跨域时,是否允许携带cookie, 只有html5 runtime才有效
  2319. withCredentials: false,
  2320. fileVal: 'file',
  2321. timeout: 2 * 60 * 1000, // 2分钟
  2322. formData: {},
  2323. headers: {},
  2324. sendAsBinary: false
  2325. };
  2326. $.extend(Transport.prototype, {
  2327. // 添加Blob, 只能添加一次,最后一次有效。
  2328. appendBlob: function (key, blob, filename) {
  2329. var me = this,
  2330. opts = me.options;
  2331. if (me.getRuid()) {
  2332. me.disconnectRuntime();
  2333. }
  2334. // 连接到blob归属的同一个runtime.
  2335. me.connectRuntime(blob.ruid, function () {
  2336. me.exec('init');
  2337. });
  2338. me._blob = blob;
  2339. opts.fileVal = key || opts.fileVal;
  2340. opts.filename = filename || opts.filename;
  2341. },
  2342. // 添加其他字段
  2343. append: function (key, value) {
  2344. if (typeof key === 'object') {
  2345. $.extend(this._formData, key);
  2346. } else {
  2347. this._formData[key] = value;
  2348. }
  2349. },
  2350. setRequestHeader: function (key, value) {
  2351. if (typeof key === 'object') {
  2352. $.extend(this._headers, key);
  2353. } else {
  2354. this._headers[key] = value;
  2355. }
  2356. },
  2357. send: function (method) {
  2358. this.exec('send', method);
  2359. this._timeout();
  2360. },
  2361. abort: function () {
  2362. clearTimeout(this._timer);
  2363. return this.exec('abort');
  2364. },
  2365. destroy: function () {
  2366. this.trigger('destroy');
  2367. this.off();
  2368. this.exec('destroy');
  2369. this.disconnectRuntime();
  2370. },
  2371. getResponse: function () {
  2372. return this.exec('getResponse');
  2373. },
  2374. getResponseAsJson: function () {
  2375. return this.exec('getResponseAsJson');
  2376. },
  2377. getStatus: function () {
  2378. return this.exec('getStatus');
  2379. },
  2380. _timeout: function () {
  2381. var me = this,
  2382. duration = me.options.timeout;
  2383. if (!duration) {
  2384. return;
  2385. }
  2386. clearTimeout(me._timer);
  2387. me._timer = setTimeout(function () {
  2388. me.abort();
  2389. me.trigger('error', 'timeout');
  2390. }, duration);
  2391. }
  2392. });
  2393. // 让Transport具备事件功能。
  2394. Mediator.installTo(Transport.prototype);
  2395. return Transport;
  2396. });
  2397. /**
  2398. * @fileOverview 负责文件上传相关。
  2399. */
  2400. define('widgets/upload', [
  2401. 'base',
  2402. 'uploader',
  2403. 'file',
  2404. 'lib/transport',
  2405. 'widgets/widget'
  2406. ], function (Base, Uploader, WUFile, Transport) {
  2407. var $ = Base.$,
  2408. isPromise = Base.isPromise,
  2409. Status = WUFile.Status;
  2410. // 添加默认配置项
  2411. $.extend(Uploader.options, {
  2412. /**
  2413. * @property {Boolean} [prepareNextFile=false]
  2414. * @namespace options
  2415. * @for Uploader
  2416. * @description 是否允许在文件传输时提前把下一个文件准备好。
  2417. * 对于一个文件的准备工作比较耗时,比如图片压缩,md5序列化。
  2418. * 如果能提前在当前文件传输期处理,可以节省总体耗时。
  2419. */
  2420. prepareNextFile: false,
  2421. /**
  2422. * @property {Boolean} [chunked=false]
  2423. * @namespace options
  2424. * @for Uploader
  2425. * @description 是否要分片处理大文件上传。
  2426. */
  2427. chunked: false,
  2428. /**
  2429. * @property {Boolean} [chunkSize=5242880]
  2430. * @namespace options
  2431. * @for Uploader
  2432. * @description 如果要分片,分多大一片? 默认大小为5M.
  2433. */
  2434. chunkSize: 5 * 1024 * 1024,
  2435. /**
  2436. * @property {Boolean} [chunkRetry=2]
  2437. * @namespace options
  2438. * @for Uploader
  2439. * @description 如果某个分片由于网络问题出错,允许自动重传多少次?
  2440. */
  2441. chunkRetry: 2,
  2442. /**
  2443. * @property {Boolean} [threads=3]
  2444. * @namespace options
  2445. * @for Uploader
  2446. * @description 上传并发数。允许同时最大上传进程数。
  2447. */
  2448. threads: 3,
  2449. /**
  2450. * @property {Object} [formData]
  2451. * @namespace options
  2452. * @for Uploader
  2453. * @description 文件上传请求的参数表,每次发送都会发送此对象中的参数。
  2454. */
  2455. formData: null
  2456. /**
  2457. * @property {Object} [fileVal='file']
  2458. * @namespace options
  2459. * @for Uploader
  2460. * @description 设置文件上传域的name。
  2461. */
  2462. /**
  2463. * @property {Object} [method='POST']
  2464. * @namespace options
  2465. * @for Uploader
  2466. * @description 文件上传方式,`POST`或者`GET`。
  2467. */
  2468. /**
  2469. * @property {Object} [sendAsBinary=false]
  2470. * @namespace options
  2471. * @for Uploader
  2472. * @description 是否已二进制的流的方式发送文件,这样整个上传内容`php://input`都为文件内容,
  2473. * 其他参数在$_GET数组中。
  2474. */
  2475. });
  2476. // 负责将文件切片。
  2477. function CuteFile(file, chunkSize) {
  2478. var pending = [],
  2479. blob = file.source,
  2480. total = blob.size,
  2481. chunks = chunkSize ? Math.ceil(total / chunkSize) : 1,
  2482. start = 0,
  2483. index = 0,
  2484. len;
  2485. while (index < chunks) {
  2486. len = Math.min(chunkSize, total - start);
  2487. pending.push({
  2488. file: file,
  2489. start: start,
  2490. end: chunkSize ? (start + len) : total,
  2491. total: total,
  2492. chunks: chunks,
  2493. chunk: index++
  2494. });
  2495. start += len;
  2496. }
  2497. file.blocks = pending.concat();
  2498. file.remaning = pending.length;
  2499. return {
  2500. file: file,
  2501. has: function () {
  2502. return !!pending.length;
  2503. },
  2504. fetch: function () {
  2505. return pending.shift();
  2506. }
  2507. };
  2508. }
  2509. Uploader.register({
  2510. 'start-upload': 'start',
  2511. 'stop-upload': 'stop',
  2512. 'skip-file': 'skipFile',
  2513. 'is-in-progress': 'isInProgress'
  2514. }, {
  2515. init: function () {
  2516. var owner = this.owner;
  2517. this.runing = false;
  2518. // 记录当前正在传的数据,跟threads相关
  2519. this.pool = [];
  2520. // 缓存即将上传的文件。
  2521. this.pending = [];
  2522. // 跟踪还有多少分片没有完成上传。
  2523. this.remaning = 0;
  2524. this.__tick = Base.bindFn(this._tick, this);
  2525. owner.on('uploadComplete', function (file) {
  2526. // 把其他块取消了。
  2527. file.blocks && $.each(file.blocks, function (_, v) {
  2528. v.transport && (v.transport.abort(), v.transport.destroy());
  2529. delete v.transport;
  2530. });
  2531. delete file.blocks;
  2532. delete file.remaning;
  2533. });
  2534. },
  2535. /**
  2536. * @event startUpload
  2537. * @description 当开始上传流程时触发。
  2538. * @for Uploader
  2539. */
  2540. /**
  2541. * 开始上传。此方法可以从初始状态调用开始上传流程,也可以从暂停状态调用,继续上传流程。
  2542. * @grammar upload() => undefined
  2543. * @method upload
  2544. * @for Uploader
  2545. */
  2546. start: function () {
  2547. var me = this;
  2548. // 移出invalid的文件
  2549. $.each(me.request('get-files', Status.INVALID), function () {
  2550. me.request('remove-file', this);
  2551. });
  2552. if (me.runing) {
  2553. return;
  2554. }
  2555. me.runing = true;
  2556. // 如果有暂停的,则续传
  2557. $.each(me.pool, function (_, v) {
  2558. var file = v.file;
  2559. if (file.getStatus() === Status.INTERRUPT) {
  2560. file.setStatus(Status.PROGRESS);
  2561. me._trigged = false;
  2562. v.transport && v.transport.send();
  2563. }
  2564. });
  2565. me._trigged = false;
  2566. me.owner.trigger('startUpload');
  2567. Base.nextTick(me.__tick);
  2568. },
  2569. /**
  2570. * @event stopUpload
  2571. * @description 当开始上传流程暂停时触发。
  2572. * @for Uploader
  2573. */
  2574. /**
  2575. * 暂停上传。第一个参数为是否中断上传当前正在上传的文件。
  2576. * @grammar stop() => undefined
  2577. * @grammar stop( true ) => undefined
  2578. * @method stop
  2579. * @for Uploader
  2580. */
  2581. stop: function (interrupt) {
  2582. var me = this;
  2583. if (me.runing === false) {
  2584. return;
  2585. }
  2586. me.runing = false;
  2587. interrupt && $.each(me.pool, function (_, v) {
  2588. v.transport && v.transport.abort();
  2589. v.file.setStatus(Status.INTERRUPT);
  2590. });
  2591. me.owner.trigger('stopUpload');
  2592. },
  2593. /**
  2594. * 判断`Uplaode`r是否正在上传中。
  2595. * @grammar isInProgress() => Boolean
  2596. * @method isInProgress
  2597. * @for Uploader
  2598. */
  2599. isInProgress: function () {
  2600. return !!this.runing;
  2601. },
  2602. getStats: function () {
  2603. return this.request('get-stats');
  2604. },
  2605. /**
  2606. * 掉过一个文件上传,直接标记指定文件为已上传状态。
  2607. * @grammar skipFile( file ) => undefined
  2608. * @method skipFile
  2609. * @for Uploader
  2610. */
  2611. skipFile: function (file, status) {
  2612. file = this.request('get-file', file);
  2613. file.setStatus(status || Status.COMPLETE);
  2614. file.skipped = true;
  2615. // 如果正在上传。
  2616. file.blocks && $.each(file.blocks, function (_, v) {
  2617. var _tr = v.transport;
  2618. if (_tr) {
  2619. _tr.abort();
  2620. _tr.destroy();
  2621. delete v.transport;
  2622. }
  2623. });
  2624. this.owner.trigger('uploadSkip', file);
  2625. },
  2626. /**
  2627. * @event uploadFinished
  2628. * @description 当所有文件上传结束时触发。
  2629. * @for Uploader
  2630. */
  2631. _tick: function () {
  2632. var me = this,
  2633. opts = me.options,
  2634. fn, val;
  2635. // 上一个promise还没有结束,则等待完成后再执行。
  2636. if (me._promise) {
  2637. return me._promise.always(me.__tick);
  2638. }
  2639. // 还有位置,且还有文件要处理的话。
  2640. if (me.pool.length < opts.threads && (val = me._nextBlock())) {
  2641. me._trigged = false;
  2642. fn = function (val) {
  2643. me._promise = null;
  2644. // 有可能是reject过来的,所以要检测val的类型。
  2645. val && val.file && me._startSend(val);
  2646. Base.nextTick(me.__tick);
  2647. };
  2648. me._promise = isPromise(val) ? val.always(fn) : fn(val);
  2649. // 没有要上传的了,且没有正在传输的了。
  2650. } else if (!me.remaning && !me.getStats().numOfQueue) {
  2651. me.runing = false;
  2652. me._trigged || Base.nextTick(function () {
  2653. me.owner.trigger('uploadFinished');
  2654. });
  2655. me._trigged = true;
  2656. }
  2657. },
  2658. _nextBlock: function () {
  2659. var me = this,
  2660. act = me._act,
  2661. opts = me.options,
  2662. next, done;
  2663. // 如果当前文件还有没有需要传输的,则直接返回剩下的。
  2664. if (act && act.has() &&
  2665. act.file.getStatus() === Status.PROGRESS) {
  2666. // 是否提前准备下一个文件
  2667. if (opts.prepareNextFile && !me.pending.length) {
  2668. me._prepareNextFile();
  2669. }
  2670. return act.fetch();
  2671. // 否则,如果正在运行,则准备下一个文件,并等待完成后返回下个分片。
  2672. } else if (me.runing) {
  2673. // 如果缓存中有,则直接在缓存中取,没有则去queue中取。
  2674. if (!me.pending.length && me.getStats().numOfQueue) {
  2675. me._prepareNextFile();
  2676. }
  2677. next = me.pending.shift();
  2678. done = function (file) {
  2679. if (!file) {
  2680. return null;
  2681. }
  2682. act = CuteFile(file, opts.chunked ? opts.chunkSize : 0);
  2683. me._act = act;
  2684. return act.fetch();
  2685. };
  2686. // 文件可能还在prepare中,也有可能已经完全准备好了。
  2687. return isPromise(next) ?
  2688. next[next.pipe ? 'pipe' : 'then'](done) :
  2689. done(next);
  2690. }
  2691. },
  2692. /**
  2693. * @event uploadStart
  2694. * @param {File} file File对象
  2695. * @description 某个文件开始上传前触发,一个文件只会触发一次。
  2696. * @for Uploader
  2697. */
  2698. _prepareNextFile: function () {
  2699. var me = this,
  2700. file = me.request('fetch-file'),
  2701. pending = me.pending,
  2702. promise;
  2703. if (file) {
  2704. promise = me.request('before-send-file', file, function () {
  2705. // 有可能文件被skip掉了。文件被skip掉后,状态坑定不是Queued.
  2706. if (file.getStatus() === Status.QUEUED) {
  2707. me.owner.trigger('uploadStart', file);
  2708. file.setStatus(Status.PROGRESS);
  2709. return file;
  2710. }
  2711. return me._finishFile(file);
  2712. });
  2713. // 如果还在pending中,则替换成文件本身。
  2714. promise.done(function () {
  2715. var idx = $.inArray(promise, pending);
  2716. ~idx && pending.splice(idx, 1, file);
  2717. });
  2718. // befeore-send-file的钩子就有错误发生。
  2719. promise.fail(function (reason) {
  2720. file.setStatus(Status.ERROR, reason);
  2721. me.owner.trigger('uploadError', file, reason);
  2722. me.owner.trigger('uploadComplete', file);
  2723. });
  2724. pending.push(promise);
  2725. }
  2726. },
  2727. // 让出位置了,可以让其他分片开始上传
  2728. _popBlock: function (block) {
  2729. var idx = $.inArray(block, this.pool);
  2730. this.pool.splice(idx, 1);
  2731. block.file.remaning--;
  2732. this.remaning--;
  2733. },
  2734. // 开始上传,可以被掉过。如果promise被reject了,则表示跳过此分片。
  2735. _startSend: function (block) {
  2736. var me = this,
  2737. file = block.file,
  2738. promise;
  2739. me.pool.push(block);
  2740. me.remaning++;
  2741. // 如果没有分片,则直接使用原始的。
  2742. // 不会丢失content-type信息。
  2743. block.blob = block.chunks === 1 ? file.source :
  2744. file.source.slice(block.start, block.end);
  2745. // hook, 每个分片发送之前可能要做些异步的事情。
  2746. promise = me.request('before-send', block, function () {
  2747. // 有可能文件已经上传出错了,所以不需要再传输了。
  2748. if (file.getStatus() === Status.PROGRESS) {
  2749. me._doSend(block);
  2750. } else {
  2751. me._popBlock(block);
  2752. Base.nextTick(me.__tick);
  2753. }
  2754. });
  2755. // 如果为fail了,则跳过此分片。
  2756. promise.fail(function () {
  2757. if (file.remaning === 1) {
  2758. me._finishFile(file).always(function () {
  2759. block.percentage = 1;
  2760. me._popBlock(block);
  2761. me.owner.trigger('uploadComplete', file);
  2762. Base.nextTick(me.__tick);
  2763. });
  2764. } else {
  2765. block.percentage = 1;
  2766. me._popBlock(block);
  2767. Base.nextTick(me.__tick);
  2768. }
  2769. });
  2770. },
  2771. /**
  2772. * @event uploadBeforeSend
  2773. * @param {Object} object
  2774. * @param {Object} data 默认的上传参数,可以扩展此对象来控制上传参数。
  2775. * @description 当某个文件的分块在发送前触发,主要用来询问是否要添加附带参数,大文件在开起分片上传的前提下此事件可能会触发多次。
  2776. * @for Uploader
  2777. */
  2778. /**
  2779. * @event uploadAccept
  2780. * @param {Object} object
  2781. * @param {Object} ret 服务端的返回数据,json格式,如果服务端不是json格式,从ret._raw中取数据,自行解析。
  2782. * @description 当某个文件上传到服务端响应后,会派送此事件来询问服务端响应是否有效。如果此事件handler返回值为`false`, 则此文件将派送`server`类型的`uploadError`事件。
  2783. * @for Uploader
  2784. */
  2785. /**
  2786. * @event uploadProgress
  2787. * @param {File} file File对象
  2788. * @param {Number} percentage 上传进度
  2789. * @description 上传过程中触发,携带上传进度。
  2790. * @for Uploader
  2791. */
  2792. /**
  2793. * @event uploadError
  2794. * @param {File} file File对象
  2795. * @param {String} reason 出错的code
  2796. * @description 当文件上传出错时触发。
  2797. * @for Uploader
  2798. */
  2799. /**
  2800. * @event uploadSuccess
  2801. * @param {File} file File对象
  2802. * @param {Object} response 服务端返回的数据
  2803. * @description 当文件上传成功时触发。
  2804. * @for Uploader
  2805. */
  2806. /**
  2807. * @event uploadComplete
  2808. * @param {File} [file] File对象
  2809. * @description 不管成功或者失败,文件上传完成时触发。
  2810. * @for Uploader
  2811. */
  2812. // 做上传操作。
  2813. _doSend: function (block) {
  2814. var me = this,
  2815. owner = me.owner,
  2816. opts = me.options,
  2817. file = block.file,
  2818. tr = new Transport(opts),
  2819. data = $.extend({}, opts.formData),
  2820. headers = $.extend({}, opts.headers),
  2821. requestAccept, ret;
  2822. block.transport = tr;
  2823. tr.on('destroy', function () {
  2824. delete block.transport;
  2825. me._popBlock(block);
  2826. Base.nextTick(me.__tick);
  2827. });
  2828. // 广播上传进度。以文件为单位。
  2829. tr.on('progress', function (percentage) {
  2830. var totalPercent = 0,
  2831. uploaded = 0;
  2832. // 可能没有abort掉,progress还是执行进来了。
  2833. // if ( !file.blocks ) {
  2834. // return;
  2835. // }
  2836. totalPercent = block.percentage = percentage;
  2837. if (block.chunks > 1) { // 计算文件的整体速度。
  2838. $.each(file.blocks, function (_, v) {
  2839. uploaded += (v.percentage || 0) * (v.end - v.start);
  2840. });
  2841. totalPercent = uploaded / file.size;
  2842. }
  2843. owner.trigger('uploadProgress', file, totalPercent || 0);
  2844. });
  2845. // 用来询问,是否返回的结果是有错误的。
  2846. requestAccept = function (reject) {
  2847. var fn;
  2848. ret = tr.getResponseAsJson() || {};
  2849. ret._raw = tr.getResponse();
  2850. fn = function (value) {
  2851. reject = value;
  2852. };
  2853. // 服务端响应了,不代表成功了,询问是否响应正确。
  2854. if (!owner.trigger('uploadAccept', block, ret, fn)) {
  2855. reject = reject || 'server';
  2856. }
  2857. return reject;
  2858. };
  2859. // 尝试重试,然后广播文件上传出错。
  2860. tr.on('error', function (type, flag) {
  2861. block.retried = block.retried || 0;
  2862. // 自动重试
  2863. if (block.chunks > 1 && ~'http,abort'.indexOf(type) &&
  2864. block.retried < opts.chunkRetry) {
  2865. block.retried++;
  2866. tr.send();
  2867. } else {
  2868. // http status 500 ~ 600
  2869. if (!flag && type === 'server') {
  2870. type = requestAccept(type);
  2871. }
  2872. file.setStatus(Status.ERROR, type);
  2873. owner.trigger('uploadError', file, type);
  2874. owner.trigger('uploadComplete', file);
  2875. }
  2876. });
  2877. // 上传成功
  2878. tr.on('load', function () {
  2879. var reason;
  2880. // 如果非预期,转向上传出错。
  2881. if ((reason = requestAccept())) {
  2882. tr.trigger('error', reason, true);
  2883. return;
  2884. }
  2885. // 全部上传完成。
  2886. if (file.remaning === 1) {
  2887. me._finishFile(file, ret);
  2888. } else {
  2889. tr.destroy();
  2890. }
  2891. });
  2892. // 配置默认的上传字段。
  2893. data = $.extend(data, {
  2894. id: file.id,
  2895. name: file.name,
  2896. type: file.type,
  2897. lastModifiedDate: file.lastModifiedDate,
  2898. size: file.size
  2899. });
  2900. block.chunks > 1 && $.extend(data, {
  2901. chunks: block.chunks,
  2902. chunk: block.chunk
  2903. });
  2904. // 在发送之间可以添加字段什么的。。。
  2905. // 如果默认的字段不够使用,可以通过监听此事件来扩展
  2906. owner.trigger('uploadBeforeSend', block, data, headers);
  2907. // 开始发送。
  2908. tr.appendBlob(opts.fileVal, block.blob, file.name);
  2909. tr.append(data);
  2910. tr.setRequestHeader(headers);
  2911. tr.send();
  2912. },
  2913. // 完成上传。
  2914. _finishFile: function (file, ret, hds) {
  2915. var owner = this.owner;
  2916. return owner
  2917. .request('after-send-file', arguments, function () {
  2918. file.setStatus(Status.COMPLETE);
  2919. owner.trigger('uploadSuccess', file, ret, hds);
  2920. })
  2921. .fail(function (reason) {
  2922. // 如果外部已经标记为invalid什么的,不再改状态。
  2923. if (file.getStatus() === Status.PROGRESS) {
  2924. file.setStatus(Status.ERROR, reason);
  2925. }
  2926. owner.trigger('uploadError', file, reason);
  2927. })
  2928. .always(function () {
  2929. owner.trigger('uploadComplete', file);
  2930. });
  2931. }
  2932. });
  2933. });
  2934. /**
  2935. * @fileOverview 各种验证,包括文件总大小是否超出、单文件是否超出和文件是否重复。
  2936. */
  2937. define('widgets/validator', [
  2938. 'base',
  2939. 'uploader',
  2940. 'file',
  2941. 'widgets/widget'
  2942. ], function (Base, Uploader, WUFile) {
  2943. var $ = Base.$,
  2944. validators = {},
  2945. api;
  2946. /**
  2947. * @event error
  2948. * @param {String} type 错误类型。
  2949. * @description 当validate不通过时,会以派送错误事件的形式通知调用者。通过`upload.on('error', handler)`可以捕获到此类错误,目前有以下错误会在特定的情况下派送错来。
  2950. *
  2951. * * `Q_EXCEED_NUM_LIMIT` 在设置了`fileNumLimit`且尝试给`uploader`添加的文件数量超出这个值时派送。
  2952. * * `Q_EXCEED_SIZE_LIMIT` 在设置了`Q_EXCEED_SIZE_LIMIT`且尝试给`uploader`添加的文件总大小超出这个值时派送。
  2953. * @for Uploader
  2954. */
  2955. // 暴露给外面的api
  2956. api = {
  2957. // 添加验证器
  2958. addValidator: function (type, cb) {
  2959. validators[type] = cb;
  2960. },
  2961. // 移除验证器
  2962. removeValidator: function (type) {
  2963. delete validators[type];
  2964. }
  2965. };
  2966. // 在Uploader初始化的时候启动Validators的初始化
  2967. Uploader.register({
  2968. init: function () {
  2969. var me = this;
  2970. $.each(validators, function () {
  2971. this.call(me.owner);
  2972. });
  2973. }
  2974. });
  2975. /**
  2976. * @property {int} [fileNumLimit=undefined]
  2977. * @namespace options
  2978. * @for Uploader
  2979. * @description 验证文件总数量, 超出则不允许加入队列。
  2980. */
  2981. api.addValidator('fileNumLimit', function () {
  2982. var uploader = this,
  2983. opts = uploader.options,
  2984. count = 0,
  2985. max = opts.fileNumLimit >> 0,
  2986. flag = true;
  2987. if (!max) {
  2988. return;
  2989. }
  2990. uploader.on('beforeFileQueued', function (file) {
  2991. if (count >= max && flag) {
  2992. flag = false;
  2993. this.trigger('error', 'Q_EXCEED_NUM_LIMIT', max, file);
  2994. setTimeout(function () {
  2995. flag = true;
  2996. }, 1);
  2997. }
  2998. return count >= max ? false : true;
  2999. });
  3000. uploader.on('fileQueued', function () {
  3001. count++;
  3002. });
  3003. uploader.on('fileDequeued', function () {
  3004. count--;
  3005. });
  3006. uploader.on('uploadFinished', function () {
  3007. count = 0;
  3008. });
  3009. });
  3010. /**
  3011. * @property {int} [fileSizeLimit=undefined]
  3012. * @namespace options
  3013. * @for Uploader
  3014. * @description 验证文件总大小是否超出限制, 超出则不允许加入队列。
  3015. */
  3016. api.addValidator('fileSizeLimit', function () {
  3017. var uploader = this,
  3018. opts = uploader.options,
  3019. count = 0,
  3020. max = opts.fileSizeLimit >> 0,
  3021. flag = true;
  3022. if (!max) {
  3023. return;
  3024. }
  3025. uploader.on('beforeFileQueued', function (file) {
  3026. var invalid = count + file.size > max;
  3027. if (invalid && flag) {
  3028. flag = false;
  3029. this.trigger('error', 'Q_EXCEED_SIZE_LIMIT', max, file);
  3030. setTimeout(function () {
  3031. flag = true;
  3032. }, 1);
  3033. }
  3034. return invalid ? false : true;
  3035. });
  3036. uploader.on('fileQueued', function (file) {
  3037. count += file.size;
  3038. });
  3039. uploader.on('fileDequeued', function (file) {
  3040. count -= file.size;
  3041. });
  3042. uploader.on('uploadFinished', function () {
  3043. count = 0;
  3044. });
  3045. });
  3046. /**
  3047. * @property {int} [fileSingleSizeLimit=undefined]
  3048. * @namespace options
  3049. * @for Uploader
  3050. * @description 验证单个文件大小是否超出限制, 超出则不允许加入队列。
  3051. */
  3052. api.addValidator('fileSingleSizeLimit', function () {
  3053. var uploader = this,
  3054. opts = uploader.options,
  3055. max = opts.fileSingleSizeLimit;
  3056. if (!max) {
  3057. return;
  3058. }
  3059. uploader.on('beforeFileQueued', function (file) {
  3060. if (file.size > max) {
  3061. file.setStatus(WUFile.Status.INVALID, 'exceed_size');
  3062. this.trigger('error', 'F_EXCEED_SIZE', file);
  3063. return false;
  3064. }
  3065. });
  3066. });
  3067. /**
  3068. * @property {int} [duplicate=undefined]
  3069. * @namespace options
  3070. * @for Uploader
  3071. * @description 去重, 根据文件名字、文件大小和最后修改时间来生成hash Key.
  3072. */
  3073. api.addValidator('duplicate', function () {
  3074. var uploader = this,
  3075. opts = uploader.options,
  3076. mapping = {};
  3077. if (opts.duplicate) {
  3078. return;
  3079. }
  3080. function hashString(str) {
  3081. var hash = 0,
  3082. i = 0,
  3083. len = str.length,
  3084. _char;
  3085. for (; i < len; i++) {
  3086. _char = str.charCodeAt(i);
  3087. hash = _char + (hash << 6) + (hash << 16) - hash;
  3088. }
  3089. return hash;
  3090. }
  3091. uploader.on('beforeFileQueued', function (file) {
  3092. var hash = file.__hash || (file.__hash = hashString(file.name +
  3093. file.size + file.lastModifiedDate));
  3094. // 已经重复了
  3095. if (mapping[hash]) {
  3096. this.trigger('error', 'F_DUPLICATE', file);
  3097. return false;
  3098. }
  3099. });
  3100. uploader.on('fileQueued', function (file) {
  3101. var hash = file.__hash;
  3102. hash && (mapping[hash] = true);
  3103. });
  3104. uploader.on('fileDequeued', function (file) {
  3105. var hash = file.__hash;
  3106. hash && (delete mapping[hash]);
  3107. });
  3108. });
  3109. return api;
  3110. });
  3111. /**
  3112. * @fileOverview Runtime管理器,负责Runtime的选择, 连接
  3113. */
  3114. define('runtime/compbase', [], function () {
  3115. function CompBase(owner, runtime) {
  3116. this.owner = owner;
  3117. this.options = owner.options;
  3118. this.getRuntime = function () {
  3119. return runtime;
  3120. };
  3121. this.getRuid = function () {
  3122. return runtime.uid;
  3123. };
  3124. this.trigger = function () {
  3125. return owner.trigger.apply(owner, arguments);
  3126. };
  3127. }
  3128. return CompBase;
  3129. });
  3130. /**
  3131. * @fileOverview FlashRuntime
  3132. */
  3133. define('runtime/flash/runtime', [
  3134. 'base',
  3135. 'runtime/runtime',
  3136. 'runtime/compbase'
  3137. ], function (Base, Runtime, CompBase) {
  3138. var $ = Base.$,
  3139. type = 'flash',
  3140. components = {};
  3141. function getFlashVersion() {
  3142. var version;
  3143. try {
  3144. version = navigator.plugins['Shockwave Flash'];
  3145. version = version.description;
  3146. } catch (ex) {
  3147. try {
  3148. version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash')
  3149. .GetVariable('$version');
  3150. } catch (ex2) {
  3151. version = '0.0';
  3152. }
  3153. }
  3154. version = version.match(/\d+/g);
  3155. return parseFloat(version[0] + '.' + version[1], 10);
  3156. }
  3157. function FlashRuntime() {
  3158. var pool = {},
  3159. clients = {},
  3160. destory = this.destory,
  3161. me = this,
  3162. jsreciver = Base.guid('webuploader_');
  3163. Runtime.apply(me, arguments);
  3164. me.type = type;
  3165. // 这个方法的调用者,实际上是RuntimeClient
  3166. me.exec = function (comp, fn/*, args...*/) {
  3167. var client = this,
  3168. uid = client.uid,
  3169. args = Base.slice(arguments, 2),
  3170. instance;
  3171. clients[uid] = client;
  3172. if (components[comp]) {
  3173. if (!pool[uid]) {
  3174. pool[uid] = new components[comp](client, me);
  3175. }
  3176. instance = pool[uid];
  3177. if (instance[fn]) {
  3178. return instance[fn].apply(instance, args);
  3179. }
  3180. }
  3181. return me.flashExec.apply(client, arguments);
  3182. };
  3183. function handler(evt, obj) {
  3184. var type = evt.type || evt,
  3185. parts, uid;
  3186. parts = type.split('::');
  3187. uid = parts[0];
  3188. type = parts[1];
  3189. // console.log.apply( console, arguments );
  3190. if (type === 'Ready' && uid === me.uid) {
  3191. me.trigger('ready');
  3192. } else if (clients[uid]) {
  3193. clients[uid].trigger(type.toLowerCase(), evt, obj);
  3194. }
  3195. // Base.log( evt, obj );
  3196. }
  3197. // flash的接受器。
  3198. window[jsreciver] = function () {
  3199. var args = arguments;
  3200. // 为了能捕获得到。
  3201. setTimeout(function () {
  3202. handler.apply(null, args);
  3203. }, 1);
  3204. };
  3205. this.jsreciver = jsreciver;
  3206. this.destory = function () {
  3207. // @todo 删除池子中的所有实例
  3208. return destory && destory.apply(this, arguments);
  3209. };
  3210. this.flashExec = function (comp, fn) {
  3211. var flash = me.getFlash(),
  3212. args = Base.slice(arguments, 2);
  3213. return flash.exec(this.uid, comp, fn, args);
  3214. };
  3215. // @todo
  3216. }
  3217. Base.inherits(Runtime, {
  3218. constructor: FlashRuntime,
  3219. init: function () {
  3220. var container = this.getContainer(),
  3221. opts = this.options,
  3222. html;
  3223. // if not the minimal height, shims are not initialized
  3224. // in older browsers (e.g FF3.6, IE6,7,8, Safari 4.0,5.0, etc)
  3225. container.css({
  3226. position: 'absolute',
  3227. top: '-8px',
  3228. left: '-8px',
  3229. width: '9px',
  3230. height: '9px',
  3231. overflow: 'hidden'
  3232. });
  3233. // insert flash object
  3234. html = '<object id="' + this.uid + '" type="application/' +
  3235. 'x-shockwave-flash" data="' + opts.swf + '" ';
  3236. if (Base.browser.ie) {
  3237. html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
  3238. }
  3239. html += 'width="100%" height="100%" style="outline:0">' +
  3240. '<param name="movie" value="' + opts.swf + '" />' +
  3241. '<param name="flashvars" value="uid=' + this.uid +
  3242. '&jsreciver=' + this.jsreciver + '" />' +
  3243. '<param name="wmode" value="transparent" />' +
  3244. '<param name="allowscriptaccess" value="always" />' +
  3245. '</object>';
  3246. container.html(html);
  3247. },
  3248. getFlash: function () {
  3249. if (this._flash) {
  3250. return this._flash;
  3251. }
  3252. this._flash = $('#' + this.uid).get(0);
  3253. return this._flash;
  3254. }
  3255. });
  3256. FlashRuntime.register = function (name, component) {
  3257. component = components[name] = Base.inherits(CompBase, $.extend({
  3258. // @todo fix this later
  3259. flashExec: function () {
  3260. var owner = this.owner,
  3261. runtime = this.getRuntime();
  3262. return runtime.flashExec.apply(owner, arguments);
  3263. }
  3264. }, component));
  3265. return component;
  3266. };
  3267. if (getFlashVersion() >= 11.4) {
  3268. Runtime.addRuntime(type, FlashRuntime);
  3269. }
  3270. return FlashRuntime;
  3271. });
  3272. /**
  3273. * @fileOverview FilePicker
  3274. */
  3275. define('runtime/flash/filepicker', [
  3276. 'base',
  3277. 'runtime/flash/runtime'
  3278. ], function (Base, FlashRuntime) {
  3279. var $ = Base.$;
  3280. return FlashRuntime.register('FilePicker', {
  3281. init: function (opts) {
  3282. var copy = $.extend({}, opts),
  3283. len, i;
  3284. // 修复Flash再没有设置title的情况下无法弹出flash文件选择框的bug.
  3285. len = copy.accept && copy.accept.length;
  3286. for (i = 0; i < len; i++) {
  3287. if (!copy.accept[i].title) {
  3288. copy.accept[i].title = 'Files';
  3289. }
  3290. }
  3291. delete copy.button;
  3292. delete copy.container;
  3293. this.flashExec('FilePicker', 'init', copy);
  3294. },
  3295. destroy: function () {
  3296. // todo
  3297. }
  3298. });
  3299. });
  3300. /**
  3301. * @fileOverview 图片压缩
  3302. */
  3303. define('runtime/flash/image', [
  3304. 'runtime/flash/runtime'
  3305. ], function (FlashRuntime) {
  3306. return FlashRuntime.register('Image', {
  3307. // init: function( options ) {
  3308. // var owner = this.owner;
  3309. // this.flashExec( 'Image', 'init', options );
  3310. // owner.on( 'load', function() {
  3311. // debugger;
  3312. // });
  3313. // },
  3314. loadFromBlob: function (blob) {
  3315. var owner = this.owner;
  3316. owner.info() && this.flashExec('Image', 'info', owner.info());
  3317. owner.meta() && this.flashExec('Image', 'meta', owner.meta());
  3318. this.flashExec('Image', 'loadFromBlob', blob.uid);
  3319. }
  3320. });
  3321. });
  3322. /**
  3323. * @fileOverview Transport flash实现
  3324. */
  3325. define('runtime/flash/transport', [
  3326. 'base',
  3327. 'runtime/flash/runtime',
  3328. 'runtime/client'
  3329. ], function (Base, FlashRuntime, RuntimeClient) {
  3330. var $ = Base.$;
  3331. return FlashRuntime.register('Transport', {
  3332. init: function () {
  3333. this._status = 0;
  3334. this._response = null;
  3335. this._responseJson = null;
  3336. },
  3337. send: function () {
  3338. var owner = this.owner,
  3339. opts = this.options,
  3340. xhr = this._initAjax(),
  3341. blob = owner._blob,
  3342. server = opts.server,
  3343. binary;
  3344. xhr.connectRuntime(blob.ruid);
  3345. if (opts.sendAsBinary) {
  3346. server += (/\?/.test(server) ? '&' : '?') +
  3347. $.param(owner._formData);
  3348. binary = blob.uid;
  3349. } else {
  3350. $.each(owner._formData, function (k, v) {
  3351. xhr.exec('append', k, v);
  3352. });
  3353. xhr.exec('appendBlob', opts.fileVal, blob.uid,
  3354. opts.filename || owner._formData.name || '');
  3355. }
  3356. this._setRequestHeader(xhr, opts.headers);
  3357. xhr.exec('send', {
  3358. method: opts.method,
  3359. url: server
  3360. }, binary);
  3361. },
  3362. getStatus: function () {
  3363. return this._status;
  3364. },
  3365. getResponse: function () {
  3366. return this._response;
  3367. },
  3368. getResponseAsJson: function () {
  3369. return this._responseJson;
  3370. },
  3371. abort: function () {
  3372. var xhr = this._xhr;
  3373. if (xhr) {
  3374. xhr.exec('abort');
  3375. xhr.destroy();
  3376. this._xhr = xhr = null;
  3377. }
  3378. },
  3379. destroy: function () {
  3380. this.abort();
  3381. },
  3382. _initAjax: function () {
  3383. var me = this,
  3384. xhr = new RuntimeClient('XMLHttpRequest');
  3385. xhr.on('uploadprogress progress', function (e) {
  3386. return me.trigger('progress', e.loaded / e.total);
  3387. });
  3388. xhr.on('load', function () {
  3389. var status = xhr.exec('getStatus'),
  3390. err = '';
  3391. xhr.off();
  3392. me._xhr = null;
  3393. if (status >= 200 && status < 300) {
  3394. me._response = xhr.exec('getResponse');
  3395. me._responseJson = xhr.exec('getResponseAsJson');
  3396. } else if (status >= 500 && status < 600) {
  3397. me._response = xhr.exec('getResponse');
  3398. me._responseJson = xhr.exec('getResponseAsJson');
  3399. err = 'server';
  3400. } else {
  3401. err = 'http';
  3402. }
  3403. xhr.destroy();
  3404. xhr = null;
  3405. return err ? me.trigger('error', err) : me.trigger('load');
  3406. });
  3407. xhr.on('error', function () {
  3408. xhr.off();
  3409. me._xhr = null;
  3410. me.trigger('error', 'http');
  3411. });
  3412. me._xhr = xhr;
  3413. return xhr;
  3414. },
  3415. _setRequestHeader: function (xhr, headers) {
  3416. $.each(headers, function (key, val) {
  3417. xhr.exec('setRequestHeader', key, val);
  3418. });
  3419. }
  3420. });
  3421. });
  3422. /**
  3423. * @fileOverview 只有flash实现的文件版本。
  3424. */
  3425. define('preset/flashonly', [
  3426. 'base',
  3427. // widgets
  3428. 'widgets/filepicker',
  3429. 'widgets/image',
  3430. 'widgets/queue',
  3431. 'widgets/runtime',
  3432. 'widgets/upload',
  3433. 'widgets/validator',
  3434. // runtimes
  3435. // flash
  3436. 'runtime/flash/filepicker',
  3437. 'runtime/flash/image',
  3438. 'runtime/flash/transport'
  3439. ], function (Base) {
  3440. return Base;
  3441. });
  3442. define('webuploader', [
  3443. 'preset/flashonly'
  3444. ], function (preset) {
  3445. return preset;
  3446. });
  3447. return require('webuploader');
  3448. });