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.

5559 lines
182 KiB

7 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 错误信息
  951. */
  952. define('lib/dnd',[
  953. 'base',
  954. 'mediator',
  955. 'runtime/client'
  956. ], function( Base, Mediator, RuntimeClent ) {
  957. var $ = Base.$;
  958. function DragAndDrop( opts ) {
  959. opts = this.options = $.extend({}, DragAndDrop.options, opts );
  960. opts.container = $( opts.container );
  961. if ( !opts.container.length ) {
  962. return;
  963. }
  964. RuntimeClent.call( this, 'DragAndDrop' );
  965. }
  966. DragAndDrop.options = {
  967. accept: null,
  968. disableGlobalDnd: false
  969. };
  970. Base.inherits( RuntimeClent, {
  971. constructor: DragAndDrop,
  972. init: function() {
  973. var me = this;
  974. me.connectRuntime( me.options, function() {
  975. me.exec('init');
  976. me.trigger('ready');
  977. });
  978. },
  979. destroy: function() {
  980. this.disconnectRuntime();
  981. }
  982. });
  983. Mediator.installTo( DragAndDrop.prototype );
  984. return DragAndDrop;
  985. });
  986. /**
  987. * @fileOverview 组件基类
  988. */
  989. define('widgets/widget',[
  990. 'base',
  991. 'uploader'
  992. ], function( Base, Uploader ) {
  993. var $ = Base.$,
  994. _init = Uploader.prototype._init,
  995. IGNORE = {},
  996. widgetClass = [];
  997. function isArrayLike( obj ) {
  998. if ( !obj ) {
  999. return false;
  1000. }
  1001. var length = obj.length,
  1002. type = $.type( obj );
  1003. if ( obj.nodeType === 1 && length ) {
  1004. return true;
  1005. }
  1006. return type === 'array' || type !== 'function' && type !== 'string' &&
  1007. (length === 0 || typeof length === 'number' && length > 0 &&
  1008. (length - 1) in obj);
  1009. }
  1010. function Widget( uploader ) {
  1011. this.owner = uploader;
  1012. this.options = uploader.options;
  1013. }
  1014. $.extend( Widget.prototype, {
  1015. init: Base.noop,
  1016. // 类Backbone的事件监听声明,监听uploader实例上的事件
  1017. // widget直接无法监听事件,事件只能通过uploader来传递
  1018. invoke: function( apiName, args ) {
  1019. /*
  1020. {
  1021. 'make-thumb': 'makeThumb'
  1022. }
  1023. */
  1024. var map = this.responseMap;
  1025. // 如果无API响应声明则忽略
  1026. if ( !map || !(apiName in map) || !(map[ apiName ] in this) ||
  1027. !$.isFunction( this[ map[ apiName ] ] ) ) {
  1028. return IGNORE;
  1029. }
  1030. return this[ map[ apiName ] ].apply( this, args );
  1031. },
  1032. /**
  1033. * 发送命令当传入`callback`或者`handler`中返回`promise`返回一个当所有`handler`中的promise都完成后完成的新`promise`
  1034. * @method request
  1035. * @grammar request( command, args ) => * | Promise
  1036. * @grammar request( command, args, callback ) => Promise
  1037. * @for Uploader
  1038. */
  1039. request: function() {
  1040. return this.owner.request.apply( this.owner, arguments );
  1041. }
  1042. });
  1043. // 扩展Uploader.
  1044. $.extend( Uploader.prototype, {
  1045. // 覆写_init用来初始化widgets
  1046. _init: function() {
  1047. var me = this,
  1048. widgets = me._widgets = [];
  1049. $.each( widgetClass, function( _, klass ) {
  1050. widgets.push( new klass( me ) );
  1051. });
  1052. return _init.apply( me, arguments );
  1053. },
  1054. request: function( apiName, args, callback ) {
  1055. var i = 0,
  1056. widgets = this._widgets,
  1057. len = widgets.length,
  1058. rlts = [],
  1059. dfds = [],
  1060. widget, rlt, promise, key;
  1061. args = isArrayLike( args ) ? args : [ args ];
  1062. for ( ; i < len; i++ ) {
  1063. widget = widgets[ i ];
  1064. rlt = widget.invoke( apiName, args );
  1065. if ( rlt !== IGNORE ) {
  1066. // Deferred对象
  1067. if ( Base.isPromise( rlt ) ) {
  1068. dfds.push( rlt );
  1069. } else {
  1070. rlts.push( rlt );
  1071. }
  1072. }
  1073. }
  1074. // 如果有callback,则用异步方式。
  1075. if ( callback || dfds.length ) {
  1076. promise = Base.when.apply( Base, dfds );
  1077. key = promise.pipe ? 'pipe' : 'then';
  1078. // 很重要不能删除。删除了会死循环。
  1079. // 保证执行顺序。让callback总是在下一个tick中执行。
  1080. return promise[ key ](function() {
  1081. var deferred = Base.Deferred(),
  1082. args = arguments;
  1083. setTimeout(function() {
  1084. deferred.resolve.apply( deferred, args );
  1085. }, 1 );
  1086. return deferred.promise();
  1087. })[ key ]( callback || Base.noop );
  1088. } else {
  1089. return rlts[ 0 ];
  1090. }
  1091. }
  1092. });
  1093. /**
  1094. * 添加组件
  1095. * @param {object} widgetProto 组件原型构造函数通过constructor属性定义
  1096. * @param {object} responseMap API名称与函数实现的映射
  1097. * @example
  1098. * Uploader.register( {
  1099. * init: function( options ) {},
  1100. * makeThumb: function() {}
  1101. * }, {
  1102. * 'make-thumb': 'makeThumb'
  1103. * } );
  1104. */
  1105. Uploader.register = Widget.register = function( responseMap, widgetProto ) {
  1106. var map = { init: 'init' },
  1107. klass;
  1108. if ( arguments.length === 1 ) {
  1109. widgetProto = responseMap;
  1110. widgetProto.responseMap = map;
  1111. } else {
  1112. widgetProto.responseMap = $.extend( map, responseMap );
  1113. }
  1114. klass = Base.inherits( Widget, widgetProto );
  1115. widgetClass.push( klass );
  1116. return klass;
  1117. };
  1118. return Widget;
  1119. });
  1120. /**
  1121. * @fileOverview DragAndDrop Widget
  1122. */
  1123. define('widgets/filednd',[
  1124. 'base',
  1125. 'uploader',
  1126. 'lib/dnd',
  1127. 'widgets/widget'
  1128. ], function( Base, Uploader, Dnd ) {
  1129. var $ = Base.$;
  1130. Uploader.options.dnd = '';
  1131. /**
  1132. * @property {Selector} [dnd=undefined] 指定Drag And Drop拖拽的容器如果不指定则不启动
  1133. * @namespace options
  1134. * @for Uploader
  1135. */
  1136. /**
  1137. * @event dndAccept
  1138. * @param {DataTransferItemList} items DataTransferItem
  1139. * @description 阻止此事件可以拒绝某些类型的文件拖入进来目前只有 chrome 提供这样的 API且只能通过 mime-type 验证
  1140. * @for Uploader
  1141. */
  1142. return Uploader.register({
  1143. init: function( opts ) {
  1144. if ( !opts.dnd ||
  1145. this.request('predict-runtime-type') !== 'html5' ) {
  1146. return;
  1147. }
  1148. var me = this,
  1149. deferred = Base.Deferred(),
  1150. options = $.extend({}, {
  1151. disableGlobalDnd: opts.disableGlobalDnd,
  1152. container: opts.dnd,
  1153. accept: opts.accept
  1154. }),
  1155. dnd;
  1156. dnd = new Dnd( options );
  1157. dnd.once( 'ready', deferred.resolve );
  1158. dnd.on( 'drop', function( files ) {
  1159. me.request( 'add-file', [ files ]);
  1160. });
  1161. // 检测文件是否全部允许添加。
  1162. dnd.on( 'accept', function( items ) {
  1163. return me.owner.trigger( 'dndAccept', items );
  1164. });
  1165. dnd.init();
  1166. return deferred.promise();
  1167. }
  1168. });
  1169. });
  1170. /**
  1171. * @fileOverview 错误信息
  1172. */
  1173. define('lib/filepaste',[
  1174. 'base',
  1175. 'mediator',
  1176. 'runtime/client'
  1177. ], function( Base, Mediator, RuntimeClent ) {
  1178. var $ = Base.$;
  1179. function FilePaste( opts ) {
  1180. opts = this.options = $.extend({}, opts );
  1181. opts.container = $( opts.container || document.body );
  1182. RuntimeClent.call( this, 'FilePaste' );
  1183. }
  1184. Base.inherits( RuntimeClent, {
  1185. constructor: FilePaste,
  1186. init: function() {
  1187. var me = this;
  1188. me.connectRuntime( me.options, function() {
  1189. me.exec('init');
  1190. me.trigger('ready');
  1191. });
  1192. },
  1193. destroy: function() {
  1194. this.exec('destroy');
  1195. this.disconnectRuntime();
  1196. this.off();
  1197. }
  1198. });
  1199. Mediator.installTo( FilePaste.prototype );
  1200. return FilePaste;
  1201. });
  1202. /**
  1203. * @fileOverview 组件基类
  1204. */
  1205. define('widgets/filepaste',[
  1206. 'base',
  1207. 'uploader',
  1208. 'lib/filepaste',
  1209. 'widgets/widget'
  1210. ], function( Base, Uploader, FilePaste ) {
  1211. var $ = Base.$;
  1212. /**
  1213. * @property {Selector} [paste=undefined] 指定监听paste事件的容器如果不指定不启用此功能此功能为通过粘贴来添加截屏的图片建议设置为`document.body`.
  1214. * @namespace options
  1215. * @for Uploader
  1216. */
  1217. return Uploader.register({
  1218. init: function( opts ) {
  1219. if ( !opts.paste ||
  1220. this.request('predict-runtime-type') !== 'html5' ) {
  1221. return;
  1222. }
  1223. var me = this,
  1224. deferred = Base.Deferred(),
  1225. options = $.extend({}, {
  1226. container: opts.paste,
  1227. accept: opts.accept
  1228. }),
  1229. paste;
  1230. paste = new FilePaste( options );
  1231. paste.once( 'ready', deferred.resolve );
  1232. paste.on( 'paste', function( files ) {
  1233. me.owner.request( 'add-file', [ files ]);
  1234. });
  1235. paste.init();
  1236. return deferred.promise();
  1237. }
  1238. });
  1239. });
  1240. /**
  1241. * @fileOverview Blob
  1242. */
  1243. define('lib/blob',[
  1244. 'base',
  1245. 'runtime/client'
  1246. ], function( Base, RuntimeClient ) {
  1247. function Blob( ruid, source ) {
  1248. var me = this;
  1249. me.source = source;
  1250. me.ruid = ruid;
  1251. RuntimeClient.call( me, 'Blob' );
  1252. this.uid = source.uid || this.uid;
  1253. this.type = source.type || '';
  1254. this.size = source.size || 0;
  1255. if ( ruid ) {
  1256. me.connectRuntime( ruid );
  1257. }
  1258. }
  1259. Base.inherits( RuntimeClient, {
  1260. constructor: Blob,
  1261. slice: function( start, end ) {
  1262. return this.exec( 'slice', start, end );
  1263. },
  1264. getSource: function() {
  1265. return this.source;
  1266. }
  1267. });
  1268. return Blob;
  1269. });
  1270. /**
  1271. * 为了统一化Flash的File和HTML5的File而存在
  1272. * 以至于要调用Flash里面的File也可以像调用HTML5版本的File一下
  1273. * @fileOverview File
  1274. */
  1275. define('lib/file',[
  1276. 'base',
  1277. 'lib/blob'
  1278. ], function( Base, Blob ) {
  1279. var uid = 1,
  1280. rExt = /\.([^.]+)$/;
  1281. function File( ruid, file ) {
  1282. var ext;
  1283. Blob.apply( this, arguments );
  1284. this.name = file.name || ('untitled' + uid++);
  1285. ext = rExt.exec( file.name ) ? RegExp.$1.toLowerCase() : '';
  1286. // todo 支持其他类型文件的转换。
  1287. // 如果有mimetype, 但是文件名里面没有找出后缀规律
  1288. if ( !ext && this.type ) {
  1289. ext = /\/(jpg|jpeg|png|gif|bmp)$/i.exec( this.type ) ?
  1290. RegExp.$1.toLowerCase() : '';
  1291. this.name += '.' + ext;
  1292. }
  1293. // 如果没有指定mimetype, 但是知道文件后缀。
  1294. if ( !this.type && ~'jpg,jpeg,png,gif,bmp'.indexOf( ext ) ) {
  1295. this.type = 'image/' + (ext === 'jpg' ? 'jpeg' : ext);
  1296. }
  1297. this.ext = ext;
  1298. this.lastModifiedDate = file.lastModifiedDate ||
  1299. (new Date()).toLocaleString();
  1300. }
  1301. return Base.inherits( Blob, File );
  1302. });
  1303. /**
  1304. * @fileOverview 错误信息
  1305. */
  1306. define('lib/filepicker',[
  1307. 'base',
  1308. 'runtime/client',
  1309. 'lib/file'
  1310. ], function( Base, RuntimeClent, File ) {
  1311. var $ = Base.$;
  1312. function FilePicker( opts ) {
  1313. opts = this.options = $.extend({}, FilePicker.options, opts );
  1314. opts.container = $( opts.id );
  1315. if ( !opts.container.length ) {
  1316. throw new Error('按钮指定错误');
  1317. }
  1318. opts.innerHTML = opts.innerHTML || opts.label ||
  1319. opts.container.html() || '';
  1320. opts.button = $( opts.button || document.createElement('div') );
  1321. opts.button.html( opts.innerHTML );
  1322. opts.container.html( opts.button );
  1323. RuntimeClent.call( this, 'FilePicker', true );
  1324. }
  1325. FilePicker.options = {
  1326. button: null,
  1327. container: null,
  1328. label: null,
  1329. innerHTML: null,
  1330. multiple: true,
  1331. accept: null,
  1332. name: 'file'
  1333. };
  1334. Base.inherits( RuntimeClent, {
  1335. constructor: FilePicker,
  1336. init: function() {
  1337. var me = this,
  1338. opts = me.options,
  1339. button = opts.button;
  1340. button.addClass('webuploader-pick');
  1341. me.on( 'all', function( type ) {
  1342. var files;
  1343. switch ( type ) {
  1344. case 'mouseenter':
  1345. button.addClass('webuploader-pick-hover');
  1346. break;
  1347. case 'mouseleave':
  1348. button.removeClass('webuploader-pick-hover');
  1349. break;
  1350. case 'change':
  1351. files = me.exec('getFiles');
  1352. me.trigger( 'select', $.map( files, function( file ) {
  1353. file = new File( me.getRuid(), file );
  1354. // 记录来源。
  1355. file._refer = opts.container;
  1356. return file;
  1357. }), opts.container );
  1358. break;
  1359. }
  1360. });
  1361. me.connectRuntime( opts, function() {
  1362. me.refresh();
  1363. me.exec( 'init', opts );
  1364. me.trigger('ready');
  1365. });
  1366. $( window ).on( 'resize', function() {
  1367. me.refresh();
  1368. });
  1369. },
  1370. refresh: function() {
  1371. var shimContainer = this.getRuntime().getContainer(),
  1372. button = this.options.button,
  1373. width = button.outerWidth ?
  1374. button.outerWidth() : button.width(),
  1375. height = button.outerHeight ?
  1376. button.outerHeight() : button.height(),
  1377. pos = button.offset();
  1378. width && height && shimContainer.css({
  1379. bottom: 'auto',
  1380. right: 'auto',
  1381. width: width + 'px',
  1382. height: height + 'px'
  1383. }).offset( pos );
  1384. },
  1385. enable: function() {
  1386. var btn = this.options.button;
  1387. btn.removeClass('webuploader-pick-disable');
  1388. this.refresh();
  1389. },
  1390. disable: function() {
  1391. var btn = this.options.button;
  1392. this.getRuntime().getContainer().css({
  1393. top: '-99999px'
  1394. });
  1395. btn.addClass('webuploader-pick-disable');
  1396. },
  1397. destroy: function() {
  1398. if ( this.runtime ) {
  1399. this.exec('destroy');
  1400. this.disconnectRuntime();
  1401. }
  1402. }
  1403. });
  1404. return FilePicker;
  1405. });
  1406. /**
  1407. * @fileOverview 文件选择相关
  1408. */
  1409. define('widgets/filepicker',[
  1410. 'base',
  1411. 'uploader',
  1412. 'lib/filepicker',
  1413. 'widgets/widget'
  1414. ], function( Base, Uploader, FilePicker ) {
  1415. var $ = Base.$;
  1416. $.extend( Uploader.options, {
  1417. /**
  1418. * @property {Selector | Object} [pick=undefined]
  1419. * @namespace options
  1420. * @for Uploader
  1421. * @description 指定选择文件的按钮容器不指定则不创建按钮
  1422. *
  1423. * * `id` {Seletor} 指定选择文件的按钮容器不指定则不创建按钮
  1424. * * `label` {String} 请采用 `innerHTML` 代替
  1425. * * `innerHTML` {String} 指定按钮文字不指定时优先从指定的容器中看是否自带文字
  1426. * * `multiple` {Boolean} 是否开起同时选择多个文件能力
  1427. */
  1428. pick: null,
  1429. /**
  1430. * @property {Arroy} [accept=null]
  1431. * @namespace options
  1432. * @for Uploader
  1433. * @description 指定接受哪些类型的文件 由于目前还有ext转mimeType表所以这里需要分开指定
  1434. *
  1435. * * `title` {String} 文字描述
  1436. * * `extensions` {String} 允许的文件后缀不带点多个用逗号分割
  1437. * * `mimeTypes` {String} 多个用逗号分割
  1438. *
  1439. *
  1440. *
  1441. * ```
  1442. * {
  1443. * title: 'Images',
  1444. * extensions: 'gif,jpg,jpeg,bmp,png',
  1445. * mimeTypes: 'image/*'
  1446. * }
  1447. * ```
  1448. */
  1449. accept: null/*{
  1450. title: 'Images',
  1451. extensions: 'gif,jpg,jpeg,bmp,png',
  1452. mimeTypes: 'image/*'
  1453. }*/
  1454. });
  1455. return Uploader.register({
  1456. 'add-btn': 'addButton',
  1457. refresh: 'refresh',
  1458. disable: 'disable',
  1459. enable: 'enable'
  1460. }, {
  1461. init: function( opts ) {
  1462. this.pickers = [];
  1463. return opts.pick && this.addButton( opts.pick );
  1464. },
  1465. refresh: function() {
  1466. $.each( this.pickers, function() {
  1467. this.refresh();
  1468. });
  1469. },
  1470. /**
  1471. * @method addButton
  1472. * @for Uploader
  1473. * @grammar addButton( pick ) => Promise
  1474. * @description
  1475. * 添加文件选择按钮如果一个按钮不够需要调用此方法来添加参数跟[options.pick](#WebUploader:Uploader:options)一致
  1476. * @example
  1477. * uploader.addButton({
  1478. * id: '#btnContainer',
  1479. * innerHTML: '选择文件'
  1480. * });
  1481. */
  1482. addButton: function( pick ) {
  1483. var me = this,
  1484. opts = me.options,
  1485. accept = opts.accept,
  1486. options, picker, deferred;
  1487. if ( !pick ) {
  1488. return;
  1489. }
  1490. deferred = Base.Deferred();
  1491. $.isPlainObject( pick ) || (pick = {
  1492. id: pick
  1493. });
  1494. options = $.extend({}, pick, {
  1495. accept: $.isPlainObject( accept ) ? [ accept ] : accept,
  1496. swf: opts.swf,
  1497. runtimeOrder: opts.runtimeOrder
  1498. });
  1499. picker = new FilePicker( options );
  1500. picker.once( 'ready', deferred.resolve );
  1501. picker.on( 'select', function( files ) {
  1502. me.owner.request( 'add-file', [ files ]);
  1503. });
  1504. picker.init();
  1505. this.pickers.push( picker );
  1506. return deferred.promise();
  1507. },
  1508. disable: function() {
  1509. $.each( this.pickers, function() {
  1510. this.disable();
  1511. });
  1512. },
  1513. enable: function() {
  1514. $.each( this.pickers, function() {
  1515. this.enable();
  1516. });
  1517. }
  1518. });
  1519. });
  1520. /**
  1521. * @fileOverview Image
  1522. */
  1523. define('lib/image',[
  1524. 'base',
  1525. 'runtime/client',
  1526. 'lib/blob'
  1527. ], function( Base, RuntimeClient, Blob ) {
  1528. var $ = Base.$;
  1529. // 构造器。
  1530. function Image( opts ) {
  1531. this.options = $.extend({}, Image.options, opts );
  1532. RuntimeClient.call( this, 'Image' );
  1533. this.on( 'load', function() {
  1534. this._info = this.exec('info');
  1535. this._meta = this.exec('meta');
  1536. });
  1537. }
  1538. // 默认选项。
  1539. Image.options = {
  1540. // 默认的图片处理质量
  1541. quality: 90,
  1542. // 是否裁剪
  1543. crop: false,
  1544. // 是否保留头部信息
  1545. preserveHeaders: true,
  1546. // 是否允许放大。
  1547. allowMagnify: true
  1548. };
  1549. // 继承RuntimeClient.
  1550. Base.inherits( RuntimeClient, {
  1551. constructor: Image,
  1552. info: function( val ) {
  1553. // setter
  1554. if ( val ) {
  1555. this._info = val;
  1556. return this;
  1557. }
  1558. // getter
  1559. return this._info;
  1560. },
  1561. meta: function( val ) {
  1562. // setter
  1563. if ( val ) {
  1564. this._meta = val;
  1565. return this;
  1566. }
  1567. // getter
  1568. return this._meta;
  1569. },
  1570. loadFromBlob: function( blob ) {
  1571. var me = this,
  1572. ruid = blob.getRuid();
  1573. this.connectRuntime( ruid, function() {
  1574. me.exec( 'init', me.options );
  1575. me.exec( 'loadFromBlob', blob );
  1576. });
  1577. },
  1578. resize: function() {
  1579. var args = Base.slice( arguments );
  1580. return this.exec.apply( this, [ 'resize' ].concat( args ) );
  1581. },
  1582. getAsDataUrl: function( type ) {
  1583. return this.exec( 'getAsDataUrl', type );
  1584. },
  1585. getAsBlob: function( type ) {
  1586. var blob = this.exec( 'getAsBlob', type );
  1587. return new Blob( this.getRuid(), blob );
  1588. }
  1589. });
  1590. return Image;
  1591. });
  1592. /**
  1593. * @fileOverview 图片操作, 负责预览图片和上传前压缩图片
  1594. */
  1595. define('widgets/image',[
  1596. 'base',
  1597. 'uploader',
  1598. 'lib/image',
  1599. 'widgets/widget'
  1600. ], function( Base, Uploader, Image ) {
  1601. var $ = Base.$,
  1602. throttle;
  1603. // 根据要处理的文件大小来节流,一次不能处理太多,会卡。
  1604. throttle = (function( max ) {
  1605. var occupied = 0,
  1606. waiting = [],
  1607. tick = function() {
  1608. var item;
  1609. while ( waiting.length && occupied < max ) {
  1610. item = waiting.shift();
  1611. occupied += item[ 0 ];
  1612. item[ 1 ]();
  1613. }
  1614. };
  1615. return function( emiter, size, cb ) {
  1616. waiting.push([ size, cb ]);
  1617. emiter.once( 'destroy', function() {
  1618. occupied -= size;
  1619. setTimeout( tick, 1 );
  1620. });
  1621. setTimeout( tick, 1 );
  1622. };
  1623. })( 5 * 1024 * 1024 );
  1624. $.extend( Uploader.options, {
  1625. /**
  1626. * @property {Object} [thumb]
  1627. * @namespace options
  1628. * @for Uploader
  1629. * @description 配置生成缩略图的选项
  1630. *
  1631. * 默认为
  1632. *
  1633. * ```javascript
  1634. * {
  1635. * width: 110,
  1636. * height: 110,
  1637. *
  1638. * // 图片质量,只有type为`image/jpeg`的时候才有效。
  1639. * quality: 70,
  1640. *
  1641. * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
  1642. * allowMagnify: true,
  1643. *
  1644. * // 是否允许裁剪。
  1645. * crop: true,
  1646. *
  1647. * // 是否保留头部meta信息。
  1648. * preserveHeaders: false,
  1649. *
  1650. * // 为空的话则保留原有图片格式。
  1651. * // 否则强制转换成指定的类型。
  1652. * type: 'image/jpeg'
  1653. * }
  1654. * ```
  1655. */
  1656. thumb: {
  1657. width: 110,
  1658. height: 110,
  1659. quality: 70,
  1660. allowMagnify: true,
  1661. crop: true,
  1662. preserveHeaders: false,
  1663. // 为空的话则保留原有图片格式。
  1664. // 否则强制转换成指定的类型。
  1665. // IE 8下面 base64 大小不能超过 32K 否则预览失败,而非 jpeg 编码的图片很可
  1666. // 能会超过 32k, 所以这里设置成预览的时候都是 image/jpeg
  1667. type: 'image/jpeg'
  1668. },
  1669. /**
  1670. * @property {Object} [compress]
  1671. * @namespace options
  1672. * @for Uploader
  1673. * @description 配置压缩的图片的选项如果此选项为`false`, 则图片在上传前不进行压缩
  1674. *
  1675. * 默认为
  1676. *
  1677. * ```javascript
  1678. * {
  1679. * width: 1600,
  1680. * height: 1600,
  1681. *
  1682. * // 图片质量,只有type为`image/jpeg`的时候才有效。
  1683. * quality: 90,
  1684. *
  1685. * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
  1686. * allowMagnify: false,
  1687. *
  1688. * // 是否允许裁剪。
  1689. * crop: false,
  1690. *
  1691. * // 是否保留头部meta信息。
  1692. * preserveHeaders: true
  1693. * }
  1694. * ```
  1695. */
  1696. compress: {
  1697. width: 1600,
  1698. height: 1600,
  1699. quality: 90,
  1700. allowMagnify: false,
  1701. crop: false,
  1702. preserveHeaders: true
  1703. }
  1704. });
  1705. return Uploader.register({
  1706. 'make-thumb': 'makeThumb',
  1707. 'before-send-file': 'compressImage'
  1708. }, {
  1709. /**
  1710. * 生成缩略图此过程为异步所以需要传入`callback`
  1711. * 通常情况在图片加入队里后调用此方法来生成预览图以增强交互效果
  1712. *
  1713. * `callback`中可以接收到两个参数
  1714. * * 第一个为error如果生成缩略图有错误此error将为真
  1715. * * 第二个为ret, 缩略图的Data URL值
  1716. *
  1717. * **注意**
  1718. * Date URL在IE6/7中不支持所以不用调用此方法了直接显示一张暂不支持预览图片好了
  1719. *
  1720. *
  1721. * @method makeThumb
  1722. * @grammar makeThumb( file, callback ) => undefined
  1723. * @grammar makeThumb( file, callback, width, height ) => undefined
  1724. * @for Uploader
  1725. * @example
  1726. *
  1727. * uploader.on( 'fileQueued', function( file ) {
  1728. * var $li = ...;
  1729. *
  1730. * uploader.makeThumb( file, function( error, ret ) {
  1731. * if ( error ) {
  1732. * $li.text('预览错误');
  1733. * } else {
  1734. * $li.append('<img alt="" src="' + ret + '" />');
  1735. * }
  1736. * });
  1737. *
  1738. * });
  1739. */
  1740. makeThumb: function( file, cb, width, height ) {
  1741. var opts, image;
  1742. file = this.request( 'get-file', file );
  1743. // 只预览图片格式。
  1744. if ( !file.type.match( /^image/ ) ) {
  1745. cb( true );
  1746. return;
  1747. }
  1748. opts = $.extend({}, this.options.thumb );
  1749. // 如果传入的是object.
  1750. if ( $.isPlainObject( width ) ) {
  1751. opts = $.extend( opts, width );
  1752. width = null;
  1753. }
  1754. width = width || opts.width;
  1755. height = height || opts.height;
  1756. image = new Image( opts );
  1757. image.once( 'load', function() {
  1758. file._info = file._info || image.info();
  1759. file._meta = file._meta || image.meta();
  1760. image.resize( width, height );
  1761. });
  1762. image.once( 'complete', function() {
  1763. cb( false, image.getAsDataUrl( opts.type ) );
  1764. image.destroy();
  1765. });
  1766. image.once( 'error', function() {
  1767. cb( true );
  1768. image.destroy();
  1769. });
  1770. throttle( image, file.source.size, function() {
  1771. file._info && image.info( file._info );
  1772. file._meta && image.meta( file._meta );
  1773. image.loadFromBlob( file.source );
  1774. });
  1775. },
  1776. compressImage: function( file ) {
  1777. var opts = this.options.compress || this.options.resize,
  1778. compressSize = opts && opts.compressSize || 300 * 1024,
  1779. image, deferred;
  1780. file = this.request( 'get-file', file );
  1781. // 只预览图片格式。
  1782. if ( !opts || !~'image/jpeg,image/jpg'.indexOf( file.type ) ||
  1783. file.size < compressSize ||
  1784. file._compressed ) {
  1785. return;
  1786. }
  1787. opts = $.extend({}, opts );
  1788. deferred = Base.Deferred();
  1789. image = new Image( opts );
  1790. deferred.always(function() {
  1791. image.destroy();
  1792. image = null;
  1793. });
  1794. image.once( 'error', deferred.reject );
  1795. image.once( 'load', function() {
  1796. file._info = file._info || image.info();
  1797. file._meta = file._meta || image.meta();
  1798. image.resize( opts.width, opts.height );
  1799. });
  1800. image.once( 'complete', function() {
  1801. var blob, size;
  1802. // 移动端 UC / qq 浏览器的无图模式下
  1803. // ctx.getImageData 处理大图的时候会报 Exception
  1804. // INDEX_SIZE_ERR: DOM Exception 1
  1805. try {
  1806. blob = image.getAsBlob( opts.type );
  1807. size = file.size;
  1808. // 如果压缩后,比原来还大则不用压缩后的。
  1809. if ( blob.size < size ) {
  1810. // file.source.destroy && file.source.destroy();
  1811. file.source = blob;
  1812. file.size = blob.size;
  1813. file.trigger( 'resize', blob.size, size );
  1814. }
  1815. // 标记,避免重复压缩。
  1816. file._compressed = true;
  1817. deferred.resolve();
  1818. } catch ( e ) {
  1819. // 出错了直接继续,让其上传原始图片
  1820. deferred.resolve();
  1821. }
  1822. });
  1823. file._info && image.info( file._info );
  1824. file._meta && image.meta( file._meta );
  1825. image.loadFromBlob( file.source );
  1826. return deferred.promise();
  1827. }
  1828. });
  1829. });
  1830. /**
  1831. * @fileOverview 文件属性封装
  1832. */
  1833. define('file',[
  1834. 'base',
  1835. 'mediator'
  1836. ], function( Base, Mediator ) {
  1837. var $ = Base.$,
  1838. idPrefix = 'WU_FILE_',
  1839. idSuffix = 0,
  1840. rExt = /\.([^.]+)$/,
  1841. statusMap = {};
  1842. function gid() {
  1843. return idPrefix + idSuffix++;
  1844. }
  1845. /**
  1846. * 文件类
  1847. * @class File
  1848. * @constructor 构造函数
  1849. * @grammar new File( source ) => File
  1850. * @param {Lib.File} source [lib.File](#Lib.File)实例, 此source对象是带有Runtime信息的
  1851. */
  1852. function WUFile( source ) {
  1853. /**
  1854. * 文件名包括扩展名后缀
  1855. * @property name
  1856. * @type {string}
  1857. */
  1858. this.name = source.name || 'Untitled';
  1859. /**
  1860. * 文件体积字节
  1861. * @property size
  1862. * @type {uint}
  1863. * @default 0
  1864. */
  1865. this.size = source.size || 0;
  1866. /**
  1867. * 文件MIMETYPE类型与文件类型的对应关系请参考[http://t.cn/z8ZnFny](http://t.cn/z8ZnFny)
  1868. * @property type
  1869. * @type {string}
  1870. * @default 'application'
  1871. */
  1872. this.type = source.type || 'application';
  1873. /**
  1874. * 文件最后修改日期
  1875. * @property lastModifiedDate
  1876. * @type {int}
  1877. * @default 当前时间戳
  1878. */
  1879. this.lastModifiedDate = source.lastModifiedDate || (new Date() * 1);
  1880. /**
  1881. * 文件ID每个对象具有唯一ID与文件名无关
  1882. * @property id
  1883. * @type {string}
  1884. */
  1885. this.id = gid();
  1886. /**
  1887. * 文件扩展名通过文件名获取例如test.png的扩展名为png
  1888. * @property ext
  1889. * @type {string}
  1890. */
  1891. this.ext = rExt.exec( this.name ) ? RegExp.$1 : '';
  1892. /**
  1893. * 状态文字说明在不同的status语境下有不同的用途
  1894. * @property statusText
  1895. * @type {string}
  1896. */
  1897. this.statusText = '';
  1898. // 存储文件状态,防止通过属性直接修改
  1899. statusMap[ this.id ] = WUFile.Status.INITED;
  1900. this.source = source;
  1901. this.loaded = 0;
  1902. this.on( 'error', function( msg ) {
  1903. this.setStatus( WUFile.Status.ERROR, msg );
  1904. });
  1905. }
  1906. $.extend( WUFile.prototype, {
  1907. /**
  1908. * 设置状态状态变化时会触发`change`事件
  1909. * @method setStatus
  1910. * @grammar setStatus( status[, statusText] );
  1911. * @param {File.Status|String} status [文件状态值](#WebUploader:File:File.Status)
  1912. * @param {String} [statusText=''] 状态说明常在error时使用用http, abort,server等来标记是由于什么原因导致文件错误
  1913. */
  1914. setStatus: function( status, text ) {
  1915. var prevStatus = statusMap[ this.id ];
  1916. typeof text !== 'undefined' && (this.statusText = text);
  1917. if ( status !== prevStatus ) {
  1918. statusMap[ this.id ] = status;
  1919. /**
  1920. * 文件状态变化
  1921. * @event statuschange
  1922. */
  1923. this.trigger( 'statuschange', status, prevStatus );
  1924. }
  1925. },
  1926. /**
  1927. * 获取文件状态
  1928. * @return {File.Status}
  1929. * @example
  1930. 文件状态具体包括以下几种类型
  1931. {
  1932. // 初始化
  1933. INITED: 0,
  1934. // 已入队列
  1935. QUEUED: 1,
  1936. // 正在上传
  1937. PROGRESS: 2,
  1938. // 上传出错
  1939. ERROR: 3,
  1940. // 上传成功
  1941. COMPLETE: 4,
  1942. // 上传取消
  1943. CANCELLED: 5
  1944. }
  1945. */
  1946. getStatus: function() {
  1947. return statusMap[ this.id ];
  1948. },
  1949. /**
  1950. * 获取文件原始信息
  1951. * @return {*}
  1952. */
  1953. getSource: function() {
  1954. return this.source;
  1955. },
  1956. destory: function() {
  1957. delete statusMap[ this.id ];
  1958. }
  1959. });
  1960. Mediator.installTo( WUFile.prototype );
  1961. /**
  1962. * 文件状态值具体包括以下几种类型
  1963. * * `inited` 初始状态
  1964. * * `queued` 已经进入队列, 等待上传
  1965. * * `progress` 上传中
  1966. * * `complete` 上传完成
  1967. * * `error` 上传出错可重试
  1968. * * `interrupt` 上传中断可续传
  1969. * * `invalid` 文件不合格不能重试上传会自动从队列中移除
  1970. * * `cancelled` 文件被移除
  1971. * @property {Object} Status
  1972. * @namespace File
  1973. * @class File
  1974. * @static
  1975. */
  1976. WUFile.Status = {
  1977. INITED: 'inited', // 初始状态
  1978. QUEUED: 'queued', // 已经进入队列, 等待上传
  1979. PROGRESS: 'progress', // 上传中
  1980. ERROR: 'error', // 上传出错,可重试
  1981. COMPLETE: 'complete', // 上传完成。
  1982. CANCELLED: 'cancelled', // 上传取消。
  1983. INTERRUPT: 'interrupt', // 上传中断,可续传。
  1984. INVALID: 'invalid' // 文件不合格,不能重试上传。
  1985. };
  1986. return WUFile;
  1987. });
  1988. /**
  1989. * @fileOverview 文件队列
  1990. */
  1991. define('queue',[
  1992. 'base',
  1993. 'mediator',
  1994. 'file'
  1995. ], function( Base, Mediator, WUFile ) {
  1996. var $ = Base.$,
  1997. STATUS = WUFile.Status;
  1998. /**
  1999. * 文件队列, 用来存储各个状态中的文件
  2000. * @class Queue
  2001. * @extends Mediator
  2002. */
  2003. function Queue() {
  2004. /**
  2005. * 统计文件数
  2006. * * `numOfQueue` 队列中的文件数
  2007. * * `numOfSuccess` 上传成功的文件数
  2008. * * `numOfCancel` 被移除的文件数
  2009. * * `numOfProgress` 正在上传中的文件数
  2010. * * `numOfUploadFailed` 上传错误的文件数
  2011. * * `numOfInvalid` 无效的文件数
  2012. * @property {Object} stats
  2013. */
  2014. this.stats = {
  2015. numOfQueue: 0,
  2016. numOfSuccess: 0,
  2017. numOfCancel: 0,
  2018. numOfProgress: 0,
  2019. numOfUploadFailed: 0,
  2020. numOfInvalid: 0
  2021. };
  2022. // 上传队列,仅包括等待上传的文件
  2023. this._queue = [];
  2024. // 存储所有文件
  2025. this._map = {};
  2026. }
  2027. $.extend( Queue.prototype, {
  2028. /**
  2029. * 将新文件加入对队列尾部
  2030. *
  2031. * @method append
  2032. * @param {File} file 文件对象
  2033. */
  2034. append: function( file ) {
  2035. this._queue.push( file );
  2036. this._fileAdded( file );
  2037. return this;
  2038. },
  2039. /**
  2040. * 将新文件加入对队列头部
  2041. *
  2042. * @method prepend
  2043. * @param {File} file 文件对象
  2044. */
  2045. prepend: function( file ) {
  2046. this._queue.unshift( file );
  2047. this._fileAdded( file );
  2048. return this;
  2049. },
  2050. /**
  2051. * 获取文件对象
  2052. *
  2053. * @method getFile
  2054. * @param {String} fileId 文件ID
  2055. * @return {File}
  2056. */
  2057. getFile: function( fileId ) {
  2058. if ( typeof fileId !== 'string' ) {
  2059. return fileId;
  2060. }
  2061. return this._map[ fileId ];
  2062. },
  2063. /**
  2064. * 从队列中取出一个指定状态的文件
  2065. * @grammar fetch( status ) => File
  2066. * @method fetch
  2067. * @param {String} status [文件状态值](#WebUploader:File:File.Status)
  2068. * @return {File} [File](#WebUploader:File)
  2069. */
  2070. fetch: function( status ) {
  2071. var len = this._queue.length,
  2072. i, file;
  2073. status = status || STATUS.QUEUED;
  2074. for ( i = 0; i < len; i++ ) {
  2075. file = this._queue[ i ];
  2076. if ( status === file.getStatus() ) {
  2077. return file;
  2078. }
  2079. }
  2080. return null;
  2081. },
  2082. /**
  2083. * 对队列进行排序能够控制文件上传顺序
  2084. * @grammar sort( fn ) => undefined
  2085. * @method sort
  2086. * @param {Function} fn 排序方法
  2087. */
  2088. sort: function( fn ) {
  2089. if ( typeof fn === 'function' ) {
  2090. this._queue.sort( fn );
  2091. }
  2092. },
  2093. /**
  2094. * 获取指定类型的文件列表, 列表中每一个成员为[File](#WebUploader:File)对象
  2095. * @grammar getFiles( [status1[, status2 ...]] ) => Array
  2096. * @method getFiles
  2097. * @param {String} [status] [文件状态值](#WebUploader:File:File.Status)
  2098. */
  2099. getFiles: function() {
  2100. var sts = [].slice.call( arguments, 0 ),
  2101. ret = [],
  2102. i = 0,
  2103. len = this._queue.length,
  2104. file;
  2105. for ( ; i < len; i++ ) {
  2106. file = this._queue[ i ];
  2107. if ( sts.length && !~$.inArray( file.getStatus(), sts ) ) {
  2108. continue;
  2109. }
  2110. ret.push( file );
  2111. }
  2112. return ret;
  2113. },
  2114. _fileAdded: function( file ) {
  2115. var me = this,
  2116. existing = this._map[ file.id ];
  2117. if ( !existing ) {
  2118. this._map[ file.id ] = file;
  2119. file.on( 'statuschange', function( cur, pre ) {
  2120. me._onFileStatusChange( cur, pre );
  2121. });
  2122. }
  2123. file.setStatus( STATUS.QUEUED );
  2124. },
  2125. _onFileStatusChange: function( curStatus, preStatus ) {
  2126. var stats = this.stats;
  2127. switch ( preStatus ) {
  2128. case STATUS.PROGRESS:
  2129. stats.numOfProgress--;
  2130. break;
  2131. case STATUS.QUEUED:
  2132. stats.numOfQueue --;
  2133. break;
  2134. case STATUS.ERROR:
  2135. stats.numOfUploadFailed--;
  2136. break;
  2137. case STATUS.INVALID:
  2138. stats.numOfInvalid--;
  2139. break;
  2140. }
  2141. switch ( curStatus ) {
  2142. case STATUS.QUEUED:
  2143. stats.numOfQueue++;
  2144. break;
  2145. case STATUS.PROGRESS:
  2146. stats.numOfProgress++;
  2147. break;
  2148. case STATUS.ERROR:
  2149. stats.numOfUploadFailed++;
  2150. break;
  2151. case STATUS.COMPLETE:
  2152. stats.numOfSuccess++;
  2153. break;
  2154. case STATUS.CANCELLED:
  2155. stats.numOfCancel++;
  2156. break;
  2157. case STATUS.INVALID:
  2158. stats.numOfInvalid++;
  2159. break;
  2160. }
  2161. }
  2162. });
  2163. Mediator.installTo( Queue.prototype );
  2164. return Queue;
  2165. });
  2166. /**
  2167. * @fileOverview 队列
  2168. */
  2169. define('widgets/queue',[
  2170. 'base',
  2171. 'uploader',
  2172. 'queue',
  2173. 'file',
  2174. 'lib/file',
  2175. 'runtime/client',
  2176. 'widgets/widget'
  2177. ], function( Base, Uploader, Queue, WUFile, File, RuntimeClient ) {
  2178. var $ = Base.$,
  2179. rExt = /\.\w+$/,
  2180. Status = WUFile.Status;
  2181. return Uploader.register({
  2182. 'sort-files': 'sortFiles',
  2183. 'add-file': 'addFiles',
  2184. 'get-file': 'getFile',
  2185. 'fetch-file': 'fetchFile',
  2186. 'get-stats': 'getStats',
  2187. 'get-files': 'getFiles',
  2188. 'remove-file': 'removeFile',
  2189. 'retry': 'retry',
  2190. 'reset': 'reset',
  2191. 'accept-file': 'acceptFile'
  2192. }, {
  2193. init: function( opts ) {
  2194. var me = this,
  2195. deferred, len, i, item, arr, accept, runtime;
  2196. if ( $.isPlainObject( opts.accept ) ) {
  2197. opts.accept = [ opts.accept ];
  2198. }
  2199. // accept中的中生成匹配正则。
  2200. if ( opts.accept ) {
  2201. arr = [];
  2202. for ( i = 0, len = opts.accept.length; i < len; i++ ) {
  2203. item = opts.accept[ i ].extensions;
  2204. item && arr.push( item );
  2205. }
  2206. if ( arr.length ) {
  2207. accept = '\\.' + arr.join(',')
  2208. .replace( /,/g, '$|\\.' )
  2209. .replace( /\*/g, '.*' ) + '$';
  2210. }
  2211. me.accept = new RegExp( accept, 'i' );
  2212. }
  2213. me.queue = new Queue();
  2214. me.stats = me.queue.stats;
  2215. // 如果当前不是html5运行时,那就算了。
  2216. // 不执行后续操作
  2217. if ( this.request('predict-runtime-type') !== 'html5' ) {
  2218. return;
  2219. }
  2220. // 创建一个 html5 运行时的 placeholder
  2221. // 以至于外部添加原生 File 对象的时候能正确包裹一下供 webuploader 使用。
  2222. deferred = Base.Deferred();
  2223. runtime = new RuntimeClient('Placeholder');
  2224. runtime.connectRuntime({
  2225. runtimeOrder: 'html5'
  2226. }, function() {
  2227. me._ruid = runtime.getRuid();
  2228. deferred.resolve();
  2229. });
  2230. return deferred.promise();
  2231. },
  2232. // 为了支持外部直接添加一个原生File对象。
  2233. _wrapFile: function( file ) {
  2234. if ( !(file instanceof WUFile) ) {
  2235. if ( !(file instanceof File) ) {
  2236. if ( !this._ruid ) {
  2237. throw new Error('Can\'t add external files.');
  2238. }
  2239. file = new File( this._ruid, file );
  2240. }
  2241. file = new WUFile( file );
  2242. }
  2243. return file;
  2244. },
  2245. // 判断文件是否可以被加入队列
  2246. acceptFile: function( file ) {
  2247. var invalid = !file || file.size < 6 || this.accept &&
  2248. // 如果名字中有后缀,才做后缀白名单处理。
  2249. rExt.exec( file.name ) && !this.accept.test( file.name );
  2250. return !invalid;
  2251. },
  2252. /**
  2253. * @event beforeFileQueued
  2254. * @param {File} file File对象
  2255. * @description 当文件被加入队列之前触发此事件的handler返回值为`false`则此文件不会被添加进入队列
  2256. * @for Uploader
  2257. */
  2258. /**
  2259. * @event fileQueued
  2260. * @param {File} file File对象
  2261. * @description 当文件被加入队列以后触发
  2262. * @for Uploader
  2263. */
  2264. _addFile: function( file ) {
  2265. var me = this;
  2266. file = me._wrapFile( file );
  2267. // 不过类型判断允许不允许,先派送 `beforeFileQueued`
  2268. if ( !me.owner.trigger( 'beforeFileQueued', file ) ) {
  2269. return;
  2270. }
  2271. // 类型不匹配,则派送错误事件,并返回。
  2272. if ( !me.acceptFile( file ) ) {
  2273. me.owner.trigger( 'error', 'Q_TYPE_DENIED', file );
  2274. return;
  2275. }
  2276. me.queue.append( file );
  2277. me.owner.trigger( 'fileQueued', file );
  2278. return file;
  2279. },
  2280. getFile: function( fileId ) {
  2281. return this.queue.getFile( fileId );
  2282. },
  2283. /**
  2284. * @event filesQueued
  2285. * @param {File} files 数组内容为原始File(lib/File对象
  2286. * @description 当一批文件添加进队列以后触发
  2287. * @for Uploader
  2288. */
  2289. /**
  2290. * @method addFiles
  2291. * @grammar addFiles( file ) => undefined
  2292. * @grammar addFiles( [file1, file2 ...] ) => undefined
  2293. * @param {Array of File or File} [files] Files 对象 数组
  2294. * @description 添加文件到队列
  2295. * @for Uploader
  2296. */
  2297. addFiles: function( files ) {
  2298. var me = this;
  2299. if ( !files.length ) {
  2300. files = [ files ];
  2301. }
  2302. files = $.map( files, function( file ) {
  2303. return me._addFile( file );
  2304. });
  2305. me.owner.trigger( 'filesQueued', files );
  2306. if ( me.options.auto ) {
  2307. me.request('start-upload');
  2308. }
  2309. },
  2310. getStats: function() {
  2311. return this.stats;
  2312. },
  2313. /**
  2314. * @event fileDequeued
  2315. * @param {File} file File对象
  2316. * @description 当文件被移除队列后触发
  2317. * @for Uploader
  2318. */
  2319. /**
  2320. * @method removeFile
  2321. * @grammar removeFile( file ) => undefined
  2322. * @grammar removeFile( id ) => undefined
  2323. * @param {File|id} file File对象或这File对象的id
  2324. * @description 移除某一文件
  2325. * @for Uploader
  2326. * @example
  2327. *
  2328. * $li.on('click', '.remove-this', function() {
  2329. * uploader.removeFile( file );
  2330. * })
  2331. */
  2332. removeFile: function( file ) {
  2333. var me = this;
  2334. file = file.id ? file : me.queue.getFile( file );
  2335. file.setStatus( Status.CANCELLED );
  2336. me.owner.trigger( 'fileDequeued', file );
  2337. },
  2338. /**
  2339. * @method getFiles
  2340. * @grammar getFiles() => Array
  2341. * @grammar getFiles( status1, status2, status... ) => Array
  2342. * @description 返回指定状态的文件集合不传参数将返回所有状态的文件
  2343. * @for Uploader
  2344. * @example
  2345. * console.log( uploader.getFiles() ); // => all files
  2346. * console.log( uploader.getFiles('error') ) // => all error files.
  2347. */
  2348. getFiles: function() {
  2349. return this.queue.getFiles.apply( this.queue, arguments );
  2350. },
  2351. fetchFile: function() {
  2352. return this.queue.fetch.apply( this.queue, arguments );
  2353. },
  2354. /**
  2355. * @method retry
  2356. * @grammar retry() => undefined
  2357. * @grammar retry( file ) => undefined
  2358. * @description 重试上传重试指定文件或者从出错的文件开始重新上传
  2359. * @for Uploader
  2360. * @example
  2361. * function retry() {
  2362. * uploader.retry();
  2363. * }
  2364. */
  2365. retry: function( file, noForceStart ) {
  2366. var me = this,
  2367. files, i, len;
  2368. if ( file ) {
  2369. file = file.id ? file : me.queue.getFile( file );
  2370. file.setStatus( Status.QUEUED );
  2371. noForceStart || me.request('start-upload');
  2372. return;
  2373. }
  2374. files = me.queue.getFiles( Status.ERROR );
  2375. i = 0;
  2376. len = files.length;
  2377. for ( ; i < len; i++ ) {
  2378. file = files[ i ];
  2379. file.setStatus( Status.QUEUED );
  2380. }
  2381. me.request('start-upload');
  2382. },
  2383. /**
  2384. * @method sort
  2385. * @grammar sort( fn ) => undefined
  2386. * @description 排序队列中的文件在上传之前调整可以控制上传顺序
  2387. * @for Uploader
  2388. */
  2389. sortFiles: function() {
  2390. return this.queue.sort.apply( this.queue, arguments );
  2391. },
  2392. /**
  2393. * @method reset
  2394. * @grammar reset() => undefined
  2395. * @description 重置uploader目前只重置了队列
  2396. * @for Uploader
  2397. * @example
  2398. * uploader.reset();
  2399. */
  2400. reset: function() {
  2401. this.queue = new Queue();
  2402. this.stats = this.queue.stats;
  2403. }
  2404. });
  2405. });
  2406. /**
  2407. * @fileOverview 添加获取Runtime相关信息的方法
  2408. */
  2409. define('widgets/runtime',[
  2410. 'uploader',
  2411. 'runtime/runtime',
  2412. 'widgets/widget'
  2413. ], function( Uploader, Runtime ) {
  2414. Uploader.support = function() {
  2415. return Runtime.hasRuntime.apply( Runtime, arguments );
  2416. };
  2417. return Uploader.register({
  2418. 'predict-runtime-type': 'predictRuntmeType'
  2419. }, {
  2420. init: function() {
  2421. if ( !this.predictRuntmeType() ) {
  2422. throw Error('Runtime Error');
  2423. }
  2424. },
  2425. /**
  2426. * 预测Uploader将采用哪个`Runtime`
  2427. * @grammar predictRuntmeType() => String
  2428. * @method predictRuntmeType
  2429. * @for Uploader
  2430. */
  2431. predictRuntmeType: function() {
  2432. var orders = this.options.runtimeOrder || Runtime.orders,
  2433. type = this.type,
  2434. i, len;
  2435. if ( !type ) {
  2436. orders = orders.split( /\s*,\s*/g );
  2437. for ( i = 0, len = orders.length; i < len; i++ ) {
  2438. if ( Runtime.hasRuntime( orders[ i ] ) ) {
  2439. this.type = type = orders[ i ];
  2440. break;
  2441. }
  2442. }
  2443. }
  2444. return type;
  2445. }
  2446. });
  2447. });
  2448. /**
  2449. * @fileOverview Transport
  2450. */
  2451. define('lib/transport',[
  2452. 'base',
  2453. 'runtime/client',
  2454. 'mediator'
  2455. ], function( Base, RuntimeClient, Mediator ) {
  2456. var $ = Base.$;
  2457. function Transport( opts ) {
  2458. var me = this;
  2459. opts = me.options = $.extend( true, {}, Transport.options, opts || {} );
  2460. RuntimeClient.call( this, 'Transport' );
  2461. this._blob = null;
  2462. this._formData = opts.formData || {};
  2463. this._headers = opts.headers || {};
  2464. this.on( 'progress', this._timeout );
  2465. this.on( 'load error', function() {
  2466. me.trigger( 'progress', 1 );
  2467. clearTimeout( me._timer );
  2468. });
  2469. }
  2470. Transport.options = {
  2471. server: '',
  2472. method: 'POST',
  2473. // 跨域时,是否允许携带cookie, 只有html5 runtime才有效
  2474. withCredentials: false,
  2475. fileVal: 'file',
  2476. timeout: 2 * 60 * 1000, // 2分钟
  2477. formData: {},
  2478. headers: {},
  2479. sendAsBinary: false
  2480. };
  2481. $.extend( Transport.prototype, {
  2482. // 添加Blob, 只能添加一次,最后一次有效。
  2483. appendBlob: function( key, blob, filename ) {
  2484. var me = this,
  2485. opts = me.options;
  2486. if ( me.getRuid() ) {
  2487. me.disconnectRuntime();
  2488. }
  2489. // 连接到blob归属的同一个runtime.
  2490. me.connectRuntime( blob.ruid, function() {
  2491. me.exec('init');
  2492. });
  2493. me._blob = blob;
  2494. opts.fileVal = key || opts.fileVal;
  2495. opts.filename = filename || opts.filename;
  2496. },
  2497. // 添加其他字段
  2498. append: function( key, value ) {
  2499. if ( typeof key === 'object' ) {
  2500. $.extend( this._formData, key );
  2501. } else {
  2502. this._formData[ key ] = value;
  2503. }
  2504. },
  2505. setRequestHeader: function( key, value ) {
  2506. if ( typeof key === 'object' ) {
  2507. $.extend( this._headers, key );
  2508. } else {
  2509. this._headers[ key ] = value;
  2510. }
  2511. },
  2512. send: function( method ) {
  2513. this.exec( 'send', method );
  2514. this._timeout();
  2515. },
  2516. abort: function() {
  2517. clearTimeout( this._timer );
  2518. return this.exec('abort');
  2519. },
  2520. destroy: function() {
  2521. this.trigger('destroy');
  2522. this.off();
  2523. this.exec('destroy');
  2524. this.disconnectRuntime();
  2525. },
  2526. getResponse: function() {
  2527. return this.exec('getResponse');
  2528. },
  2529. getResponseAsJson: function() {
  2530. return this.exec('getResponseAsJson');
  2531. },
  2532. getStatus: function() {
  2533. return this.exec('getStatus');
  2534. },
  2535. _timeout: function() {
  2536. var me = this,
  2537. duration = me.options.timeout;
  2538. if ( !duration ) {
  2539. return;
  2540. }
  2541. clearTimeout( me._timer );
  2542. me._timer = setTimeout(function() {
  2543. me.abort();
  2544. me.trigger( 'error', 'timeout' );
  2545. }, duration );
  2546. }
  2547. });
  2548. // 让Transport具备事件功能。
  2549. Mediator.installTo( Transport.prototype );
  2550. return Transport;
  2551. });
  2552. /**
  2553. * @fileOverview 负责文件上传相关
  2554. */
  2555. define('widgets/upload',[
  2556. 'base',
  2557. 'uploader',
  2558. 'file',
  2559. 'lib/transport',
  2560. 'widgets/widget'
  2561. ], function( Base, Uploader, WUFile, Transport ) {
  2562. var $ = Base.$,
  2563. isPromise = Base.isPromise,
  2564. Status = WUFile.Status;
  2565. // 添加默认配置项
  2566. $.extend( Uploader.options, {
  2567. /**
  2568. * @property {Boolean} [prepareNextFile=false]
  2569. * @namespace options
  2570. * @for Uploader
  2571. * @description 是否允许在文件传输时提前把下一个文件准备好
  2572. * 对于一个文件的准备工作比较耗时比如图片压缩md5序列化
  2573. * 如果能提前在当前文件传输期处理可以节省总体耗时
  2574. */
  2575. prepareNextFile: false,
  2576. /**
  2577. * @property {Boolean} [chunked=false]
  2578. * @namespace options
  2579. * @for Uploader
  2580. * @description 是否要分片处理大文件上传
  2581. */
  2582. chunked: false,
  2583. /**
  2584. * @property {Boolean} [chunkSize=5242880]
  2585. * @namespace options
  2586. * @for Uploader
  2587. * @description 如果要分片分多大一片 默认大小为5M.
  2588. */
  2589. chunkSize: 5 * 1024 * 1024,
  2590. /**
  2591. * @property {Boolean} [chunkRetry=2]
  2592. * @namespace options
  2593. * @for Uploader
  2594. * @description 如果某个分片由于网络问题出错允许自动重传多少次
  2595. */
  2596. chunkRetry: 2,
  2597. /**
  2598. * @property {Boolean} [threads=3]
  2599. * @namespace options
  2600. * @for Uploader
  2601. * @description 上传并发数允许同时最大上传进程数
  2602. */
  2603. threads: 3,
  2604. /**
  2605. * @property {Object} [formData]
  2606. * @namespace options
  2607. * @for Uploader
  2608. * @description 文件上传请求的参数表每次发送都会发送此对象中的参数
  2609. */
  2610. formData: null
  2611. /**
  2612. * @property {Object} [fileVal='file']
  2613. * @namespace options
  2614. * @for Uploader
  2615. * @description 设置文件上传域的name
  2616. */
  2617. /**
  2618. * @property {Object} [method='POST']
  2619. * @namespace options
  2620. * @for Uploader
  2621. * @description 文件上传方式`POST`或者`GET`
  2622. */
  2623. /**
  2624. * @property {Object} [sendAsBinary=false]
  2625. * @namespace options
  2626. * @for Uploader
  2627. * @description 是否已二进制的流的方式发送文件这样整个上传内容`php://input`都为文件内容
  2628. * 其他参数在$_GET数组中
  2629. */
  2630. });
  2631. // 负责将文件切片。
  2632. function CuteFile( file, chunkSize ) {
  2633. var pending = [],
  2634. blob = file.source,
  2635. total = blob.size,
  2636. chunks = chunkSize ? Math.ceil( total / chunkSize ) : 1,
  2637. start = 0,
  2638. index = 0,
  2639. len;
  2640. while ( index < chunks ) {
  2641. len = Math.min( chunkSize, total - start );
  2642. pending.push({
  2643. file: file,
  2644. start: start,
  2645. end: chunkSize ? (start + len) : total,
  2646. total: total,
  2647. chunks: chunks,
  2648. chunk: index++
  2649. });
  2650. start += len;
  2651. }
  2652. file.blocks = pending.concat();
  2653. file.remaning = pending.length;
  2654. return {
  2655. file: file,
  2656. has: function() {
  2657. return !!pending.length;
  2658. },
  2659. fetch: function() {
  2660. return pending.shift();
  2661. }
  2662. };
  2663. }
  2664. Uploader.register({
  2665. 'start-upload': 'start',
  2666. 'stop-upload': 'stop',
  2667. 'skip-file': 'skipFile',
  2668. 'is-in-progress': 'isInProgress'
  2669. }, {
  2670. init: function() {
  2671. var owner = this.owner;
  2672. this.runing = false;
  2673. // 记录当前正在传的数据,跟threads相关
  2674. this.pool = [];
  2675. // 缓存即将上传的文件。
  2676. this.pending = [];
  2677. // 跟踪还有多少分片没有完成上传。
  2678. this.remaning = 0;
  2679. this.__tick = Base.bindFn( this._tick, this );
  2680. owner.on( 'uploadComplete', function( file ) {
  2681. // 把其他块取消了。
  2682. file.blocks && $.each( file.blocks, function( _, v ) {
  2683. v.transport && (v.transport.abort(), v.transport.destroy());
  2684. delete v.transport;
  2685. });
  2686. delete file.blocks;
  2687. delete file.remaning;
  2688. });
  2689. },
  2690. /**
  2691. * @event startUpload
  2692. * @description 当开始上传流程时触发
  2693. * @for Uploader
  2694. */
  2695. /**
  2696. * 开始上传此方法可以从初始状态调用开始上传流程也可以从暂停状态调用继续上传流程
  2697. * @grammar upload() => undefined
  2698. * @method upload
  2699. * @for Uploader
  2700. */
  2701. start: function() {
  2702. var me = this;
  2703. // 移出invalid的文件
  2704. $.each( me.request( 'get-files', Status.INVALID ), function() {
  2705. me.request( 'remove-file', this );
  2706. });
  2707. if ( me.runing ) {
  2708. return;
  2709. }
  2710. me.runing = true;
  2711. // 如果有暂停的,则续传
  2712. $.each( me.pool, function( _, v ) {
  2713. var file = v.file;
  2714. if ( file.getStatus() === Status.INTERRUPT ) {
  2715. file.setStatus( Status.PROGRESS );
  2716. me._trigged = false;
  2717. v.transport && v.transport.send();
  2718. }
  2719. });
  2720. me._trigged = false;
  2721. me.owner.trigger('startUpload');
  2722. Base.nextTick( me.__tick );
  2723. },
  2724. /**
  2725. * @event stopUpload
  2726. * @description 当开始上传流程暂停时触发
  2727. * @for Uploader
  2728. */
  2729. /**
  2730. * 暂停上传第一个参数为是否中断上传当前正在上传的文件
  2731. * @grammar stop() => undefined
  2732. * @grammar stop( true ) => undefined
  2733. * @method stop
  2734. * @for Uploader
  2735. */
  2736. stop: function( interrupt ) {
  2737. var me = this;
  2738. if ( me.runing === false ) {
  2739. return;
  2740. }
  2741. me.runing = false;
  2742. interrupt && $.each( me.pool, function( _, v ) {
  2743. v.transport && v.transport.abort();
  2744. v.file.setStatus( Status.INTERRUPT );
  2745. });
  2746. me.owner.trigger('stopUpload');
  2747. },
  2748. /**
  2749. * 判断`Uplaode`r是否正在上传中
  2750. * @grammar isInProgress() => Boolean
  2751. * @method isInProgress
  2752. * @for Uploader
  2753. */
  2754. isInProgress: function() {
  2755. return !!this.runing;
  2756. },
  2757. getStats: function() {
  2758. return this.request('get-stats');
  2759. },
  2760. /**
  2761. * 掉过一个文件上传直接标记指定文件为已上传状态
  2762. * @grammar skipFile( file ) => undefined
  2763. * @method skipFile
  2764. * @for Uploader
  2765. */
  2766. skipFile: function( file, status ) {
  2767. file = this.request( 'get-file', file );
  2768. file.setStatus( status || Status.COMPLETE );
  2769. file.skipped = true;
  2770. // 如果正在上传。
  2771. file.blocks && $.each( file.blocks, function( _, v ) {
  2772. var _tr = v.transport;
  2773. if ( _tr ) {
  2774. _tr.abort();
  2775. _tr.destroy();
  2776. delete v.transport;
  2777. }
  2778. });
  2779. this.owner.trigger( 'uploadSkip', file );
  2780. },
  2781. /**
  2782. * @event uploadFinished
  2783. * @description 当所有文件上传结束时触发
  2784. * @for Uploader
  2785. */
  2786. _tick: function() {
  2787. var me = this,
  2788. opts = me.options,
  2789. fn, val;
  2790. // 上一个promise还没有结束,则等待完成后再执行。
  2791. if ( me._promise ) {
  2792. return me._promise.always( me.__tick );
  2793. }
  2794. // 还有位置,且还有文件要处理的话。
  2795. if ( me.pool.length < opts.threads && (val = me._nextBlock()) ) {
  2796. me._trigged = false;
  2797. fn = function( val ) {
  2798. me._promise = null;
  2799. // 有可能是reject过来的,所以要检测val的类型。
  2800. val && val.file && me._startSend( val );
  2801. Base.nextTick( me.__tick );
  2802. };
  2803. me._promise = isPromise( val ) ? val.always( fn ) : fn( val );
  2804. // 没有要上传的了,且没有正在传输的了。
  2805. } else if ( !me.remaning && !me.getStats().numOfQueue ) {
  2806. me.runing = false;
  2807. me._trigged || Base.nextTick(function() {
  2808. me.owner.trigger('uploadFinished');
  2809. });
  2810. me._trigged = true;
  2811. }
  2812. },
  2813. _nextBlock: function() {
  2814. var me = this,
  2815. act = me._act,
  2816. opts = me.options,
  2817. next, done;
  2818. // 如果当前文件还有没有需要传输的,则直接返回剩下的。
  2819. if ( act && act.has() &&
  2820. act.file.getStatus() === Status.PROGRESS ) {
  2821. // 是否提前准备下一个文件
  2822. if ( opts.prepareNextFile && !me.pending.length ) {
  2823. me._prepareNextFile();
  2824. }
  2825. return act.fetch();
  2826. // 否则,如果正在运行,则准备下一个文件,并等待完成后返回下个分片。
  2827. } else if ( me.runing ) {
  2828. // 如果缓存中有,则直接在缓存中取,没有则去queue中取。
  2829. if ( !me.pending.length && me.getStats().numOfQueue ) {
  2830. me._prepareNextFile();
  2831. }
  2832. next = me.pending.shift();
  2833. done = function( file ) {
  2834. if ( !file ) {
  2835. return null;
  2836. }
  2837. act = CuteFile( file, opts.chunked ? opts.chunkSize : 0 );
  2838. me._act = act;
  2839. return act.fetch();
  2840. };
  2841. // 文件可能还在prepare中,也有可能已经完全准备好了。
  2842. return isPromise( next ) ?
  2843. next[ next.pipe ? 'pipe' : 'then']( done ) :
  2844. done( next );
  2845. }
  2846. },
  2847. /**
  2848. * @event uploadStart
  2849. * @param {File} file File对象
  2850. * @description 某个文件开始上传前触发一个文件只会触发一次
  2851. * @for Uploader
  2852. */
  2853. _prepareNextFile: function() {
  2854. var me = this,
  2855. file = me.request('fetch-file'),
  2856. pending = me.pending,
  2857. promise;
  2858. if ( file ) {
  2859. promise = me.request( 'before-send-file', file, function() {
  2860. // 有可能文件被skip掉了。文件被skip掉后,状态坑定不是Queued.
  2861. if ( file.getStatus() === Status.QUEUED ) {
  2862. me.owner.trigger( 'uploadStart', file );
  2863. file.setStatus( Status.PROGRESS );
  2864. return file;
  2865. }
  2866. return me._finishFile( file );
  2867. });
  2868. // 如果还在pending中,则替换成文件本身。
  2869. promise.done(function() {
  2870. var idx = $.inArray( promise, pending );
  2871. ~idx && pending.splice( idx, 1, file );
  2872. });
  2873. // befeore-send-file的钩子就有错误发生。
  2874. promise.fail(function( reason ) {
  2875. file.setStatus( Status.ERROR, reason );
  2876. me.owner.trigger( 'uploadError', file, reason );
  2877. me.owner.trigger( 'uploadComplete', file );
  2878. });
  2879. pending.push( promise );
  2880. }
  2881. },
  2882. // 让出位置了,可以让其他分片开始上传
  2883. _popBlock: function( block ) {
  2884. var idx = $.inArray( block, this.pool );
  2885. this.pool.splice( idx, 1 );
  2886. block.file.remaning--;
  2887. this.remaning--;
  2888. },
  2889. // 开始上传,可以被掉过。如果promise被reject了,则表示跳过此分片。
  2890. _startSend: function( block ) {
  2891. var me = this,
  2892. file = block.file,
  2893. promise;
  2894. me.pool.push( block );
  2895. me.remaning++;
  2896. // 如果没有分片,则直接使用原始的。
  2897. // 不会丢失content-type信息。
  2898. block.blob = block.chunks === 1 ? file.source :
  2899. file.source.slice( block.start, block.end );
  2900. // hook, 每个分片发送之前可能要做些异步的事情。
  2901. promise = me.request( 'before-send', block, function() {
  2902. // 有可能文件已经上传出错了,所以不需要再传输了。
  2903. if ( file.getStatus() === Status.PROGRESS ) {
  2904. me._doSend( block );
  2905. } else {
  2906. me._popBlock( block );
  2907. Base.nextTick( me.__tick );
  2908. }
  2909. });
  2910. // 如果为fail了,则跳过此分片。
  2911. promise.fail(function() {
  2912. if ( file.remaning === 1 ) {
  2913. me._finishFile( file ).always(function() {
  2914. block.percentage = 1;
  2915. me._popBlock( block );
  2916. me.owner.trigger( 'uploadComplete', file );
  2917. Base.nextTick( me.__tick );
  2918. });
  2919. } else {
  2920. block.percentage = 1;
  2921. me._popBlock( block );
  2922. Base.nextTick( me.__tick );
  2923. }
  2924. });
  2925. },
  2926. /**
  2927. * @event uploadBeforeSend
  2928. * @param {Object} object
  2929. * @param {Object} data 默认的上传参数可以扩展此对象来控制上传参数
  2930. * @description 当某个文件的分块在发送前触发主要用来询问是否要添加附带参数大文件在开起分片上传的前提下此事件可能会触发多次
  2931. * @for Uploader
  2932. */
  2933. /**
  2934. * @event uploadAccept
  2935. * @param {Object} object
  2936. * @param {Object} ret 服务端的返回数据json格式如果服务端不是json格式从ret._raw中取数据自行解析
  2937. * @description 当某个文件上传到服务端响应后会派送此事件来询问服务端响应是否有效如果此事件handler返回值为`false`, 则此文件将派送`server`类型的`uploadError`事件
  2938. * @for Uploader
  2939. */
  2940. /**
  2941. * @event uploadProgress
  2942. * @param {File} file File对象
  2943. * @param {Number} percentage 上传进度
  2944. * @description 上传过程中触发携带上传进度
  2945. * @for Uploader
  2946. */
  2947. /**
  2948. * @event uploadError
  2949. * @param {File} file File对象
  2950. * @param {String} reason 出错的code
  2951. * @description 当文件上传出错时触发
  2952. * @for Uploader
  2953. */
  2954. /**
  2955. * @event uploadSuccess
  2956. * @param {File} file File对象
  2957. * @param {Object} response 服务端返回的数据
  2958. * @description 当文件上传成功时触发
  2959. * @for Uploader
  2960. */
  2961. /**
  2962. * @event uploadComplete
  2963. * @param {File} [file] File对象
  2964. * @description 不管成功或者失败文件上传完成时触发
  2965. * @for Uploader
  2966. */
  2967. // 做上传操作。
  2968. _doSend: function( block ) {
  2969. var me = this,
  2970. owner = me.owner,
  2971. opts = me.options,
  2972. file = block.file,
  2973. tr = new Transport( opts ),
  2974. data = $.extend({}, opts.formData ),
  2975. headers = $.extend({}, opts.headers ),
  2976. requestAccept, ret;
  2977. block.transport = tr;
  2978. tr.on( 'destroy', function() {
  2979. delete block.transport;
  2980. me._popBlock( block );
  2981. Base.nextTick( me.__tick );
  2982. });
  2983. // 广播上传进度。以文件为单位。
  2984. tr.on( 'progress', function( percentage ) {
  2985. var totalPercent = 0,
  2986. uploaded = 0;
  2987. // 可能没有abort掉,progress还是执行进来了。
  2988. // if ( !file.blocks ) {
  2989. // return;
  2990. // }
  2991. totalPercent = block.percentage = percentage;
  2992. if ( block.chunks > 1 ) { // 计算文件的整体速度。
  2993. $.each( file.blocks, function( _, v ) {
  2994. uploaded += (v.percentage || 0) * (v.end - v.start);
  2995. });
  2996. totalPercent = uploaded / file.size;
  2997. }
  2998. owner.trigger( 'uploadProgress', file, totalPercent || 0 );
  2999. });
  3000. // 用来询问,是否返回的结果是有错误的。
  3001. requestAccept = function( reject ) {
  3002. var fn;
  3003. ret = tr.getResponseAsJson() || {};
  3004. ret._raw = tr.getResponse();
  3005. fn = function( value ) {
  3006. reject = value;
  3007. };
  3008. // 服务端响应了,不代表成功了,询问是否响应正确。
  3009. if ( !owner.trigger( 'uploadAccept', block, ret, fn ) ) {
  3010. reject = reject || 'server';
  3011. }
  3012. return reject;
  3013. };
  3014. // 尝试重试,然后广播文件上传出错。
  3015. tr.on( 'error', function( type, flag ) {
  3016. block.retried = block.retried || 0;
  3017. // 自动重试
  3018. if ( block.chunks > 1 && ~'http,abort'.indexOf( type ) &&
  3019. block.retried < opts.chunkRetry ) {
  3020. block.retried++;
  3021. tr.send();
  3022. } else {
  3023. // http status 500 ~ 600
  3024. if ( !flag && type === 'server' ) {
  3025. type = requestAccept( type );
  3026. }
  3027. file.setStatus( Status.ERROR, type );
  3028. owner.trigger( 'uploadError', file, type );
  3029. owner.trigger( 'uploadComplete', file );
  3030. }
  3031. });
  3032. // 上传成功
  3033. tr.on( 'load', function() {
  3034. var reason;
  3035. // 如果非预期,转向上传出错。
  3036. if ( (reason = requestAccept()) ) {
  3037. tr.trigger( 'error', reason, true );
  3038. return;
  3039. }
  3040. // 全部上传完成。
  3041. if ( file.remaning === 1 ) {
  3042. me._finishFile( file, ret );
  3043. } else {
  3044. tr.destroy();
  3045. }
  3046. });
  3047. // 配置默认的上传字段。
  3048. data = $.extend( data, {
  3049. id: file.id,
  3050. name: file.name,
  3051. type: file.type,
  3052. lastModifiedDate: file.lastModifiedDate,
  3053. size: file.size
  3054. });
  3055. block.chunks > 1 && $.extend( data, {
  3056. chunks: block.chunks,
  3057. chunk: block.chunk
  3058. });
  3059. // 在发送之间可以添加字段什么的。。。
  3060. // 如果默认的字段不够使用,可以通过监听此事件来扩展
  3061. owner.trigger( 'uploadBeforeSend', block, data, headers );
  3062. // 开始发送。
  3063. tr.appendBlob( opts.fileVal, block.blob, file.name );
  3064. tr.append( data );
  3065. tr.setRequestHeader( headers );
  3066. tr.send();
  3067. },
  3068. // 完成上传。
  3069. _finishFile: function( file, ret, hds ) {
  3070. var owner = this.owner;
  3071. return owner
  3072. .request( 'after-send-file', arguments, function() {
  3073. file.setStatus( Status.COMPLETE );
  3074. owner.trigger( 'uploadSuccess', file, ret, hds );
  3075. })
  3076. .fail(function( reason ) {
  3077. // 如果外部已经标记为invalid什么的,不再改状态。
  3078. if ( file.getStatus() === Status.PROGRESS ) {
  3079. file.setStatus( Status.ERROR, reason );
  3080. }
  3081. owner.trigger( 'uploadError', file, reason );
  3082. })
  3083. .always(function() {
  3084. owner.trigger( 'uploadComplete', file );
  3085. });
  3086. }
  3087. });
  3088. });
  3089. /**
  3090. * @fileOverview 各种验证包括文件总大小是否超出单文件是否超出和文件是否重复
  3091. */
  3092. define('widgets/validator',[
  3093. 'base',
  3094. 'uploader',
  3095. 'file',
  3096. 'widgets/widget'
  3097. ], function( Base, Uploader, WUFile ) {
  3098. var $ = Base.$,
  3099. validators = {},
  3100. api;
  3101. /**
  3102. * @event error
  3103. * @param {String} type 错误类型
  3104. * @description 当validate不通过时会以派送错误事件的形式通知调用者通过`upload.on('error', handler)`可以捕获到此类错误目前有以下错误会在特定的情况下派送错来
  3105. *
  3106. * * `Q_EXCEED_NUM_LIMIT` 在设置了`fileNumLimit`且尝试给`uploader`添加的文件数量超出这个值时派送
  3107. * * `Q_EXCEED_SIZE_LIMIT` 在设置了`Q_EXCEED_SIZE_LIMIT`且尝试给`uploader`添加的文件总大小超出这个值时派送
  3108. * @for Uploader
  3109. */
  3110. // 暴露给外面的api
  3111. api = {
  3112. // 添加验证器
  3113. addValidator: function( type, cb ) {
  3114. validators[ type ] = cb;
  3115. },
  3116. // 移除验证器
  3117. removeValidator: function( type ) {
  3118. delete validators[ type ];
  3119. }
  3120. };
  3121. // 在Uploader初始化的时候启动Validators的初始化
  3122. Uploader.register({
  3123. init: function() {
  3124. var me = this;
  3125. $.each( validators, function() {
  3126. this.call( me.owner );
  3127. });
  3128. }
  3129. });
  3130. /**
  3131. * @property {int} [fileNumLimit=undefined]
  3132. * @namespace options
  3133. * @for Uploader
  3134. * @description 验证文件总数量, 超出则不允许加入队列
  3135. */
  3136. api.addValidator( 'fileNumLimit', function() {
  3137. var uploader = this,
  3138. opts = uploader.options,
  3139. count = 0,
  3140. max = opts.fileNumLimit >> 0,
  3141. flag = true;
  3142. if ( !max ) {
  3143. return;
  3144. }
  3145. uploader.on( 'beforeFileQueued', function( file ) {
  3146. if ( count >= max && flag ) {
  3147. flag = false;
  3148. this.trigger( 'error', 'Q_EXCEED_NUM_LIMIT', max, file );
  3149. setTimeout(function() {
  3150. flag = true;
  3151. }, 1 );
  3152. }
  3153. return count >= max ? false : true;
  3154. });
  3155. uploader.on( 'fileQueued', function() {
  3156. count++;
  3157. });
  3158. uploader.on( 'fileDequeued', function() {
  3159. count--;
  3160. });
  3161. uploader.on( 'uploadFinished', function() {
  3162. count = 0;
  3163. });
  3164. });
  3165. /**
  3166. * @property {int} [fileSizeLimit=undefined]
  3167. * @namespace options
  3168. * @for Uploader
  3169. * @description 验证文件总大小是否超出限制, 超出则不允许加入队列
  3170. */
  3171. api.addValidator( 'fileSizeLimit', function() {
  3172. var uploader = this,
  3173. opts = uploader.options,
  3174. count = 0,
  3175. max = opts.fileSizeLimit >> 0,
  3176. flag = true;
  3177. if ( !max ) {
  3178. return;
  3179. }
  3180. uploader.on( 'beforeFileQueued', function( file ) {
  3181. var invalid = count + file.size > max;
  3182. if ( invalid && flag ) {
  3183. flag = false;
  3184. this.trigger( 'error', 'Q_EXCEED_SIZE_LIMIT', max, file );
  3185. setTimeout(function() {
  3186. flag = true;
  3187. }, 1 );
  3188. }
  3189. return invalid ? false : true;
  3190. });
  3191. uploader.on( 'fileQueued', function( file ) {
  3192. count += file.size;
  3193. });
  3194. uploader.on( 'fileDequeued', function( file ) {
  3195. count -= file.size;
  3196. });
  3197. uploader.on( 'uploadFinished', function() {
  3198. count = 0;
  3199. });
  3200. });
  3201. /**
  3202. * @property {int} [fileSingleSizeLimit=undefined]
  3203. * @namespace options
  3204. * @for Uploader
  3205. * @description 验证单个文件大小是否超出限制, 超出则不允许加入队列
  3206. */
  3207. api.addValidator( 'fileSingleSizeLimit', function() {
  3208. var uploader = this,
  3209. opts = uploader.options,
  3210. max = opts.fileSingleSizeLimit;
  3211. if ( !max ) {
  3212. return;
  3213. }
  3214. uploader.on( 'beforeFileQueued', function( file ) {
  3215. if ( file.size > max ) {
  3216. file.setStatus( WUFile.Status.INVALID, 'exceed_size' );
  3217. this.trigger( 'error', 'F_EXCEED_SIZE', file );
  3218. return false;
  3219. }
  3220. });
  3221. });
  3222. /**
  3223. * @property {int} [duplicate=undefined]
  3224. * @namespace options
  3225. * @for Uploader
  3226. * @description 去重 根据文件名字文件大小和最后修改时间来生成hash Key.
  3227. */
  3228. api.addValidator( 'duplicate', function() {
  3229. var uploader = this,
  3230. opts = uploader.options,
  3231. mapping = {};
  3232. if ( opts.duplicate ) {
  3233. return;
  3234. }
  3235. function hashString( str ) {
  3236. var hash = 0,
  3237. i = 0,
  3238. len = str.length,
  3239. _char;
  3240. for ( ; i < len; i++ ) {
  3241. _char = str.charCodeAt( i );
  3242. hash = _char + (hash << 6) + (hash << 16) - hash;
  3243. }
  3244. return hash;
  3245. }
  3246. uploader.on( 'beforeFileQueued', function( file ) {
  3247. var hash = file.__hash || (file.__hash = hashString( file.name +
  3248. file.size + file.lastModifiedDate ));
  3249. // 已经重复了
  3250. if ( mapping[ hash ] ) {
  3251. this.trigger( 'error', 'F_DUPLICATE', file );
  3252. return false;
  3253. }
  3254. });
  3255. uploader.on( 'fileQueued', function( file ) {
  3256. var hash = file.__hash;
  3257. hash && (mapping[ hash ] = true);
  3258. });
  3259. uploader.on( 'fileDequeued', function( file ) {
  3260. var hash = file.__hash;
  3261. hash && (delete mapping[ hash ]);
  3262. });
  3263. });
  3264. return api;
  3265. });
  3266. /**
  3267. * @fileOverview Runtime管理器负责Runtime的选择, 连接
  3268. */
  3269. define('runtime/compbase',[],function() {
  3270. function CompBase( owner, runtime ) {
  3271. this.owner = owner;
  3272. this.options = owner.options;
  3273. this.getRuntime = function() {
  3274. return runtime;
  3275. };
  3276. this.getRuid = function() {
  3277. return runtime.uid;
  3278. };
  3279. this.trigger = function() {
  3280. return owner.trigger.apply( owner, arguments );
  3281. };
  3282. }
  3283. return CompBase;
  3284. });
  3285. /**
  3286. * @fileOverview Html5Runtime
  3287. */
  3288. define('runtime/html5/runtime',[
  3289. 'base',
  3290. 'runtime/runtime',
  3291. 'runtime/compbase'
  3292. ], function( Base, Runtime, CompBase ) {
  3293. var type = 'html5',
  3294. components = {};
  3295. function Html5Runtime() {
  3296. var pool = {},
  3297. me = this,
  3298. destory = this.destory;
  3299. Runtime.apply( me, arguments );
  3300. me.type = type;
  3301. // 这个方法的调用者,实际上是RuntimeClient
  3302. me.exec = function( comp, fn/*, args...*/) {
  3303. var client = this,
  3304. uid = client.uid,
  3305. args = Base.slice( arguments, 2 ),
  3306. instance;
  3307. if ( components[ comp ] ) {
  3308. instance = pool[ uid ] = pool[ uid ] ||
  3309. new components[ comp ]( client, me );
  3310. if ( instance[ fn ] ) {
  3311. return instance[ fn ].apply( instance, args );
  3312. }
  3313. }
  3314. };
  3315. me.destory = function() {
  3316. // @todo 删除池子中的所有实例
  3317. return destory && destory.apply( this, arguments );
  3318. };
  3319. }
  3320. Base.inherits( Runtime, {
  3321. constructor: Html5Runtime,
  3322. // 不需要连接其他程序,直接执行callback
  3323. init: function() {
  3324. var me = this;
  3325. setTimeout(function() {
  3326. me.trigger('ready');
  3327. }, 1 );
  3328. }
  3329. });
  3330. // 注册Components
  3331. Html5Runtime.register = function( name, component ) {
  3332. var klass = components[ name ] = Base.inherits( CompBase, component );
  3333. return klass;
  3334. };
  3335. // 注册html5运行时。
  3336. // 只有在支持的前提下注册。
  3337. if ( window.Blob && window.FileReader && window.DataView ) {
  3338. Runtime.addRuntime( type, Html5Runtime );
  3339. }
  3340. return Html5Runtime;
  3341. });
  3342. /**
  3343. * @fileOverview Blob Html实现
  3344. */
  3345. define('runtime/html5/blob',[
  3346. 'runtime/html5/runtime',
  3347. 'lib/blob'
  3348. ], function( Html5Runtime, Blob ) {
  3349. return Html5Runtime.register( 'Blob', {
  3350. slice: function( start, end ) {
  3351. var blob = this.owner.source,
  3352. slice = blob.slice || blob.webkitSlice || blob.mozSlice;
  3353. blob = slice.call( blob, start, end );
  3354. return new Blob( this.getRuid(), blob );
  3355. }
  3356. });
  3357. });
  3358. /**
  3359. * @fileOverview FilePaste
  3360. */
  3361. define('runtime/html5/dnd',[
  3362. 'base',
  3363. 'runtime/html5/runtime',
  3364. 'lib/file'
  3365. ], function( Base, Html5Runtime, File ) {
  3366. var $ = Base.$,
  3367. prefix = 'webuploader-dnd-';
  3368. return Html5Runtime.register( 'DragAndDrop', {
  3369. init: function() {
  3370. var elem = this.elem = this.options.container;
  3371. this.dragEnterHandler = Base.bindFn( this._dragEnterHandler, this );
  3372. this.dragOverHandler = Base.bindFn( this._dragOverHandler, this );
  3373. this.dragLeaveHandler = Base.bindFn( this._dragLeaveHandler, this );
  3374. this.dropHandler = Base.bindFn( this._dropHandler, this );
  3375. this.dndOver = false;
  3376. elem.on( 'dragenter', this.dragEnterHandler );
  3377. elem.on( 'dragover', this.dragOverHandler );
  3378. elem.on( 'dragleave', this.dragLeaveHandler );
  3379. elem.on( 'drop', this.dropHandler );
  3380. if ( this.options.disableGlobalDnd ) {
  3381. $( document ).on( 'dragover', this.dragOverHandler );
  3382. $( document ).on( 'drop', this.dropHandler );
  3383. }
  3384. },
  3385. _dragEnterHandler: function( e ) {
  3386. var me = this,
  3387. denied = me._denied || false,
  3388. items;
  3389. e = e.originalEvent || e;
  3390. if ( !me.dndOver ) {
  3391. me.dndOver = true;
  3392. // 注意只有 chrome 支持。
  3393. items = e.dataTransfer.items;
  3394. if ( items && items.length ) {
  3395. me._denied = denied = !me.trigger( 'accept', items );
  3396. }
  3397. me.elem.addClass( prefix + 'over' );
  3398. me.elem[ denied ? 'addClass' :
  3399. 'removeClass' ]( prefix + 'denied' );
  3400. }
  3401. e.dataTransfer.dropEffect = denied ? 'none' : 'copy';
  3402. return false;
  3403. },
  3404. _dragOverHandler: function( e ) {
  3405. // 只处理框内的。
  3406. var parentElem = this.elem.parent().get( 0 );
  3407. if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) {
  3408. return false;
  3409. }
  3410. clearTimeout( this._leaveTimer );
  3411. this._dragEnterHandler.call( this, e );
  3412. return false;
  3413. },
  3414. _dragLeaveHandler: function() {
  3415. var me = this,
  3416. handler;
  3417. handler = function() {
  3418. me.dndOver = false;
  3419. me.elem.removeClass( prefix + 'over ' + prefix + 'denied' );
  3420. };
  3421. clearTimeout( me._leaveTimer );
  3422. me._leaveTimer = setTimeout( handler, 100 );
  3423. return false;
  3424. },
  3425. _dropHandler: function( e ) {
  3426. var me = this,
  3427. ruid = me.getRuid(),
  3428. parentElem = me.elem.parent().get( 0 );
  3429. // 只处理框内的。
  3430. if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) {
  3431. return false;
  3432. }
  3433. me._getTansferFiles( e, function( results ) {
  3434. me.trigger( 'drop', $.map( results, function( file ) {
  3435. return new File( ruid, file );
  3436. }) );
  3437. });
  3438. me.dndOver = false;
  3439. me.elem.removeClass( prefix + 'over' );
  3440. return false;
  3441. },
  3442. // 如果传入 callback 则去查看文件夹,否则只管当前文件夹。
  3443. _getTansferFiles: function( e, callback ) {
  3444. var results = [],
  3445. promises = [],
  3446. items, files, dataTransfer, file, item, i, len, canAccessFolder;
  3447. e = e.originalEvent || e;
  3448. dataTransfer = e.dataTransfer;
  3449. items = dataTransfer.items;
  3450. files = dataTransfer.files;
  3451. canAccessFolder = !!(items && items[ 0 ].webkitGetAsEntry);
  3452. for ( i = 0, len = files.length; i < len; i++ ) {
  3453. file = files[ i ];
  3454. item = items && items[ i ];
  3455. if ( canAccessFolder && item.webkitGetAsEntry().isDirectory ) {
  3456. promises.push( this._traverseDirectoryTree(
  3457. item.webkitGetAsEntry(), results ) );
  3458. } else {
  3459. results.push( file );
  3460. }
  3461. }
  3462. Base.when.apply( Base, promises ).done(function() {
  3463. if ( !results.length ) {
  3464. return;
  3465. }
  3466. callback( results );
  3467. });
  3468. },
  3469. _traverseDirectoryTree: function( entry, results ) {
  3470. var deferred = Base.Deferred(),
  3471. me = this;
  3472. if ( entry.isFile ) {
  3473. entry.file(function( file ) {
  3474. results.push( file );
  3475. deferred.resolve();
  3476. });
  3477. } else if ( entry.isDirectory ) {
  3478. entry.createReader().readEntries(function( entries ) {
  3479. var len = entries.length,
  3480. promises = [],
  3481. arr = [], // 为了保证顺序。
  3482. i;
  3483. for ( i = 0; i < len; i++ ) {
  3484. promises.push( me._traverseDirectoryTree(
  3485. entries[ i ], arr ) );
  3486. }
  3487. Base.when.apply( Base, promises ).then(function() {
  3488. results.push.apply( results, arr );
  3489. deferred.resolve();
  3490. }, deferred.reject );
  3491. });
  3492. }
  3493. return deferred.promise();
  3494. },
  3495. destroy: function() {
  3496. var elem = this.elem;
  3497. elem.off( 'dragenter', this.dragEnterHandler );
  3498. elem.off( 'dragover', this.dragEnterHandler );
  3499. elem.off( 'dragleave', this.dragLeaveHandler );
  3500. elem.off( 'drop', this.dropHandler );
  3501. if ( this.options.disableGlobalDnd ) {
  3502. $( document ).off( 'dragover', this.dragOverHandler );
  3503. $( document ).off( 'drop', this.dropHandler );
  3504. }
  3505. }
  3506. });
  3507. });
  3508. /**
  3509. * @fileOverview FilePaste
  3510. */
  3511. define('runtime/html5/filepaste',[
  3512. 'base',
  3513. 'runtime/html5/runtime',
  3514. 'lib/file'
  3515. ], function( Base, Html5Runtime, File ) {
  3516. return Html5Runtime.register( 'FilePaste', {
  3517. init: function() {
  3518. var opts = this.options,
  3519. elem = this.elem = opts.container,
  3520. accept = '.*',
  3521. arr, i, len, item;
  3522. // accetp的mimeTypes中生成匹配正则。
  3523. if ( opts.accept ) {
  3524. arr = [];
  3525. for ( i = 0, len = opts.accept.length; i < len; i++ ) {
  3526. item = opts.accept[ i ].mimeTypes;
  3527. item && arr.push( item );
  3528. }
  3529. if ( arr.length ) {
  3530. accept = arr.join(',');
  3531. accept = accept.replace( /,/g, '|' ).replace( /\*/g, '.*' );
  3532. }
  3533. }
  3534. this.accept = accept = new RegExp( accept, 'i' );
  3535. this.hander = Base.bindFn( this._pasteHander, this );
  3536. elem.on( 'paste', this.hander );
  3537. },
  3538. _pasteHander: function( e ) {
  3539. var allowed = [],
  3540. ruid = this.getRuid(),
  3541. items, item, blob, i, len;
  3542. e = e.originalEvent || e;
  3543. items = e.clipboardData.items;
  3544. for ( i = 0, len = items.length; i < len; i++ ) {
  3545. item = items[ i ];
  3546. if ( item.kind !== 'file' || !(blob = item.getAsFile()) ) {
  3547. continue;
  3548. }
  3549. allowed.push( new File( ruid, blob ) );
  3550. }
  3551. if ( allowed.length ) {
  3552. // 不阻止非文件粘贴(文字粘贴)的事件冒泡
  3553. e.preventDefault();
  3554. e.stopPropagation();
  3555. this.trigger( 'paste', allowed );
  3556. }
  3557. },
  3558. destroy: function() {
  3559. this.elem.off( 'paste', this.hander );
  3560. }
  3561. });
  3562. });
  3563. /**
  3564. * @fileOverview FilePicker
  3565. */
  3566. define('runtime/html5/filepicker',[
  3567. 'base',
  3568. 'runtime/html5/runtime'
  3569. ], function( Base, Html5Runtime ) {
  3570. var $ = Base.$;
  3571. return Html5Runtime.register( 'FilePicker', {
  3572. init: function() {
  3573. var container = this.getRuntime().getContainer(),
  3574. me = this,
  3575. owner = me.owner,
  3576. opts = me.options,
  3577. lable = $( document.createElement('label') ),
  3578. input = $( document.createElement('input') ),
  3579. arr, i, len, mouseHandler;
  3580. input.attr( 'type', 'file' );
  3581. input.attr( 'name', opts.name );
  3582. input.addClass('webuploader-element-invisible');
  3583. lable.on( 'click', function() {
  3584. input.trigger('click');
  3585. });
  3586. lable.css({
  3587. opacity: 0,
  3588. width: '100%',
  3589. height: '100%',
  3590. display: 'block',
  3591. cursor: 'pointer',
  3592. background: '#ffffff'
  3593. });
  3594. if ( opts.multiple ) {
  3595. input.attr( 'multiple', 'multiple' );
  3596. }
  3597. // @todo Firefox不支持单独指定后缀
  3598. if ( opts.accept && opts.accept.length > 0 ) {
  3599. arr = [];
  3600. for ( i = 0, len = opts.accept.length; i < len; i++ ) {
  3601. arr.push( opts.accept[ i ].mimeTypes );
  3602. }
  3603. input.attr( 'accept', arr.join(',') );
  3604. }
  3605. container.append( input );
  3606. container.append( lable );
  3607. mouseHandler = function( e ) {
  3608. owner.trigger( e.type );
  3609. };
  3610. input.on( 'change', function( e ) {
  3611. var fn = arguments.callee,
  3612. clone;
  3613. me.files = e.target.files;
  3614. // reset input
  3615. clone = this.cloneNode( true );
  3616. this.parentNode.replaceChild( clone, this );
  3617. input.off();
  3618. input = $( clone ).on( 'change', fn )
  3619. .on( 'mouseenter mouseleave', mouseHandler );
  3620. owner.trigger('change');
  3621. });
  3622. lable.on( 'mouseenter mouseleave', mouseHandler );
  3623. },
  3624. getFiles: function() {
  3625. return this.files;
  3626. },
  3627. destroy: function() {
  3628. // todo
  3629. }
  3630. });
  3631. });
  3632. /**
  3633. * Terms:
  3634. *
  3635. * Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
  3636. * @fileOverview Image控件
  3637. */
  3638. define('runtime/html5/util',[
  3639. 'base'
  3640. ], function( Base ) {
  3641. var urlAPI = window.createObjectURL && window ||
  3642. window.URL && URL.revokeObjectURL && URL ||
  3643. window.webkitURL,
  3644. createObjectURL = Base.noop,
  3645. revokeObjectURL = createObjectURL;
  3646. if ( urlAPI ) {
  3647. // 更安全的方式调用,比如android里面就能把context改成其他的对象。
  3648. createObjectURL = function() {
  3649. return urlAPI.createObjectURL.apply( urlAPI, arguments );
  3650. };
  3651. revokeObjectURL = function() {
  3652. return urlAPI.revokeObjectURL.apply( urlAPI, arguments );
  3653. };
  3654. }
  3655. return {
  3656. createObjectURL: createObjectURL,
  3657. revokeObjectURL: revokeObjectURL,
  3658. dataURL2Blob: function( dataURI ) {
  3659. var byteStr, intArray, ab, i, mimetype, parts;
  3660. parts = dataURI.split(',');
  3661. if ( ~parts[ 0 ].indexOf('base64') ) {
  3662. byteStr = atob( parts[ 1 ] );
  3663. } else {
  3664. byteStr = decodeURIComponent( parts[ 1 ] );
  3665. }
  3666. ab = new ArrayBuffer( byteStr.length );
  3667. intArray = new Uint8Array( ab );
  3668. for ( i = 0; i < byteStr.length; i++ ) {
  3669. intArray[ i ] = byteStr.charCodeAt( i );
  3670. }
  3671. mimetype = parts[ 0 ].split(':')[ 1 ].split(';')[ 0 ];
  3672. return this.arrayBufferToBlob( ab, mimetype );
  3673. },
  3674. dataURL2ArrayBuffer: function( dataURI ) {
  3675. var byteStr, intArray, i, parts;
  3676. parts = dataURI.split(',');
  3677. if ( ~parts[ 0 ].indexOf('base64') ) {
  3678. byteStr = atob( parts[ 1 ] );
  3679. } else {
  3680. byteStr = decodeURIComponent( parts[ 1 ] );
  3681. }
  3682. intArray = new Uint8Array( byteStr.length );
  3683. for ( i = 0; i < byteStr.length; i++ ) {
  3684. intArray[ i ] = byteStr.charCodeAt( i );
  3685. }
  3686. return intArray.buffer;
  3687. },
  3688. arrayBufferToBlob: function( buffer, type ) {
  3689. var builder = window.BlobBuilder || window.WebKitBlobBuilder,
  3690. bb;
  3691. // android不支持直接new Blob, 只能借助blobbuilder.
  3692. if ( builder ) {
  3693. bb = new builder();
  3694. bb.append( buffer );
  3695. return bb.getBlob( type );
  3696. }
  3697. return new Blob([ buffer ], type ? { type: type } : {} );
  3698. },
  3699. // 抽出来主要是为了解决android下面canvas.toDataUrl不支持jpeg.
  3700. // 你得到的结果是png.
  3701. canvasToDataUrl: function( canvas, type, quality ) {
  3702. return canvas.toDataURL( type, quality / 100 );
  3703. },
  3704. // imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
  3705. parseMeta: function( blob, callback ) {
  3706. callback( false, {});
  3707. },
  3708. // imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
  3709. updateImageHead: function( data ) {
  3710. return data;
  3711. }
  3712. };
  3713. });
  3714. /**
  3715. * Terms:
  3716. *
  3717. * Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
  3718. * @fileOverview Image控件
  3719. */
  3720. define('runtime/html5/imagemeta',[
  3721. 'runtime/html5/util'
  3722. ], function( Util ) {
  3723. var api;
  3724. api = {
  3725. parsers: {
  3726. 0xffe1: []
  3727. },
  3728. maxMetaDataSize: 262144,
  3729. parse: function( blob, cb ) {
  3730. var me = this,
  3731. fr = new FileReader();
  3732. fr.onload = function() {
  3733. cb( false, me._parse( this.result ) );
  3734. fr = fr.onload = fr.onerror = null;
  3735. };
  3736. fr.onerror = function( e ) {
  3737. cb( e.message );
  3738. fr = fr.onload = fr.onerror = null;
  3739. };
  3740. blob = blob.slice( 0, me.maxMetaDataSize );
  3741. fr.readAsArrayBuffer( blob.getSource() );
  3742. },
  3743. _parse: function( buffer, noParse ) {
  3744. if ( buffer.byteLength < 6 ) {
  3745. return;
  3746. }
  3747. var dataview = new DataView( buffer ),
  3748. offset = 2,
  3749. maxOffset = dataview.byteLength - 4,
  3750. headLength = offset,
  3751. ret = {},
  3752. markerBytes, markerLength, parsers, i;
  3753. if ( dataview.getUint16( 0 ) === 0xffd8 ) {
  3754. while ( offset < maxOffset ) {
  3755. markerBytes = dataview.getUint16( offset );
  3756. if ( markerBytes >= 0xffe0 && markerBytes <= 0xffef ||
  3757. markerBytes === 0xfffe ) {
  3758. markerLength = dataview.getUint16( offset + 2 ) + 2;
  3759. if ( offset + markerLength > dataview.byteLength ) {
  3760. break;
  3761. }
  3762. parsers = api.parsers[ markerBytes ];
  3763. if ( !noParse && parsers ) {
  3764. for ( i = 0; i < parsers.length; i += 1 ) {
  3765. parsers[ i ].call( api, dataview, offset,
  3766. markerLength, ret );
  3767. }
  3768. }
  3769. offset += markerLength;
  3770. headLength = offset;
  3771. } else {
  3772. break;
  3773. }
  3774. }
  3775. if ( headLength > 6 ) {
  3776. if ( buffer.slice ) {
  3777. ret.imageHead = buffer.slice( 2, headLength );
  3778. } else {
  3779. // Workaround for IE10, which does not yet
  3780. // support ArrayBuffer.slice:
  3781. ret.imageHead = new Uint8Array( buffer )
  3782. .subarray( 2, headLength );
  3783. }
  3784. }
  3785. }
  3786. return ret;
  3787. },
  3788. updateImageHead: function( buffer, head ) {
  3789. var data = this._parse( buffer, true ),
  3790. buf1, buf2, bodyoffset;
  3791. bodyoffset = 2;
  3792. if ( data.imageHead ) {
  3793. bodyoffset = 2 + data.imageHead.byteLength;
  3794. }
  3795. if ( buffer.slice ) {
  3796. buf2 = buffer.slice( bodyoffset );
  3797. } else {
  3798. buf2 = new Uint8Array( buffer ).subarray( bodyoffset );
  3799. }
  3800. buf1 = new Uint8Array( head.byteLength + 2 + buf2.byteLength );
  3801. buf1[ 0 ] = 0xFF;
  3802. buf1[ 1 ] = 0xD8;
  3803. buf1.set( new Uint8Array( head ), 2 );
  3804. buf1.set( new Uint8Array( buf2 ), head.byteLength + 2 );
  3805. return buf1.buffer;
  3806. }
  3807. };
  3808. Util.parseMeta = function() {
  3809. return api.parse.apply( api, arguments );
  3810. };
  3811. Util.updateImageHead = function() {
  3812. return api.updateImageHead.apply( api, arguments );
  3813. };
  3814. return api;
  3815. });
  3816. /**
  3817. * 代码来自于https://github.com/blueimp/JavaScript-Load-Image
  3818. * 暂时项目中只用了orientation.
  3819. *
  3820. * 去除了 Exif Sub IFD Pointer, GPS Info IFD Pointer, Exif Thumbnail.
  3821. * @fileOverview EXIF解析
  3822. */
  3823. // Sample
  3824. // ====================================
  3825. // Make : Apple
  3826. // Model : iPhone 4S
  3827. // Orientation : 1
  3828. // XResolution : 72 [72/1]
  3829. // YResolution : 72 [72/1]
  3830. // ResolutionUnit : 2
  3831. // Software : QuickTime 7.7.1
  3832. // DateTime : 2013:09:01 22:53:55
  3833. // ExifIFDPointer : 190
  3834. // ExposureTime : 0.058823529411764705 [1/17]
  3835. // FNumber : 2.4 [12/5]
  3836. // ExposureProgram : Normal program
  3837. // ISOSpeedRatings : 800
  3838. // ExifVersion : 0220
  3839. // DateTimeOriginal : 2013:09:01 22:52:51
  3840. // DateTimeDigitized : 2013:09:01 22:52:51
  3841. // ComponentsConfiguration : YCbCr
  3842. // ShutterSpeedValue : 4.058893515764426
  3843. // ApertureValue : 2.5260688216892597 [4845/1918]
  3844. // BrightnessValue : -0.3126686601998395
  3845. // MeteringMode : Pattern
  3846. // Flash : Flash did not fire, compulsory flash mode
  3847. // FocalLength : 4.28 [107/25]
  3848. // SubjectArea : [4 values]
  3849. // FlashpixVersion : 0100
  3850. // ColorSpace : 1
  3851. // PixelXDimension : 2448
  3852. // PixelYDimension : 3264
  3853. // SensingMethod : One-chip color area sensor
  3854. // ExposureMode : 0
  3855. // WhiteBalance : Auto white balance
  3856. // FocalLengthIn35mmFilm : 35
  3857. // SceneCaptureType : Standard
  3858. define('runtime/html5/imagemeta/exif',[
  3859. 'base',
  3860. 'runtime/html5/imagemeta'
  3861. ], function( Base, ImageMeta ) {
  3862. var EXIF = {};
  3863. EXIF.ExifMap = function() {
  3864. return this;
  3865. };
  3866. EXIF.ExifMap.prototype.map = {
  3867. 'Orientation': 0x0112
  3868. };
  3869. EXIF.ExifMap.prototype.get = function( id ) {
  3870. return this[ id ] || this[ this.map[ id ] ];
  3871. };
  3872. EXIF.exifTagTypes = {
  3873. // byte, 8-bit unsigned int:
  3874. 1: {
  3875. getValue: function( dataView, dataOffset ) {
  3876. return dataView.getUint8( dataOffset );
  3877. },
  3878. size: 1
  3879. },
  3880. // ascii, 8-bit byte:
  3881. 2: {
  3882. getValue: function( dataView, dataOffset ) {
  3883. return String.fromCharCode( dataView.getUint8( dataOffset ) );
  3884. },
  3885. size: 1,
  3886. ascii: true
  3887. },
  3888. // short, 16 bit int:
  3889. 3: {
  3890. getValue: function( dataView, dataOffset, littleEndian ) {
  3891. return dataView.getUint16( dataOffset, littleEndian );
  3892. },
  3893. size: 2
  3894. },
  3895. // long, 32 bit int:
  3896. 4: {
  3897. getValue: function( dataView, dataOffset, littleEndian ) {
  3898. return dataView.getUint32( dataOffset, littleEndian );
  3899. },
  3900. size: 4
  3901. },
  3902. // rational = two long values,
  3903. // first is numerator, second is denominator:
  3904. 5: {
  3905. getValue: function( dataView, dataOffset, littleEndian ) {
  3906. return dataView.getUint32( dataOffset, littleEndian ) /
  3907. dataView.getUint32( dataOffset + 4, littleEndian );
  3908. },
  3909. size: 8
  3910. },
  3911. // slong, 32 bit signed int:
  3912. 9: {
  3913. getValue: function( dataView, dataOffset, littleEndian ) {
  3914. return dataView.getInt32( dataOffset, littleEndian );
  3915. },
  3916. size: 4
  3917. },
  3918. // srational, two slongs, first is numerator, second is denominator:
  3919. 10: {
  3920. getValue: function( dataView, dataOffset, littleEndian ) {
  3921. return dataView.getInt32( dataOffset, littleEndian ) /
  3922. dataView.getInt32( dataOffset + 4, littleEndian );
  3923. },
  3924. size: 8
  3925. }
  3926. };
  3927. // undefined, 8-bit byte, value depending on field:
  3928. EXIF.exifTagTypes[ 7 ] = EXIF.exifTagTypes[ 1 ];
  3929. EXIF.getExifValue = function( dataView, tiffOffset, offset, type, length,
  3930. littleEndian ) {
  3931. var tagType = EXIF.exifTagTypes[ type ],
  3932. tagSize, dataOffset, values, i, str, c;
  3933. if ( !tagType ) {
  3934. Base.log('Invalid Exif data: Invalid tag type.');
  3935. return;
  3936. }
  3937. tagSize = tagType.size * length;
  3938. // Determine if the value is contained in the dataOffset bytes,
  3939. // or if the value at the dataOffset is a pointer to the actual data:
  3940. dataOffset = tagSize > 4 ? tiffOffset + dataView.getUint32( offset + 8,
  3941. littleEndian ) : (offset + 8);
  3942. if ( dataOffset + tagSize > dataView.byteLength ) {
  3943. Base.log('Invalid Exif data: Invalid data offset.');
  3944. return;
  3945. }
  3946. if ( length === 1 ) {
  3947. return tagType.getValue( dataView, dataOffset, littleEndian );
  3948. }
  3949. values = [];
  3950. for ( i = 0; i < length; i += 1 ) {
  3951. values[ i ] = tagType.getValue( dataView,
  3952. dataOffset + i * tagType.size, littleEndian );
  3953. }
  3954. if ( tagType.ascii ) {
  3955. str = '';
  3956. // Concatenate the chars:
  3957. for ( i = 0; i < values.length; i += 1 ) {
  3958. c = values[ i ];
  3959. // Ignore the terminating NULL byte(s):
  3960. if ( c === '\u0000' ) {
  3961. break;
  3962. }
  3963. str += c;
  3964. }
  3965. return str;
  3966. }
  3967. return values;
  3968. };
  3969. EXIF.parseExifTag = function( dataView, tiffOffset, offset, littleEndian,
  3970. data ) {
  3971. var tag = dataView.getUint16( offset, littleEndian );
  3972. data.exif[ tag ] = EXIF.getExifValue( dataView, tiffOffset, offset,
  3973. dataView.getUint16( offset + 2, littleEndian ), // tag type
  3974. dataView.getUint32( offset + 4, littleEndian ), // tag length
  3975. littleEndian );
  3976. };
  3977. EXIF.parseExifTags = function( dataView, tiffOffset, dirOffset,
  3978. littleEndian, data ) {
  3979. var tagsNumber, dirEndOffset, i;
  3980. if ( dirOffset + 6 > dataView.byteLength ) {
  3981. Base.log('Invalid Exif data: Invalid directory offset.');
  3982. return;
  3983. }
  3984. tagsNumber = dataView.getUint16( dirOffset, littleEndian );
  3985. dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
  3986. if ( dirEndOffset + 4 > dataView.byteLength ) {
  3987. Base.log('Invalid Exif data: Invalid directory size.');
  3988. return;
  3989. }
  3990. for ( i = 0; i < tagsNumber; i += 1 ) {
  3991. this.parseExifTag( dataView, tiffOffset,
  3992. dirOffset + 2 + 12 * i, // tag offset
  3993. littleEndian, data );
  3994. }
  3995. // Return the offset to the next directory:
  3996. return dataView.getUint32( dirEndOffset, littleEndian );
  3997. };
  3998. // EXIF.getExifThumbnail = function(dataView, offset, length) {
  3999. // var hexData,
  4000. // i,
  4001. // b;
  4002. // if (!length || offset + length > dataView.byteLength) {
  4003. // Base.log('Invalid Exif data: Invalid thumbnail data.');
  4004. // return;
  4005. // }
  4006. // hexData = [];
  4007. // for (i = 0; i < length; i += 1) {
  4008. // b = dataView.getUint8(offset + i);
  4009. // hexData.push((b < 16 ? '0' : '') + b.toString(16));
  4010. // }
  4011. // return 'data:image/jpeg,%' + hexData.join('%');
  4012. // };
  4013. EXIF.parseExifData = function( dataView, offset, length, data ) {
  4014. var tiffOffset = offset + 10,
  4015. littleEndian, dirOffset;
  4016. // Check for the ASCII code for "Exif" (0x45786966):
  4017. if ( dataView.getUint32( offset + 4 ) !== 0x45786966 ) {
  4018. // No Exif data, might be XMP data instead
  4019. return;
  4020. }
  4021. if ( tiffOffset + 8 > dataView.byteLength ) {
  4022. Base.log('Invalid Exif data: Invalid segment size.');
  4023. return;
  4024. }
  4025. // Check for the two null bytes:
  4026. if ( dataView.getUint16( offset + 8 ) !== 0x0000 ) {
  4027. Base.log('Invalid Exif data: Missing byte alignment offset.');
  4028. return;
  4029. }
  4030. // Check the byte alignment:
  4031. switch ( dataView.getUint16( tiffOffset ) ) {
  4032. case 0x4949:
  4033. littleEndian = true;
  4034. break;
  4035. case 0x4D4D:
  4036. littleEndian = false;
  4037. break;
  4038. default:
  4039. Base.log('Invalid Exif data: Invalid byte alignment marker.');
  4040. return;
  4041. }
  4042. // Check for the TIFF tag marker (0x002A):
  4043. if ( dataView.getUint16( tiffOffset + 2, littleEndian ) !== 0x002A ) {
  4044. Base.log('Invalid Exif data: Missing TIFF marker.');
  4045. return;
  4046. }
  4047. // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
  4048. dirOffset = dataView.getUint32( tiffOffset + 4, littleEndian );
  4049. // Create the exif object to store the tags:
  4050. data.exif = new EXIF.ExifMap();
  4051. // Parse the tags of the main image directory and retrieve the
  4052. // offset to the next directory, usually the thumbnail directory:
  4053. dirOffset = EXIF.parseExifTags( dataView, tiffOffset,
  4054. tiffOffset + dirOffset, littleEndian, data );
  4055. // 尝试读取缩略图
  4056. // if ( dirOffset ) {
  4057. // thumbnailData = {exif: {}};
  4058. // dirOffset = EXIF.parseExifTags(
  4059. // dataView,
  4060. // tiffOffset,
  4061. // tiffOffset + dirOffset,
  4062. // littleEndian,
  4063. // thumbnailData
  4064. // );
  4065. // // Check for JPEG Thumbnail offset:
  4066. // if (thumbnailData.exif[0x0201]) {
  4067. // data.exif.Thumbnail = EXIF.getExifThumbnail(
  4068. // dataView,
  4069. // tiffOffset + thumbnailData.exif[0x0201],
  4070. // thumbnailData.exif[0x0202] // Thumbnail data length
  4071. // );
  4072. // }
  4073. // }
  4074. };
  4075. ImageMeta.parsers[ 0xffe1 ].push( EXIF.parseExifData );
  4076. return EXIF;
  4077. });
  4078. /**
  4079. * @fileOverview Image
  4080. */
  4081. define('runtime/html5/image',[
  4082. 'base',
  4083. 'runtime/html5/runtime',
  4084. 'runtime/html5/util'
  4085. ], function( Base, Html5Runtime, Util ) {
  4086. var BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D';
  4087. return Html5Runtime.register( 'Image', {
  4088. // flag: 标记是否被修改过。
  4089. modified: false,
  4090. init: function() {
  4091. var me = this,
  4092. img = new Image();
  4093. img.onload = function() {
  4094. me._info = {
  4095. type: me.type,
  4096. width: this.width,
  4097. height: this.height
  4098. };
  4099. // 读取meta信息。
  4100. if ( !me._metas && 'image/jpeg' === me.type ) {
  4101. Util.parseMeta( me._blob, function( error, ret ) {
  4102. me._metas = ret;
  4103. me.owner.trigger('load');
  4104. });
  4105. } else {
  4106. me.owner.trigger('load');
  4107. }
  4108. };
  4109. img.onerror = function() {
  4110. me.owner.trigger('error');
  4111. };
  4112. me._img = img;
  4113. },
  4114. loadFromBlob: function( blob ) {
  4115. var me = this,
  4116. img = me._img;
  4117. me._blob = blob;
  4118. me.type = blob.type;
  4119. img.src = Util.createObjectURL( blob.getSource() );
  4120. me.owner.once( 'load', function() {
  4121. Util.revokeObjectURL( img.src );
  4122. });
  4123. },
  4124. resize: function( width, height ) {
  4125. var canvas = this._canvas ||
  4126. (this._canvas = document.createElement('canvas'));
  4127. this._resize( this._img, canvas, width, height );
  4128. this._blob = null; // 没用了,可以删掉了。
  4129. this.modified = true;
  4130. this.owner.trigger('complete');
  4131. },
  4132. getAsBlob: function( type ) {
  4133. var blob = this._blob,
  4134. opts = this.options,
  4135. canvas;
  4136. type = type || this.type;
  4137. // blob需要重新生成。
  4138. if ( this.modified || this.type !== type ) {
  4139. canvas = this._canvas;
  4140. if ( type === 'image/jpeg' ) {
  4141. blob = Util.canvasToDataUrl( canvas, 'image/jpeg',
  4142. opts.quality );
  4143. if ( opts.preserveHeaders && this._metas &&
  4144. this._metas.imageHead ) {
  4145. blob = Util.dataURL2ArrayBuffer( blob );
  4146. blob = Util.updateImageHead( blob,
  4147. this._metas.imageHead );
  4148. blob = Util.arrayBufferToBlob( blob, type );
  4149. return blob;
  4150. }
  4151. } else {
  4152. blob = Util.canvasToDataUrl( canvas, type );
  4153. }
  4154. blob = Util.dataURL2Blob( blob );
  4155. }
  4156. return blob;
  4157. },
  4158. getAsDataUrl: function( type ) {
  4159. var opts = this.options;
  4160. type = type || this.type;
  4161. if ( type === 'image/jpeg' ) {
  4162. return Util.canvasToDataUrl( this._canvas, type, opts.quality );
  4163. } else {
  4164. return this._canvas.toDataURL( type );
  4165. }
  4166. },
  4167. getOrientation: function() {
  4168. return this._metas && this._metas.exif &&
  4169. this._metas.exif.get('Orientation') || 1;
  4170. },
  4171. info: function( val ) {
  4172. // setter
  4173. if ( val ) {
  4174. this._info = val;
  4175. return this;
  4176. }
  4177. // getter
  4178. return this._info;
  4179. },
  4180. meta: function( val ) {
  4181. // setter
  4182. if ( val ) {
  4183. this._meta = val;
  4184. return this;
  4185. }
  4186. // getter
  4187. return this._meta;
  4188. },
  4189. destroy: function() {
  4190. var canvas = this._canvas;
  4191. this._img.onload = null;
  4192. if ( canvas ) {
  4193. canvas.getContext('2d')
  4194. .clearRect( 0, 0, canvas.width, canvas.height );
  4195. canvas.width = canvas.height = 0;
  4196. this._canvas = null;
  4197. }
  4198. // 释放内存。非常重要,否则释放不了image的内存。
  4199. this._img.src = BLANK;
  4200. this._img = this._blob = null;
  4201. },
  4202. _resize: function( img, cvs, width, height ) {
  4203. var opts = this.options,
  4204. naturalWidth = img.width,
  4205. naturalHeight = img.height,
  4206. orientation = this.getOrientation(),
  4207. scale, w, h, x, y;
  4208. // values that require 90 degree rotation
  4209. if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) {
  4210. // 交换width, height的值。
  4211. width ^= height;
  4212. height ^= width;
  4213. width ^= height;
  4214. }
  4215. scale = Math[ opts.crop ? 'max' : 'min' ]( width / naturalWidth,
  4216. height / naturalHeight );
  4217. // 不允许放大。
  4218. opts.allowMagnify || (scale = Math.min( 1, scale ));
  4219. w = naturalWidth * scale;
  4220. h = naturalHeight * scale;
  4221. if ( opts.crop ) {
  4222. cvs.width = width;
  4223. cvs.height = height;
  4224. } else {
  4225. cvs.width = w;
  4226. cvs.height = h;
  4227. }
  4228. x = (cvs.width - w) / 2;
  4229. y = (cvs.height - h) / 2;
  4230. opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation );
  4231. this._renderImageToCanvas( cvs, img, x, y, w, h );
  4232. },
  4233. _rotate2Orientaion: function( canvas, orientation ) {
  4234. var width = canvas.width,
  4235. height = canvas.height,
  4236. ctx = canvas.getContext('2d');
  4237. switch ( orientation ) {
  4238. case 5:
  4239. case 6:
  4240. case 7:
  4241. case 8:
  4242. canvas.width = height;
  4243. canvas.height = width;
  4244. break;
  4245. }
  4246. switch ( orientation ) {
  4247. case 2: // horizontal flip
  4248. ctx.translate( width, 0 );
  4249. ctx.scale( -1, 1 );
  4250. break;
  4251. case 3: // 180 rotate left
  4252. ctx.translate( width, height );
  4253. ctx.rotate( Math.PI );
  4254. break;
  4255. case 4: // vertical flip
  4256. ctx.translate( 0, height );
  4257. ctx.scale( 1, -1 );
  4258. break;
  4259. case 5: // vertical flip + 90 rotate right
  4260. ctx.rotate( 0.5 * Math.PI );
  4261. ctx.scale( 1, -1 );
  4262. break;
  4263. case 6: // 90 rotate right
  4264. ctx.rotate( 0.5 * Math.PI );
  4265. ctx.translate( 0, -height );
  4266. break;
  4267. case 7: // horizontal flip + 90 rotate right
  4268. ctx.rotate( 0.5 * Math.PI );
  4269. ctx.translate( width, -height );
  4270. ctx.scale( -1, 1 );
  4271. break;
  4272. case 8: // 90 rotate left
  4273. ctx.rotate( -0.5 * Math.PI );
  4274. ctx.translate( -width, 0 );
  4275. break;
  4276. }
  4277. },
  4278. // https://github.com/stomita/ios-imagefile-megapixel/
  4279. // blob/master/src/megapix-image.js
  4280. _renderImageToCanvas: (function() {
  4281. // 如果不是ios, 不需要这么复杂!
  4282. if ( !Base.os.ios ) {
  4283. return function( canvas, img, x, y, w, h ) {
  4284. canvas.getContext('2d').drawImage( img, x, y, w, h );
  4285. };
  4286. }
  4287. /**
  4288. * Detecting vertical squash in loaded image.
  4289. * Fixes a bug which squash image vertically while drawing into
  4290. * canvas for some images.
  4291. */
  4292. function detectVerticalSquash( img, iw, ih ) {
  4293. var canvas = document.createElement('canvas'),
  4294. ctx = canvas.getContext('2d'),
  4295. sy = 0,
  4296. ey = ih,
  4297. py = ih,
  4298. data, alpha, ratio;
  4299. canvas.width = 1;
  4300. canvas.height = ih;
  4301. ctx.drawImage( img, 0, 0 );
  4302. data = ctx.getImageData( 0, 0, 1, ih ).data;
  4303. // search image edge pixel position in case
  4304. // it is squashed vertically.
  4305. while ( py > sy ) {
  4306. alpha = data[ (py - 1) * 4 + 3 ];
  4307. if ( alpha === 0 ) {
  4308. ey = py;
  4309. } else {
  4310. sy = py;
  4311. }
  4312. py = (ey + sy) >> 1;
  4313. }
  4314. ratio = (py / ih);
  4315. return (ratio === 0) ? 1 : ratio;
  4316. }
  4317. // fix ie7 bug
  4318. // http://stackoverflow.com/questions/11929099/
  4319. // html5-canvas-drawimage-ratio-bug-ios
  4320. if ( Base.os.ios >= 7 ) {
  4321. return function( canvas, img, x, y, w, h ) {
  4322. var iw = img.naturalWidth,
  4323. ih = img.naturalHeight,
  4324. vertSquashRatio = detectVerticalSquash( img, iw, ih );
  4325. return canvas.getContext('2d').drawImage( img, 0, 0,
  4326. iw * vertSquashRatio, ih * vertSquashRatio,
  4327. x, y, w, h );
  4328. };
  4329. }
  4330. /**
  4331. * Detect subsampling in loaded image.
  4332. * In iOS, larger images than 2M pixels may be
  4333. * subsampled in rendering.
  4334. */
  4335. function detectSubsampling( img ) {
  4336. var iw = img.naturalWidth,
  4337. ih = img.naturalHeight,
  4338. canvas, ctx;
  4339. // subsampling may happen overmegapixel image
  4340. if ( iw * ih > 1024 * 1024 ) {
  4341. canvas = document.createElement('canvas');
  4342. canvas.width = canvas.height = 1;
  4343. ctx = canvas.getContext('2d');
  4344. ctx.drawImage( img, -iw + 1, 0 );
  4345. // subsampled image becomes half smaller in rendering size.
  4346. // check alpha channel value to confirm image is covering
  4347. // edge pixel or not. if alpha value is 0
  4348. // image is not covering, hence subsampled.
  4349. return ctx.getImageData( 0, 0, 1, 1 ).data[ 3 ] === 0;
  4350. } else {
  4351. return false;
  4352. }
  4353. }
  4354. return function( canvas, img, x, y, width, height ) {
  4355. var iw = img.naturalWidth,
  4356. ih = img.naturalHeight,
  4357. ctx = canvas.getContext('2d'),
  4358. subsampled = detectSubsampling( img ),
  4359. doSquash = this.type === 'image/jpeg',
  4360. d = 1024,
  4361. sy = 0,
  4362. dy = 0,
  4363. tmpCanvas, tmpCtx, vertSquashRatio, dw, dh, sx, dx;
  4364. if ( subsampled ) {
  4365. iw /= 2;
  4366. ih /= 2;
  4367. }
  4368. ctx.save();
  4369. tmpCanvas = document.createElement('canvas');
  4370. tmpCanvas.width = tmpCanvas.height = d;
  4371. tmpCtx = tmpCanvas.getContext('2d');
  4372. vertSquashRatio = doSquash ?
  4373. detectVerticalSquash( img, iw, ih ) : 1;
  4374. dw = Math.ceil( d * width / iw );
  4375. dh = Math.ceil( d * height / ih / vertSquashRatio );
  4376. while ( sy < ih ) {
  4377. sx = 0;
  4378. dx = 0;
  4379. while ( sx < iw ) {
  4380. tmpCtx.clearRect( 0, 0, d, d );
  4381. tmpCtx.drawImage( img, -sx, -sy );
  4382. ctx.drawImage( tmpCanvas, 0, 0, d, d,
  4383. x + dx, y + dy, dw, dh );
  4384. sx += d;
  4385. dx += dw;
  4386. }
  4387. sy += d;
  4388. dy += dh;
  4389. }
  4390. ctx.restore();
  4391. tmpCanvas = tmpCtx = null;
  4392. };
  4393. })()
  4394. });
  4395. });
  4396. /**
  4397. * @fileOverview Transport
  4398. * @todo 支持chunked传输优势
  4399. * 可以将大文件分成小块挨个传输可以提高大文件成功率当失败的时候也只需要重传那小部分
  4400. * 而不需要重头再传一次另外断点续传也需要用chunked方式
  4401. */
  4402. define('runtime/html5/transport',[
  4403. 'base',
  4404. 'runtime/html5/runtime'
  4405. ], function( Base, Html5Runtime ) {
  4406. var noop = Base.noop,
  4407. $ = Base.$;
  4408. return Html5Runtime.register( 'Transport', {
  4409. init: function() {
  4410. this._status = 0;
  4411. this._response = null;
  4412. },
  4413. send: function() {
  4414. var owner = this.owner,
  4415. opts = this.options,
  4416. xhr = this._initAjax(),
  4417. blob = owner._blob,
  4418. server = opts.server,
  4419. formData, binary, fr;
  4420. if ( opts.sendAsBinary ) {
  4421. server += (/\?/.test( server ) ? '&' : '?') +
  4422. $.param( owner._formData );
  4423. binary = blob.getSource();
  4424. } else {
  4425. formData = new FormData();
  4426. $.each( owner._formData, function( k, v ) {
  4427. formData.append( k, v );
  4428. });
  4429. formData.append( opts.fileVal, blob.getSource(),
  4430. opts.filename || owner._formData.name || '' );
  4431. }
  4432. if ( opts.withCredentials && 'withCredentials' in xhr ) {
  4433. xhr.open( opts.method, server, true );
  4434. xhr.withCredentials = true;
  4435. } else {
  4436. xhr.open( opts.method, server );
  4437. }
  4438. this._setRequestHeader( xhr, opts.headers );
  4439. if ( binary ) {
  4440. xhr.overrideMimeType('application/octet-stream');
  4441. // android直接发送blob会导致服务端接收到的是空文件。
  4442. // bug详情。
  4443. // https://code.google.com/p/android/issues/detail?id=39882
  4444. // 所以先用fileReader读取出来再通过arraybuffer的方式发送。
  4445. if ( Base.os.android ) {
  4446. fr = new FileReader();
  4447. fr.onload = function() {
  4448. xhr.send( this.result );
  4449. fr = fr.onload = null;
  4450. };
  4451. fr.readAsArrayBuffer( binary );
  4452. } else {
  4453. xhr.send( binary );
  4454. }
  4455. } else {
  4456. xhr.send( formData );
  4457. }
  4458. },
  4459. getResponse: function() {
  4460. return this._response;
  4461. },
  4462. getResponseAsJson: function() {
  4463. return this._parseJson( this._response );
  4464. },
  4465. getStatus: function() {
  4466. return this._status;
  4467. },
  4468. abort: function() {
  4469. var xhr = this._xhr;
  4470. if ( xhr ) {
  4471. xhr.upload.onprogress = noop;
  4472. xhr.onreadystatechange = noop;
  4473. xhr.abort();
  4474. this._xhr = xhr = null;
  4475. }
  4476. },
  4477. destroy: function() {
  4478. this.abort();
  4479. },
  4480. _initAjax: function() {
  4481. var me = this,
  4482. xhr = new XMLHttpRequest(),
  4483. opts = this.options;
  4484. if ( opts.withCredentials && !('withCredentials' in xhr) &&
  4485. typeof XDomainRequest !== 'undefined' ) {
  4486. xhr = new XDomainRequest();
  4487. }
  4488. xhr.upload.onprogress = function( e ) {
  4489. var percentage = 0;
  4490. if ( e.lengthComputable ) {
  4491. percentage = e.loaded / e.total;
  4492. }
  4493. return me.trigger( 'progress', percentage );
  4494. };
  4495. xhr.onreadystatechange = function() {
  4496. if ( xhr.readyState !== 4 ) {
  4497. return;
  4498. }
  4499. xhr.upload.onprogress = noop;
  4500. xhr.onreadystatechange = noop;
  4501. me._xhr = null;
  4502. me._status = xhr.status;
  4503. if ( xhr.status >= 200 && xhr.status < 300 ) {
  4504. me._response = xhr.responseText;
  4505. return me.trigger('load');
  4506. } else if ( xhr.status >= 500 && xhr.status < 600 ) {
  4507. me._response = xhr.responseText;
  4508. return me.trigger( 'error', 'server' );
  4509. }
  4510. return me.trigger( 'error', me._status ? 'http' : 'abort' );
  4511. };
  4512. me._xhr = xhr;
  4513. return xhr;
  4514. },
  4515. _setRequestHeader: function( xhr, headers ) {
  4516. $.each( headers, function( key, val ) {
  4517. xhr.setRequestHeader( key, val );
  4518. });
  4519. },
  4520. _parseJson: function( str ) {
  4521. var json;
  4522. try {
  4523. json = JSON.parse( str );
  4524. } catch ( ex ) {
  4525. json = {};
  4526. }
  4527. return json;
  4528. }
  4529. });
  4530. });
  4531. /**
  4532. * @fileOverview 只有html5实现的文件版本
  4533. */
  4534. define('preset/html5only',[
  4535. 'base',
  4536. // widgets
  4537. 'widgets/filednd',
  4538. 'widgets/filepaste',
  4539. 'widgets/filepicker',
  4540. 'widgets/image',
  4541. 'widgets/queue',
  4542. 'widgets/runtime',
  4543. 'widgets/upload',
  4544. 'widgets/validator',
  4545. // runtimes
  4546. // html5
  4547. 'runtime/html5/blob',
  4548. 'runtime/html5/dnd',
  4549. 'runtime/html5/filepaste',
  4550. 'runtime/html5/filepicker',
  4551. 'runtime/html5/imagemeta/exif',
  4552. 'runtime/html5/image',
  4553. 'runtime/html5/transport'
  4554. ], function( Base ) {
  4555. return Base;
  4556. });
  4557. define('webuploader',[
  4558. 'preset/html5only'
  4559. ], function( preset ) {
  4560. return preset;
  4561. });
  4562. return require('webuploader');
  4563. });