You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4176 lines
136 KiB

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