农燊高科官方网站
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

4042 lignes
129 KiB

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