webuploader.flashonly.js 110 KB

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