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.

5670 lines
194 KiB

8 years ago
  1. /*! WebUploader 0.1.2 */
  2. /**
  3. * @fileOverview 让内部各个部件的代码可以用[amd](https://github.com/amdjs/amdjs-api/wiki/AMD)模块定义方式组织起来。
  4. *
  5. * AMD API 内部的简单不完全实现请忽略只有当WebUploader被合并成一个文件的时候才会引入
  6. */
  7. (function( root, factory ) {
  8. var modules = {},
  9. // 内部require, 简单不完全实现。
  10. // https://github.com/amdjs/amdjs-api/wiki/require
  11. _require = function( deps, callback ) {
  12. var args, len, i;
  13. // 如果deps不是数组,则直接返回指定module
  14. if ( typeof deps === 'string' ) {
  15. return getModule( deps );
  16. } else {
  17. args = [];
  18. for( len = deps.length, i = 0; i < len; i++ ) {
  19. args.push( getModule( deps[ i ] ) );
  20. }
  21. return callback.apply( null, args );
  22. }
  23. },
  24. // 内部define,暂时不支持不指定id.
  25. _define = function( id, deps, factory ) {
  26. if ( arguments.length === 2 ) {
  27. factory = deps;
  28. deps = null;
  29. }
  30. _require( deps || [], function() {
  31. setModule( id, factory, arguments );
  32. });
  33. },
  34. // 设置module, 兼容CommonJs写法。
  35. setModule = function( id, factory, args ) {
  36. var module = {
  37. exports: factory
  38. },
  39. returned;
  40. if ( typeof factory === 'function' ) {
  41. args.length || (args = [ _require, module.exports, module ]);
  42. returned = factory.apply( null, args );
  43. returned !== undefined && (module.exports = returned);
  44. }
  45. modules[ id ] = module.exports;
  46. },
  47. // 根据id获取module
  48. getModule = function( id ) {
  49. var module = modules[ id ] || root[ id ];
  50. if ( !module ) {
  51. throw new Error( '`' + id + '` is undefined' );
  52. }
  53. return module;
  54. },
  55. // 将所有modules,将路径ids装换成对象。
  56. exportsTo = function( obj ) {
  57. var key, host, parts, part, last, ucFirst;
  58. // make the first character upper case.
  59. ucFirst = function( str ) {
  60. return str && (str.charAt( 0 ).toUpperCase() + str.substr( 1 ));
  61. };
  62. for ( key in modules ) {
  63. host = obj;
  64. if ( !modules.hasOwnProperty( key ) ) {
  65. continue;
  66. }
  67. parts = key.split('/');
  68. last = ucFirst( parts.pop() );
  69. while( (part = ucFirst( parts.shift() )) ) {
  70. host[ part ] = host[ part ] || {};
  71. host = host[ part ];
  72. }
  73. host[ last ] = modules[ key ];
  74. }
  75. },
  76. exports = factory( root, _define, _require ),
  77. origin;
  78. // exports every module.
  79. exportsTo( exports );
  80. if ( typeof module === 'object' && typeof module.exports === 'object' ) {
  81. // For CommonJS and CommonJS-like environments where a proper window is present,
  82. module.exports = exports;
  83. } else if ( typeof define === 'function' && define.amd ) {
  84. // Allow using this built library as an AMD module
  85. // in another project. That other project will only
  86. // see this AMD call, not the internal modules in
  87. // the closure below.
  88. define([], exports );
  89. } else {
  90. // Browser globals case. Just assign the
  91. // result to a property on the global.
  92. origin = root.WebUploader;
  93. root.WebUploader = exports;
  94. root.WebUploader.noConflict = function() {
  95. root.WebUploader = origin;
  96. };
  97. }
  98. })( this, function( window, define, require ) {
  99. /**
  100. * @fileOverview jQuery or Zepto
  101. */
  102. define('dollar-third',[],function() {
  103. return window.jQuery || window.Zepto;
  104. });
  105. /**
  106. * @fileOverview Dom 操作相关
  107. */
  108. define('dollar',[
  109. 'dollar-third'
  110. ], function( _ ) {
  111. return _;
  112. });
  113. /**
  114. * @fileOverview 使用jQuery的Promise
  115. */
  116. define('promise-third',[
  117. 'dollar'
  118. ], function( $ ) {
  119. return {
  120. Deferred: $.Deferred,
  121. when: $.when,
  122. isPromise: function( anything ) {
  123. return anything && typeof anything.then === 'function';
  124. }
  125. };
  126. });
  127. /**
  128. * @fileOverview Promise/A+
  129. */
  130. define('promise',[
  131. 'promise-third'
  132. ], function( _ ) {
  133. return _;
  134. });
  135. /**
  136. * @fileOverview 基础类方法
  137. */
  138. /**
  139. * Web Uploader内部类的详细说明以下提及的功能类都可以在`WebUploader`这个变量中访问到
  140. *
  141. * As you know, Web Uploader的每个文件都是用过[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD)规范中的`define`组织起来的, 每个Module都会有个module id.
  142. * 默认module id该文件的路径而此路径将会转化成名字空间存放在WebUploader中
  143. *
  144. * * module `base`WebUploader.Base
  145. * * module `file`: WebUploader.File
  146. * * module `lib/dnd`: WebUploader.Lib.Dnd
  147. * * module `runtime/html5/dnd`: WebUploader.Runtime.Html5.Dnd
  148. *
  149. *
  150. * 以下文档将可能省略`WebUploader`前缀
  151. * @module WebUploader
  152. * @title WebUploader API文档
  153. */
  154. define('base',[
  155. 'dollar',
  156. 'promise'
  157. ], function( $, promise ) {
  158. var noop = function() {},
  159. call = Function.call;
  160. // http://jsperf.com/uncurrythis
  161. // 反科里化
  162. function uncurryThis( fn ) {
  163. return function() {
  164. return call.apply( fn, arguments );
  165. };
  166. }
  167. function bindFn( fn, context ) {
  168. return function() {
  169. return fn.apply( context, arguments );
  170. };
  171. }
  172. function createObject( proto ) {
  173. var f;
  174. if ( Object.create ) {
  175. return Object.create( proto );
  176. } else {
  177. f = function() {};
  178. f.prototype = proto;
  179. return new f();
  180. }
  181. }
  182. /**
  183. * 基础类提供一些简单常用的方法
  184. * @class Base
  185. */
  186. return {
  187. /**
  188. * @property {String} version 当前版本号
  189. */
  190. version: '0.1.2',
  191. /**
  192. * @property {jQuery|Zepto} $ 引用依赖的jQuery或者Zepto对象
  193. */
  194. $: $,
  195. Deferred: promise.Deferred,
  196. isPromise: promise.isPromise,
  197. when: promise.when,
  198. /**
  199. * @description 简单的浏览器检查结果
  200. *
  201. * * `webkit` webkit版本号如果浏览器为非webkit内核此属性为`undefined`
  202. * * `chrome` chrome浏览器版本号如果浏览器为chrome此属性为`undefined`
  203. * * `ie` ie浏览器版本号如果浏览器为非ie此属性为`undefined`**暂不支持ie10+**
  204. * * `firefox` firefox浏览器版本号如果浏览器为非firefox此属性为`undefined`
  205. * * `safari` safari浏览器版本号如果浏览器为非safari此属性为`undefined`
  206. * * `opera` opera浏览器版本号如果浏览器为非opera此属性为`undefined`
  207. *
  208. * @property {Object} [browser]
  209. */
  210. browser: (function( ua ) {
  211. var ret = {},
  212. webkit = ua.match( /WebKit\/([\d.]+)/ ),
  213. chrome = ua.match( /Chrome\/([\d.]+)/ ) ||
  214. ua.match( /CriOS\/([\d.]+)/ ),
  215. ie = ua.match( /MSIE\s([\d\.]+)/ ) ||
  216. ua.match(/(?:trident)(?:.*rv:([\w.]+))?/i),
  217. firefox = ua.match( /Firefox\/([\d.]+)/ ),
  218. safari = ua.match( /Safari\/([\d.]+)/ ),
  219. opera = ua.match( /OPR\/([\d.]+)/ );
  220. webkit && (ret.webkit = parseFloat( webkit[ 1 ] ));
  221. chrome && (ret.chrome = parseFloat( chrome[ 1 ] ));
  222. ie && (ret.ie = parseFloat( ie[ 1 ] ));
  223. firefox && (ret.firefox = parseFloat( firefox[ 1 ] ));
  224. safari && (ret.safari = parseFloat( safari[ 1 ] ));
  225. opera && (ret.opera = parseFloat( opera[ 1 ] ));
  226. return ret;
  227. })( navigator.userAgent ),
  228. /**
  229. * @description 操作系统检查结果
  230. *
  231. * * `android` 如果在android浏览器环境下此值为对应的android版本号否则为`undefined`
  232. * * `ios` 如果在ios浏览器环境下此值为对应的ios版本号否则为`undefined`
  233. * @property {Object} [os]
  234. */
  235. os: (function( ua ) {
  236. var ret = {},
  237. // osx = !!ua.match( /\(Macintosh\; Intel / ),
  238. android = ua.match( /(?:Android);?[\s\/]+([\d.]+)?/ ),
  239. ios = ua.match( /(?:iPad|iPod|iPhone).*OS\s([\d_]+)/ );
  240. // osx && (ret.osx = true);
  241. android && (ret.android = parseFloat( android[ 1 ] ));
  242. ios && (ret.ios = parseFloat( ios[ 1 ].replace( /_/g, '.' ) ));
  243. return ret;
  244. })( navigator.userAgent ),
  245. /**
  246. * 实现类与类之间的继承
  247. * @method inherits
  248. * @grammar Base.inherits( super ) => child
  249. * @grammar Base.inherits( super, protos ) => child
  250. * @grammar Base.inherits( super, protos, statics ) => child
  251. * @param {Class} super 父类
  252. * @param {Object | Function} [protos] 子类或者对象如果对象中包含constructor子类将是用此属性值
  253. * @param {Function} [protos.constructor] 子类构造器不指定的话将创建个临时的直接执行父类构造器的方法
  254. * @param {Object} [statics] 静态属性或方法
  255. * @return {Class} 返回子类
  256. * @example
  257. * function Person() {
  258. * console.log( 'Super' );
  259. * }
  260. * Person.prototype.hello = function() {
  261. * console.log( 'hello' );
  262. * };
  263. *
  264. * var Manager = Base.inherits( Person, {
  265. * world: function() {
  266. * console.log( 'World' );
  267. * }
  268. * });
  269. *
  270. * // 因为没有指定构造器,父类的构造器将会执行。
  271. * var instance = new Manager(); // => Super
  272. *
  273. * // 继承子父类的方法
  274. * instance.hello(); // => hello
  275. * instance.world(); // => World
  276. *
  277. * // 子类的__super__属性指向父类
  278. * console.log( Manager.__super__ === Person ); // => true
  279. */
  280. inherits: function( Super, protos, staticProtos ) {
  281. var child;
  282. if ( typeof protos === 'function' ) {
  283. child = protos;
  284. protos = null;
  285. } else if ( protos && protos.hasOwnProperty('constructor') ) {
  286. child = protos.constructor;
  287. } else {
  288. child = function() {
  289. return Super.apply( this, arguments );
  290. };
  291. }
  292. // 复制静态方法
  293. $.extend( true, child, Super, staticProtos || {} );
  294. /* jshint camelcase: false */
  295. // 让子类的__super__属性指向父类。
  296. child.__super__ = Super.prototype;
  297. // 构建原型,添加原型方法或属性。
  298. // 暂时用Object.create实现。
  299. child.prototype = createObject( Super.prototype );
  300. protos && $.extend( true, child.prototype, protos );
  301. return child;
  302. },
  303. /**
  304. * 一个不做任何事情的方法可以用来赋值给默认的callback.
  305. * @method noop
  306. */
  307. noop: noop,
  308. /**
  309. * 返回一个新的方法此方法将已指定的`context`来执行
  310. * @grammar Base.bindFn( fn, context ) => Function
  311. * @method bindFn
  312. * @example
  313. * var doSomething = function() {
  314. * console.log( this.name );
  315. * },
  316. * obj = {
  317. * name: 'Object Name'
  318. * },
  319. * aliasFn = Base.bind( doSomething, obj );
  320. *
  321. * aliasFn(); // => Object Name
  322. *
  323. */
  324. bindFn: bindFn,
  325. /**
  326. * 引用Console.log如果存在的话否则引用一个[空函数loop](#WebUploader:Base.log)
  327. * @grammar Base.log( args... ) => undefined
  328. * @method log
  329. */
  330. log: (function() {
  331. if ( window.console ) {
  332. return bindFn( console.log, console );
  333. }
  334. return noop;
  335. })(),
  336. nextTick: (function() {
  337. return function( cb ) {
  338. setTimeout( cb, 1 );
  339. };
  340. // @bug 当浏览器不在当前窗口时就停了。
  341. // var next = window.requestAnimationFrame ||
  342. // window.webkitRequestAnimationFrame ||
  343. // window.mozRequestAnimationFrame ||
  344. // function( cb ) {
  345. // window.setTimeout( cb, 1000 / 60 );
  346. // };
  347. // // fix: Uncaught TypeError: Illegal invocation
  348. // return bindFn( next, window );
  349. })(),
  350. /**
  351. * [uncurrythis](http://www.2ality.com/2011/11/uncurrying-this.html)的数组slice方法。
  352. * 将用来将非数组对象转化成数组对象
  353. * @grammar Base.slice( target, start[, end] ) => Array
  354. * @method slice
  355. * @example
  356. * function doSomthing() {
  357. * var args = Base.slice( arguments, 1 );
  358. * console.log( args );
  359. * }
  360. *
  361. * doSomthing( 'ignored', 'arg2', 'arg3' ); // => Array ["arg2", "arg3"]
  362. */
  363. slice: uncurryThis( [].slice ),
  364. /**
  365. * 生成唯一的ID
  366. * @method guid
  367. * @grammar Base.guid() => String
  368. * @grammar Base.guid( prefx ) => String
  369. */
  370. guid: (function() {
  371. var counter = 0;
  372. return function( prefix ) {
  373. var guid = (+new Date()).toString( 32 ),
  374. i = 0;
  375. for ( ; i < 5; i++ ) {
  376. guid += Math.floor( Math.random() * 65535 ).toString( 32 );
  377. }
  378. return (prefix || 'wu_') + guid + (counter++).toString( 32 );
  379. };
  380. })(),
  381. /**
  382. * 格式化文件大小, 输出成带单位的字符串
  383. * @method formatSize
  384. * @grammar Base.formatSize( size ) => String
  385. * @grammar Base.formatSize( size, pointLength ) => String
  386. * @grammar Base.formatSize( size, pointLength, units ) => String
  387. * @param {Number} size 文件大小
  388. * @param {Number} [pointLength=2] 精确到的小数点数
  389. * @param {Array} [units=[ 'B', 'K', 'M', 'G', 'TB' ]] 单位数组从字节到千字节一直往上指定如果单位数组里面只指定了到了K(千字节)同时文件大小大于M, 此方法的输出将还是显示成多少K.
  390. * @example
  391. * console.log( Base.formatSize( 100 ) ); // => 100B
  392. * console.log( Base.formatSize( 1024 ) ); // => 1.00K
  393. * console.log( Base.formatSize( 1024, 0 ) ); // => 1K
  394. * console.log( Base.formatSize( 1024 * 1024 ) ); // => 1.00M
  395. * console.log( Base.formatSize( 1024 * 1024 * 1024 ) ); // => 1.00G
  396. * console.log( Base.formatSize( 1024 * 1024 * 1024, 0, ['B', 'KB', 'MB'] ) ); // => 1024MB
  397. */
  398. formatSize: function( size, pointLength, units ) {
  399. var unit;
  400. units = units || [ 'B', 'K', 'M', 'G', 'TB' ];
  401. while ( (unit = units.shift()) && size > 1024 ) {
  402. size = size / 1024;
  403. }
  404. return (unit === 'B' ? size : size.toFixed( pointLength || 2 )) +
  405. unit;
  406. }
  407. };
  408. });
  409. /**
  410. * 事件处理类可以独立使用也可以扩展给对象使用
  411. * @fileOverview Mediator
  412. */
  413. define('mediator',[
  414. 'base'
  415. ], function( Base ) {
  416. var $ = Base.$,
  417. slice = [].slice,
  418. separator = /\s+/,
  419. protos;
  420. // 根据条件过滤出事件handlers.
  421. function findHandlers( arr, name, callback, context ) {
  422. return $.grep( arr, function( handler ) {
  423. return handler &&
  424. (!name || handler.e === name) &&
  425. (!callback || handler.cb === callback ||
  426. handler.cb._cb === callback) &&
  427. (!context || handler.ctx === context);
  428. });
  429. }
  430. function eachEvent( events, callback, iterator ) {
  431. // 不支持对象,只支持多个event用空格隔开
  432. $.each( (events || '').split( separator ), function( _, key ) {
  433. iterator( key, callback );
  434. });
  435. }
  436. function triggerHanders( events, args ) {
  437. var stoped = false,
  438. i = -1,
  439. len = events.length,
  440. handler;
  441. while ( ++i < len ) {
  442. handler = events[ i ];
  443. if ( handler.cb.apply( handler.ctx2, args ) === false ) {
  444. stoped = true;
  445. break;
  446. }
  447. }
  448. return !stoped;
  449. }
  450. protos = {
  451. /**
  452. * 绑定事件
  453. *
  454. * `callback`方法在执行时arguments将会来源于trigger的时候携带的参数
  455. * ```javascript
  456. * var obj = {};
  457. *
  458. * // 使得obj有事件行为
  459. * Mediator.installTo( obj );
  460. *
  461. * obj.on( 'testa', function( arg1, arg2 ) {
  462. * console.log( arg1, arg2 ); // => 'arg1', 'arg2'
  463. * });
  464. *
  465. * obj.trigger( 'testa', 'arg1', 'arg2' );
  466. * ```
  467. *
  468. * 如果`callback`某一个方法`return false`则后续的其他`callback`都不会被执行到
  469. * 切会影响到`trigger`方法的返回值`false`
  470. *
  471. * `on`还可以用来添加一个特殊事件`all`, 这样所有的事件触发都会响应到同时此类`callback`中的arguments有一个不同处
  472. * 就是第一个参数为`type`记录当前是什么事件在触发此类`callback`的优先级比脚低会再正常`callback`执行完后触发
  473. * ```javascript
  474. * obj.on( 'all', function( type, arg1, arg2 ) {
  475. * console.log( type, arg1, arg2 ); // => 'testa', 'arg1', 'arg2'
  476. * });
  477. * ```
  478. *
  479. * @method on
  480. * @grammar on( name, callback[, context] ) => self
  481. * @param {String} name 事件名支持多个事件用空格隔开
  482. * @param {Function} callback 事件处理器
  483. * @param {Object} [context] 事件处理器的上下文
  484. * @return {self} 返回自身方便链式
  485. * @chainable
  486. * @class Mediator
  487. */
  488. on: function( name, callback, context ) {
  489. var me = this,
  490. set;
  491. if ( !callback ) {
  492. return this;
  493. }
  494. set = this._events || (this._events = []);
  495. eachEvent( name, callback, function( name, callback ) {
  496. var handler = { e: name };
  497. handler.cb = callback;
  498. handler.ctx = context;
  499. handler.ctx2 = context || me;
  500. handler.id = set.length;
  501. set.push( handler );
  502. });
  503. return this;
  504. },
  505. /**
  506. * 绑定事件且当handler执行完后自动解除绑定
  507. * @method once
  508. * @grammar once( name, callback[, context] ) => self
  509. * @param {String} name 事件名
  510. * @param {Function} callback 事件处理器
  511. * @param {Object} [context] 事件处理器的上下文
  512. * @return {self} 返回自身方便链式
  513. * @chainable
  514. */
  515. once: function( name, callback, context ) {
  516. var me = this;
  517. if ( !callback ) {
  518. return me;
  519. }
  520. eachEvent( name, callback, function( name, callback ) {
  521. var once = function() {
  522. me.off( name, once );
  523. return callback.apply( context || me, arguments );
  524. };
  525. once._cb = callback;
  526. me.on( name, once, context );
  527. });
  528. return me;
  529. },
  530. /**
  531. * 解除事件绑定
  532. * @method off
  533. * @grammar off( [name[, callback[, context] ] ] ) => self
  534. * @param {String} [name] 事件名
  535. * @param {Function} [callback] 事件处理器
  536. * @param {Object} [context] 事件处理器的上下文
  537. * @return {self} 返回自身方便链式
  538. * @chainable
  539. */
  540. off: function( name, cb, ctx ) {
  541. var events = this._events;
  542. if ( !events ) {
  543. return this;
  544. }
  545. if ( !name && !cb && !ctx ) {
  546. this._events = [];
  547. return this;
  548. }
  549. eachEvent( name, cb, function( name, cb ) {
  550. $.each( findHandlers( events, name, cb, ctx ), function() {
  551. delete events[ this.id ];
  552. });
  553. });
  554. return this;
  555. },
  556. /**
  557. * 触发事件
  558. * @method trigger
  559. * @grammar trigger( name[, args...] ) => self
  560. * @param {String} type 事件名
  561. * @param {*} [...] 任意参数
  562. * @return {Boolean} 如果handler中return false了则返回false, 否则返回true
  563. */
  564. trigger: function( type ) {
  565. var args, events, allEvents;
  566. if ( !this._events || !type ) {
  567. return this;
  568. }
  569. args = slice.call( arguments, 1 );
  570. events = findHandlers( this._events, type );
  571. allEvents = findHandlers( this._events, 'all' );
  572. return triggerHanders( events, args ) &&
  573. triggerHanders( allEvents, arguments );
  574. }
  575. };
  576. /**
  577. * 中介者它本身是个单例但可以通过[installTo](#WebUploader:Mediator:installTo)方法使任何对象具备事件行为
  578. * 主要目的是负责模块与模块之间的合作降低耦合度
  579. *
  580. * @class Mediator
  581. */
  582. return $.extend({
  583. /**
  584. * 可以通过这个接口使任何对象具备事件功能
  585. * @method installTo
  586. * @param {Object} obj 需要具备事件行为的对象
  587. * @return {Object} 返回obj.
  588. */
  589. installTo: function( obj ) {
  590. return $.extend( obj, protos );
  591. }
  592. }, protos );
  593. });
  594. /**
  595. * @fileOverview Uploader上传类
  596. */
  597. define('uploader',[
  598. 'base',
  599. 'mediator'
  600. ], function( Base, Mediator ) {
  601. var $ = Base.$;
  602. /**
  603. * 上传入口类
  604. * @class Uploader
  605. * @constructor
  606. * @grammar new Uploader( opts ) => Uploader
  607. * @example
  608. * var uploader = WebUploader.Uploader({
  609. * swf: 'path_of_swf/Uploader.swf',
  610. *
  611. * // 开起分片上传。
  612. * chunked: true
  613. * });
  614. */
  615. function Uploader( opts ) {
  616. this.options = $.extend( true, {}, Uploader.options, opts );
  617. this._init( this.options );
  618. }
  619. // default Options
  620. // widgets中有相应扩展
  621. Uploader.options = {};
  622. Mediator.installTo( Uploader.prototype );
  623. // 批量添加纯命令式方法。
  624. $.each({
  625. upload: 'start-upload',
  626. stop: 'stop-upload',
  627. getFile: 'get-file',
  628. getFiles: 'get-files',
  629. addFile: 'add-file',
  630. addFiles: 'add-file',
  631. sort: 'sort-files',
  632. removeFile: 'remove-file',
  633. skipFile: 'skip-file',
  634. retry: 'retry',
  635. isInProgress: 'is-in-progress',
  636. makeThumb: 'make-thumb',
  637. getDimension: 'get-dimension',
  638. addButton: 'add-btn',
  639. getRuntimeType: 'get-runtime-type',
  640. refresh: 'refresh',
  641. disable: 'disable',
  642. enable: 'enable',
  643. reset: 'reset'
  644. }, function( fn, command ) {
  645. Uploader.prototype[ fn ] = function() {
  646. return this.request( command, arguments );
  647. };
  648. });
  649. $.extend( Uploader.prototype, {
  650. state: 'pending',
  651. _init: function( opts ) {
  652. var me = this;
  653. me.request( 'init', opts, function() {
  654. me.state = 'ready';
  655. me.trigger('ready');
  656. });
  657. },
  658. /**
  659. * 获取或者设置Uploader配置项
  660. * @method option
  661. * @grammar option( key ) => *
  662. * @grammar option( key, val ) => self
  663. * @example
  664. *
  665. * // 初始状态图片上传前不会压缩
  666. * var uploader = new WebUploader.Uploader({
  667. * resize: null;
  668. * });
  669. *
  670. * // 修改后图片上传前,尝试将图片压缩到1600 * 1600
  671. * uploader.options( 'resize', {
  672. * width: 1600,
  673. * height: 1600
  674. * });
  675. */
  676. option: function( key, val ) {
  677. var opts = this.options;
  678. // setter
  679. if ( arguments.length > 1 ) {
  680. if ( $.isPlainObject( val ) &&
  681. $.isPlainObject( opts[ key ] ) ) {
  682. $.extend( opts[ key ], val );
  683. } else {
  684. opts[ key ] = val;
  685. }
  686. } else { // getter
  687. return key ? opts[ key ] : opts;
  688. }
  689. },
  690. /**
  691. * 获取文件统计信息返回一个包含一下信息的对象
  692. * * `successNum` 上传成功的文件数
  693. * * `uploadFailNum` 上传失败的文件数
  694. * * `cancelNum` 被删除的文件数
  695. * * `invalidNum` 无效的文件数
  696. * * `queueNum` 还在队列中的文件数
  697. * @method getStats
  698. * @grammar getStats() => Object
  699. */
  700. getStats: function() {
  701. // return this._mgr.getStats.apply( this._mgr, arguments );
  702. var stats = this.request('get-stats');
  703. return {
  704. successNum: stats.numOfSuccess,
  705. // who care?
  706. // queueFailNum: 0,
  707. cancelNum: stats.numOfCancel,
  708. invalidNum: stats.numOfInvalid,
  709. uploadFailNum: stats.numOfUploadFailed,
  710. queueNum: stats.numOfQueue
  711. };
  712. },
  713. // 需要重写此方法来来支持opts.onEvent和instance.onEvent的处理器
  714. trigger: function( type/*, args...*/ ) {
  715. var args = [].slice.call( arguments, 1 ),
  716. opts = this.options,
  717. name = 'on' + type.substring( 0, 1 ).toUpperCase() +
  718. type.substring( 1 );
  719. if (
  720. // 调用通过on方法注册的handler.
  721. Mediator.trigger.apply( this, arguments ) === false ||
  722. // 调用opts.onEvent
  723. $.isFunction( opts[ name ] ) &&
  724. opts[ name ].apply( this, args ) === false ||
  725. // 调用this.onEvent
  726. $.isFunction( this[ name ] ) &&
  727. this[ name ].apply( this, args ) === false ||
  728. // 广播所有uploader的事件。
  729. Mediator.trigger.apply( Mediator,
  730. [ this, type ].concat( args ) ) === false ) {
  731. return false;
  732. }
  733. return true;
  734. },
  735. // widgets/widget.js将补充此方法的详细文档。
  736. request: Base.noop
  737. });
  738. /**
  739. * 创建Uploader实例等同于new Uploader( opts );
  740. * @method create
  741. * @class Base
  742. * @static
  743. * @grammar Base.create( opts ) => Uploader
  744. */
  745. Base.create = Uploader.create = function( opts ) {
  746. return new Uploader( opts );
  747. };
  748. // 暴露Uploader,可以通过它来扩展业务逻辑。
  749. Base.Uploader = Uploader;
  750. return Uploader;
  751. });
  752. /**
  753. * @fileOverview Runtime管理器负责Runtime的选择, 连接
  754. */
  755. define('runtime/runtime',[
  756. 'base',
  757. 'mediator'
  758. ], function( Base, Mediator ) {
  759. var $ = Base.$,
  760. factories = {},
  761. // 获取对象的第一个key
  762. getFirstKey = function( obj ) {
  763. for ( var key in obj ) {
  764. if ( obj.hasOwnProperty( key ) ) {
  765. return key;
  766. }
  767. }
  768. return null;
  769. };
  770. // 接口类。
  771. function Runtime( options ) {
  772. this.options = $.extend({
  773. container: document.body
  774. }, options );
  775. this.uid = Base.guid('rt_');
  776. }
  777. $.extend( Runtime.prototype, {
  778. getContainer: function() {
  779. var opts = this.options,
  780. parent, container;
  781. if ( this._container ) {
  782. return this._container;
  783. }
  784. parent = $( opts.container || document.body );
  785. container = $( document.createElement('div') );
  786. container.attr( 'id', 'rt_' + this.uid );
  787. container.css({
  788. position: 'absolute',
  789. top: '0px',
  790. left: '0px',
  791. width: '1px',
  792. height: '1px',
  793. overflow: 'hidden'
  794. });
  795. parent.append( container );
  796. parent.addClass('webuploader-container');
  797. this._container = container;
  798. return container;
  799. },
  800. init: Base.noop,
  801. exec: Base.noop,
  802. destroy: function() {
  803. if ( this._container ) {
  804. this._container.parentNode.removeChild( this.__container );
  805. }
  806. this.off();
  807. }
  808. });
  809. Runtime.orders = 'html5,flash';
  810. /**
  811. * 添加Runtime实现
  812. * @param {String} type 类型
  813. * @param {Runtime} factory 具体Runtime实现
  814. */
  815. Runtime.addRuntime = function( type, factory ) {
  816. factories[ type ] = factory;
  817. };
  818. Runtime.hasRuntime = function( type ) {
  819. return !!(type ? factories[ type ] : getFirstKey( factories ));
  820. };
  821. Runtime.create = function( opts, orders ) {
  822. var type, runtime;
  823. orders = orders || Runtime.orders;
  824. $.each( orders.split( /\s*,\s*/g ), function() {
  825. if ( factories[ this ] ) {
  826. type = this;
  827. return false;
  828. }
  829. });
  830. type = type || getFirstKey( factories );
  831. if ( !type ) {
  832. throw new Error('Runtime Error');
  833. }
  834. runtime = new factories[ type ]( opts );
  835. return runtime;
  836. };
  837. Mediator.installTo( Runtime.prototype );
  838. return Runtime;
  839. });
  840. /**
  841. * @fileOverview Runtime管理器负责Runtime的选择, 连接
  842. */
  843. define('runtime/client',[
  844. 'base',
  845. 'mediator',
  846. 'runtime/runtime'
  847. ], function( Base, Mediator, Runtime ) {
  848. var cache;
  849. cache = (function() {
  850. var obj = {};
  851. return {
  852. add: function( runtime ) {
  853. obj[ runtime.uid ] = runtime;
  854. },
  855. get: function( ruid, standalone ) {
  856. var i;
  857. if ( ruid ) {
  858. return obj[ ruid ];
  859. }
  860. for ( i in obj ) {
  861. // 有些类型不能重用,比如filepicker.
  862. if ( standalone && obj[ i ].__standalone ) {
  863. continue;
  864. }
  865. return obj[ i ];
  866. }
  867. return null;
  868. },
  869. remove: function( runtime ) {
  870. delete obj[ runtime.uid ];
  871. }
  872. };
  873. })();
  874. function RuntimeClient( component, standalone ) {
  875. var deferred = Base.Deferred(),
  876. runtime;
  877. this.uid = Base.guid('client_');
  878. // 允许runtime没有初始化之前,注册一些方法在初始化后执行。
  879. this.runtimeReady = function( cb ) {
  880. return deferred.done( cb );
  881. };
  882. this.connectRuntime = function( opts, cb ) {
  883. // already connected.
  884. if ( runtime ) {
  885. throw new Error('already connected!');
  886. }
  887. deferred.done( cb );
  888. if ( typeof opts === 'string' && cache.get( opts ) ) {
  889. runtime = cache.get( opts );
  890. }
  891. // 像filePicker只能独立存在,不能公用。
  892. runtime = runtime || cache.get( null, standalone );
  893. // 需要创建
  894. if ( !runtime ) {
  895. runtime = Runtime.create( opts, opts.runtimeOrder );
  896. runtime.__promise = deferred.promise();
  897. runtime.once( 'ready', deferred.resolve );
  898. runtime.init();
  899. cache.add( runtime );
  900. runtime.__client = 1;
  901. } else {
  902. // 来自cache
  903. Base.$.extend( runtime.options, opts );
  904. runtime.__promise.then( deferred.resolve );
  905. runtime.__client++;
  906. }
  907. standalone && (runtime.__standalone = standalone);
  908. return runtime;
  909. };
  910. this.getRuntime = function() {
  911. return runtime;
  912. };
  913. this.disconnectRuntime = function() {
  914. if ( !runtime ) {
  915. return;
  916. }
  917. runtime.__client--;
  918. if ( runtime.__client <= 0 ) {
  919. cache.remove( runtime );
  920. delete runtime.__promise;
  921. runtime.destroy();
  922. }
  923. runtime = null;
  924. };
  925. this.exec = function() {
  926. if ( !runtime ) {
  927. return;
  928. }
  929. var args = Base.slice( arguments );
  930. component && args.unshift( component );
  931. return runtime.exec.apply( this, args );
  932. };
  933. this.getRuid = function() {
  934. return runtime && runtime.uid;
  935. };
  936. this.destroy = (function( destroy ) {
  937. return function() {
  938. destroy && destroy.apply( this, arguments );
  939. this.trigger('destroy');
  940. this.off();
  941. this.exec('destroy');
  942. this.disconnectRuntime();
  943. };
  944. })( this.destroy );
  945. }
  946. Mediator.installTo( RuntimeClient.prototype );
  947. return RuntimeClient;
  948. });
  949. /**
  950. * @fileOverview Blob
  951. */
  952. define('lib/blob',[
  953. 'base',
  954. 'runtime/client'
  955. ], function( Base, RuntimeClient ) {
  956. function Blob( ruid, source ) {
  957. var me = this;
  958. me.source = source;
  959. me.ruid = ruid;
  960. RuntimeClient.call( me, 'Blob' );
  961. this.uid = source.uid || this.uid;
  962. this.type = source.type || '';
  963. this.size = source.size || 0;
  964. if ( ruid ) {
  965. me.connectRuntime( ruid );
  966. }
  967. }
  968. Base.inherits( RuntimeClient, {
  969. constructor: Blob,
  970. slice: function( start, end ) {
  971. return this.exec( 'slice', start, end );
  972. },
  973. getSource: function() {
  974. return this.source;
  975. }
  976. });
  977. return Blob;
  978. });
  979. /**
  980. * 为了统一化Flash的File和HTML5的File而存在
  981. * 以至于要调用Flash里面的File也可以像调用HTML5版本的File一下
  982. * @fileOverview File
  983. */
  984. define('lib/file',[
  985. 'base',
  986. 'lib/blob'
  987. ], function( Base, Blob ) {
  988. var uid = 1,
  989. rExt = /\.([^.]+)$/;
  990. function File( ruid, file ) {
  991. var ext;
  992. Blob.apply( this, arguments );
  993. this.name = file.name || ('untitled' + uid++);
  994. ext = rExt.exec( file.name ) ? RegExp.$1.toLowerCase() : '';
  995. // todo 支持其他类型文件的转换。
  996. // 如果有mimetype, 但是文件名里面没有找出后缀规律
  997. if ( !ext && this.type ) {
  998. ext = /\/(jpg|jpeg|png|gif|bmp)$/i.exec( this.type ) ?
  999. RegExp.$1.toLowerCase() : '';
  1000. this.name += '.' + ext;
  1001. }
  1002. // 如果没有指定mimetype, 但是知道文件后缀。
  1003. if ( !this.type && ~'jpg,jpeg,png,gif,bmp'.indexOf( ext ) ) {
  1004. this.type = 'image/' + (ext === 'jpg' ? 'jpeg' : ext);
  1005. }
  1006. this.ext = ext;
  1007. this.lastModifiedDate = file.lastModifiedDate ||
  1008. (new Date()).toLocaleString();
  1009. }
  1010. return Base.inherits( Blob, File );
  1011. });
  1012. /**
  1013. * @fileOverview 错误信息
  1014. */
  1015. define('lib/filepicker',[
  1016. 'base',
  1017. 'runtime/client',
  1018. 'lib/file'
  1019. ], function( Base, RuntimeClent, File ) {
  1020. var $ = Base.$;
  1021. function FilePicker( opts ) {
  1022. opts = this.options = $.extend({}, FilePicker.options, opts );
  1023. opts.container = $( opts.id );
  1024. if ( !opts.container.length ) {
  1025. throw new Error('按钮指定错误');
  1026. }
  1027. opts.innerHTML = opts.innerHTML || opts.label ||
  1028. opts.container.html() || '';
  1029. opts.button = $( opts.button || document.createElement('div') );
  1030. opts.button.html( opts.innerHTML );
  1031. opts.container.html( opts.button );
  1032. RuntimeClent.call( this, 'FilePicker', true );
  1033. }
  1034. FilePicker.options = {
  1035. button: null,
  1036. container: null,
  1037. label: null,
  1038. innerHTML: null,
  1039. multiple: true,
  1040. accept: null,
  1041. name: 'file'
  1042. };
  1043. Base.inherits( RuntimeClent, {
  1044. constructor: FilePicker,
  1045. init: function() {
  1046. var me = this,
  1047. opts = me.options,
  1048. button = opts.button;
  1049. button.addClass('webuploader-pick');
  1050. me.on( 'all', function( type ) {
  1051. var files;
  1052. switch ( type ) {
  1053. case 'mouseenter':
  1054. button.addClass('webuploader-pick-hover');
  1055. break;
  1056. case 'mouseleave':
  1057. button.removeClass('webuploader-pick-hover');
  1058. break;
  1059. case 'change':
  1060. files = me.exec('getFiles');
  1061. me.trigger( 'select', $.map( files, function( file ) {
  1062. file = new File( me.getRuid(), file );
  1063. // 记录来源。
  1064. file._refer = opts.container;
  1065. return file;
  1066. }), opts.container );
  1067. break;
  1068. }
  1069. });
  1070. me.connectRuntime( opts, function() {
  1071. me.refresh();
  1072. me.exec( 'init', opts );
  1073. me.trigger('ready');
  1074. });
  1075. $( window ).on( 'resize', function() {
  1076. me.refresh();
  1077. });
  1078. },
  1079. refresh: function() {
  1080. var shimContainer = this.getRuntime().getContainer(),
  1081. button = this.options.button,
  1082. width = button.outerWidth ?
  1083. button.outerWidth() : button.width(),
  1084. height = button.outerHeight ?
  1085. button.outerHeight() : button.height(),
  1086. pos = button.offset();
  1087. width && height && shimContainer.css({
  1088. bottom: 'auto',
  1089. right: 'auto',
  1090. width: width + 'px',
  1091. height: height + 'px'
  1092. }).offset( pos );
  1093. },
  1094. enable: function() {
  1095. var btn = this.options.button;
  1096. btn.removeClass('webuploader-pick-disable');
  1097. this.refresh();
  1098. },
  1099. disable: function() {
  1100. var btn = this.options.button;
  1101. this.getRuntime().getContainer().css({
  1102. top: '-99999px'
  1103. });
  1104. btn.addClass('webuploader-pick-disable');
  1105. },
  1106. destroy: function() {
  1107. if ( this.runtime ) {
  1108. this.exec('destroy');
  1109. this.disconnectRuntime();
  1110. }
  1111. }
  1112. });
  1113. return FilePicker;
  1114. });
  1115. /**
  1116. * @fileOverview 组件基类
  1117. */
  1118. define('widgets/widget',[
  1119. 'base',
  1120. 'uploader'
  1121. ], function( Base, Uploader ) {
  1122. var $ = Base.$,
  1123. _init = Uploader.prototype._init,
  1124. IGNORE = {},
  1125. widgetClass = [];
  1126. function isArrayLike( obj ) {
  1127. if ( !obj ) {
  1128. return false;
  1129. }
  1130. var length = obj.length,
  1131. type = $.type( obj );
  1132. if ( obj.nodeType === 1 && length ) {
  1133. return true;
  1134. }
  1135. return type === 'array' || type !== 'function' && type !== 'string' &&
  1136. (length === 0 || typeof length === 'number' && length > 0 &&
  1137. (length - 1) in obj);
  1138. }
  1139. function Widget( uploader ) {
  1140. this.owner = uploader;
  1141. this.options = uploader.options;
  1142. }
  1143. $.extend( Widget.prototype, {
  1144. init: Base.noop,
  1145. // 类Backbone的事件监听声明,监听uploader实例上的事件
  1146. // widget直接无法监听事件,事件只能通过uploader来传递
  1147. invoke: function( apiName, args ) {
  1148. /*
  1149. {
  1150. 'make-thumb': 'makeThumb'
  1151. }
  1152. */
  1153. var map = this.responseMap;
  1154. // 如果无API响应声明则忽略
  1155. if ( !map || !(apiName in map) || !(map[ apiName ] in this) ||
  1156. !$.isFunction( this[ map[ apiName ] ] ) ) {
  1157. return IGNORE;
  1158. }
  1159. return this[ map[ apiName ] ].apply( this, args );
  1160. },
  1161. /**
  1162. * 发送命令当传入`callback`或者`handler`中返回`promise`返回一个当所有`handler`中的promise都完成后完成的新`promise`
  1163. * @method request
  1164. * @grammar request( command, args ) => * | Promise
  1165. * @grammar request( command, args, callback ) => Promise
  1166. * @for Uploader
  1167. */
  1168. request: function() {
  1169. return this.owner.request.apply( this.owner, arguments );
  1170. }
  1171. });
  1172. // 扩展Uploader.
  1173. $.extend( Uploader.prototype, {
  1174. // 覆写_init用来初始化widgets
  1175. _init: function() {
  1176. var me = this,
  1177. widgets = me._widgets = [];
  1178. $.each( widgetClass, function( _, klass ) {
  1179. widgets.push( new klass( me ) );
  1180. });
  1181. return _init.apply( me, arguments );
  1182. },
  1183. request: function( apiName, args, callback ) {
  1184. var i = 0,
  1185. widgets = this._widgets,
  1186. len = widgets.length,
  1187. rlts = [],
  1188. dfds = [],
  1189. widget, rlt, promise, key;
  1190. args = isArrayLike( args ) ? args : [ args ];
  1191. for ( ; i < len; i++ ) {
  1192. widget = widgets[ i ];
  1193. rlt = widget.invoke( apiName, args );
  1194. if ( rlt !== IGNORE ) {
  1195. // Deferred对象
  1196. if ( Base.isPromise( rlt ) ) {
  1197. dfds.push( rlt );
  1198. } else {
  1199. rlts.push( rlt );
  1200. }
  1201. }
  1202. }
  1203. // 如果有callback,则用异步方式。
  1204. if ( callback || dfds.length ) {
  1205. promise = Base.when.apply( Base, dfds );
  1206. key = promise.pipe ? 'pipe' : 'then';
  1207. // 很重要不能删除。删除了会死循环。
  1208. // 保证执行顺序。让callback总是在下一个tick中执行。
  1209. return promise[ key ](function() {
  1210. var deferred = Base.Deferred(),
  1211. args = arguments;
  1212. setTimeout(function() {
  1213. deferred.resolve.apply( deferred, args );
  1214. }, 1 );
  1215. return deferred.promise();
  1216. })[ key ]( callback || Base.noop );
  1217. } else {
  1218. return rlts[ 0 ];
  1219. }
  1220. }
  1221. });
  1222. /**
  1223. * 添加组件
  1224. * @param {object} widgetProto 组件原型构造函数通过constructor属性定义
  1225. * @param {object} responseMap API名称与函数实现的映射
  1226. * @example
  1227. * Uploader.register( {
  1228. * init: function( options ) {},
  1229. * makeThumb: function() {}
  1230. * }, {
  1231. * 'make-thumb': 'makeThumb'
  1232. * } );
  1233. */
  1234. Uploader.register = Widget.register = function( responseMap, widgetProto ) {
  1235. var map = { init: 'init' },
  1236. klass;
  1237. if ( arguments.length === 1 ) {
  1238. widgetProto = responseMap;
  1239. widgetProto.responseMap = map;
  1240. } else {
  1241. widgetProto.responseMap = $.extend( map, responseMap );
  1242. }
  1243. klass = Base.inherits( Widget, widgetProto );
  1244. widgetClass.push( klass );
  1245. return klass;
  1246. };
  1247. return Widget;
  1248. });
  1249. /**
  1250. * @fileOverview 文件选择相关
  1251. */
  1252. define('widgets/filepicker',[
  1253. 'base',
  1254. 'uploader',
  1255. 'lib/filepicker',
  1256. 'widgets/widget'
  1257. ], function( Base, Uploader, FilePicker ) {
  1258. var $ = Base.$;
  1259. $.extend( Uploader.options, {
  1260. /**
  1261. * @property {Selector | Object} [pick=undefined]
  1262. * @namespace options
  1263. * @for Uploader
  1264. * @description 指定选择文件的按钮容器不指定则不创建按钮
  1265. *
  1266. * * `id` {Seletor} 指定选择文件的按钮容器不指定则不创建按钮
  1267. * * `label` {String} 请采用 `innerHTML` 代替
  1268. * * `innerHTML` {String} 指定按钮文字不指定时优先从指定的容器中看是否自带文字
  1269. * * `multiple` {Boolean} 是否开起同时选择多个文件能力
  1270. */
  1271. pick: null,
  1272. /**
  1273. * @property {Arroy} [accept=null]
  1274. * @namespace options
  1275. * @for Uploader
  1276. * @description 指定接受哪些类型的文件 由于目前还有ext转mimeType表所以这里需要分开指定
  1277. *
  1278. * * `title` {String} 文字描述
  1279. * * `extensions` {String} 允许的文件后缀不带点多个用逗号分割
  1280. * * `mimeTypes` {String} 多个用逗号分割
  1281. *
  1282. *
  1283. *
  1284. * ```
  1285. * {
  1286. * title: 'Images',
  1287. * extensions: 'gif,jpg,jpeg,bmp,png',
  1288. * mimeTypes: 'image/*'
  1289. * }
  1290. * ```
  1291. */
  1292. accept: null/*{
  1293. title: 'Images',
  1294. extensions: 'gif,jpg,jpeg,bmp,png',
  1295. mimeTypes: 'image/*'
  1296. }*/
  1297. });
  1298. return Uploader.register({
  1299. 'add-btn': 'addButton',
  1300. refresh: 'refresh',
  1301. disable: 'disable',
  1302. enable: 'enable'
  1303. }, {
  1304. init: function( opts ) {
  1305. this.pickers = [];
  1306. return opts.pick && this.addButton( opts.pick );
  1307. },
  1308. refresh: function() {
  1309. $.each( this.pickers, function() {
  1310. this.refresh();
  1311. });
  1312. },
  1313. /**
  1314. * @method addButton
  1315. * @for Uploader
  1316. * @grammar addButton( pick ) => Promise
  1317. * @description
  1318. * 添加文件选择按钮如果一个按钮不够需要调用此方法来添加参数跟[options.pick](#WebUploader:Uploader:options)一致
  1319. * @example
  1320. * uploader.addButton({
  1321. * id: '#btnContainer',
  1322. * innerHTML: '选择文件'
  1323. * });
  1324. */
  1325. addButton: function( pick ) {
  1326. var me = this,
  1327. opts = me.options,
  1328. accept = opts.accept,
  1329. options, picker, deferred;
  1330. if ( !pick ) {
  1331. return;
  1332. }
  1333. deferred = Base.Deferred();
  1334. $.isPlainObject( pick ) || (pick = {
  1335. id: pick
  1336. });
  1337. options = $.extend({}, pick, {
  1338. accept: $.isPlainObject( accept ) ? [ accept ] : accept,
  1339. swf: opts.swf,
  1340. runtimeOrder: opts.runtimeOrder
  1341. });
  1342. picker = new FilePicker( options );
  1343. picker.once( 'ready', deferred.resolve );
  1344. picker.on( 'select', function( files ) {
  1345. me.owner.request( 'add-file', [ files ]);
  1346. });
  1347. picker.init();
  1348. this.pickers.push( picker );
  1349. return deferred.promise();
  1350. },
  1351. disable: function() {
  1352. $.each( this.pickers, function() {
  1353. this.disable();
  1354. });
  1355. },
  1356. enable: function() {
  1357. $.each( this.pickers, function() {
  1358. this.enable();
  1359. });
  1360. }
  1361. });
  1362. });
  1363. /**
  1364. * @fileOverview Image
  1365. */
  1366. define('lib/image',[
  1367. 'base',
  1368. 'runtime/client',
  1369. 'lib/blob'
  1370. ], function( Base, RuntimeClient, Blob ) {
  1371. var $ = Base.$;
  1372. // 构造器。
  1373. function Image( opts ) {
  1374. this.options = $.extend({}, Image.options, opts );
  1375. RuntimeClient.call( this, 'Image' );
  1376. this.on( 'load', function() {
  1377. this._info = this.exec('info');
  1378. this._meta = this.exec('meta');
  1379. });
  1380. }
  1381. // 默认选项。
  1382. Image.options = {
  1383. // 默认的图片处理质量
  1384. quality: 90,
  1385. // 是否裁剪
  1386. crop: false,
  1387. // 是否保留头部信息
  1388. preserveHeaders: true,
  1389. // 是否允许放大。
  1390. allowMagnify: true
  1391. };
  1392. // 继承RuntimeClient.
  1393. Base.inherits( RuntimeClient, {
  1394. constructor: Image,
  1395. info: function( val ) {
  1396. // setter
  1397. if ( val ) {
  1398. this._info = val;
  1399. return this;
  1400. }
  1401. // getter
  1402. return this._info;
  1403. },
  1404. meta: function( val ) {
  1405. // setter
  1406. if ( val ) {
  1407. this._meta = val;
  1408. return this;
  1409. }
  1410. // getter
  1411. return this._meta;
  1412. },
  1413. loadFromBlob: function( blob ) {
  1414. var me = this,
  1415. ruid = blob.getRuid();
  1416. this.connectRuntime( ruid, function() {
  1417. me.exec( 'init', me.options );
  1418. me.exec( 'loadFromBlob', blob );
  1419. });
  1420. },
  1421. resize: function() {
  1422. var args = Base.slice( arguments );
  1423. return this.exec.apply( this, [ 'resize' ].concat( args ) );
  1424. },
  1425. getAsDataUrl: function( type ) {
  1426. return this.exec( 'getAsDataUrl', type );
  1427. },
  1428. getAsBlob: function( type ) {
  1429. var blob = this.exec( 'getAsBlob', type );
  1430. return new Blob( this.getRuid(), blob );
  1431. }
  1432. });
  1433. return Image;
  1434. });
  1435. /**
  1436. * @fileOverview 图片操作, 负责预览图片和上传前压缩图片
  1437. */
  1438. define('widgets/image',[
  1439. 'base',
  1440. 'uploader',
  1441. 'lib/image',
  1442. 'widgets/widget'
  1443. ], function( Base, Uploader, Image ) {
  1444. var $ = Base.$,
  1445. throttle;
  1446. // 根据要处理的文件大小来节流,一次不能处理太多,会卡。
  1447. throttle = (function( max ) {
  1448. var occupied = 0,
  1449. waiting = [],
  1450. tick = function() {
  1451. var item;
  1452. while ( waiting.length && occupied < max ) {
  1453. item = waiting.shift();
  1454. occupied += item[ 0 ];
  1455. item[ 1 ]();
  1456. }
  1457. };
  1458. return function( emiter, size, cb ) {
  1459. waiting.push([ size, cb ]);
  1460. emiter.once( 'destroy', function() {
  1461. occupied -= size;
  1462. setTimeout( tick, 1 );
  1463. });
  1464. setTimeout( tick, 1 );
  1465. };
  1466. })( 5 * 1024 * 1024 );
  1467. $.extend( Uploader.options, {
  1468. /**
  1469. * @property {Object} [thumb]
  1470. * @namespace options
  1471. * @for Uploader
  1472. * @description 配置生成缩略图的选项
  1473. *
  1474. * 默认为
  1475. *
  1476. * ```javascript
  1477. * {
  1478. * width: 110,
  1479. * height: 110,
  1480. *
  1481. * // 图片质量,只有type为`image/jpeg`的时候才有效。
  1482. * quality: 70,
  1483. *
  1484. * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
  1485. * allowMagnify: true,
  1486. *
  1487. * // 是否允许裁剪。
  1488. * crop: true,
  1489. *
  1490. * // 是否保留头部meta信息。
  1491. * preserveHeaders: false,
  1492. *
  1493. * // 为空的话则保留原有图片格式。
  1494. * // 否则强制转换成指定的类型。
  1495. * type: 'image/jpeg'
  1496. * }
  1497. * ```
  1498. */
  1499. thumb: {
  1500. width: 110,
  1501. height: 110,
  1502. quality: 70,
  1503. allowMagnify: true,
  1504. crop: true,
  1505. preserveHeaders: false,
  1506. // 为空的话则保留原有图片格式。
  1507. // 否则强制转换成指定的类型。
  1508. // IE 8下面 base64 大小不能超过 32K 否则预览失败,而非 jpeg 编码的图片很可
  1509. // 能会超过 32k, 所以这里设置成预览的时候都是 image/jpeg
  1510. type: 'image/jpeg'
  1511. },
  1512. /**
  1513. * @property {Object} [compress]
  1514. * @namespace options
  1515. * @for Uploader
  1516. * @description 配置压缩的图片的选项如果此选项为`false`, 则图片在上传前不进行压缩
  1517. *
  1518. * 默认为
  1519. *
  1520. * ```javascript
  1521. * {
  1522. * width: 1600,
  1523. * height: 1600,
  1524. *
  1525. * // 图片质量,只有type为`image/jpeg`的时候才有效。
  1526. * quality: 90,
  1527. *
  1528. * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
  1529. * allowMagnify: false,
  1530. *
  1531. * // 是否允许裁剪。
  1532. * crop: false,
  1533. *
  1534. * // 是否保留头部meta信息。
  1535. * preserveHeaders: true
  1536. * }
  1537. * ```
  1538. */
  1539. compress: {
  1540. width: 1600,
  1541. height: 1600,
  1542. quality: 90,
  1543. allowMagnify: false,
  1544. crop: false,
  1545. preserveHeaders: true
  1546. }
  1547. });
  1548. return Uploader.register({
  1549. 'make-thumb': 'makeThumb',
  1550. 'before-send-file': 'compressImage'
  1551. }, {
  1552. /**
  1553. * 生成缩略图此过程为异步所以需要传入`callback`
  1554. * 通常情况在图片加入队里后调用此方法来生成预览图以增强交互效果
  1555. *
  1556. * `callback`中可以接收到两个参数
  1557. * * 第一个为error如果生成缩略图有错误此error将为真
  1558. * * 第二个为ret, 缩略图的Data URL值
  1559. *
  1560. * **注意**
  1561. * Date URL在IE6/7中不支持所以不用调用此方法了直接显示一张暂不支持预览图片好了
  1562. *
  1563. *
  1564. * @method makeThumb
  1565. * @grammar makeThumb( file, callback ) => undefined
  1566. * @grammar makeThumb( file, callback, width, height ) => undefined
  1567. * @for Uploader
  1568. * @example
  1569. *
  1570. * uploader.on( 'fileQueued', function( file ) {
  1571. * var $li = ...;
  1572. *
  1573. * uploader.makeThumb( file, function( error, ret ) {
  1574. * if ( error ) {
  1575. * $li.text('预览错误');
  1576. * } else {
  1577. * $li.append('<img alt="" src="' + ret + '" />');
  1578. * }
  1579. * });
  1580. *
  1581. * });
  1582. */
  1583. makeThumb: function( file, cb, width, height ) {
  1584. var opts, image;
  1585. file = this.request( 'get-file', file );
  1586. // 只预览图片格式。
  1587. if ( !file.type.match( /^image/ ) ) {
  1588. cb( true );
  1589. return;
  1590. }
  1591. opts = $.extend({}, this.options.thumb );
  1592. // 如果传入的是object.
  1593. if ( $.isPlainObject( width ) ) {
  1594. opts = $.extend( opts, width );
  1595. width = null;
  1596. }
  1597. width = width || opts.width;
  1598. height = height || opts.height;
  1599. image = new Image( opts );
  1600. image.once( 'load', function() {
  1601. file._info = file._info || image.info();
  1602. file._meta = file._meta || image.meta();
  1603. image.resize( width, height );
  1604. });
  1605. image.once( 'complete', function() {
  1606. cb( false, image.getAsDataUrl( opts.type ) );
  1607. image.destroy();
  1608. });
  1609. image.once( 'error', function() {
  1610. cb( true );
  1611. image.destroy();
  1612. });
  1613. throttle( image, file.source.size, function() {
  1614. file._info && image.info( file._info );
  1615. file._meta && image.meta( file._meta );
  1616. image.loadFromBlob( file.source );
  1617. });
  1618. },
  1619. compressImage: function( file ) {
  1620. var opts = this.options.compress || this.options.resize,
  1621. compressSize = opts && opts.compressSize || 300 * 1024,
  1622. image, deferred;
  1623. file = this.request( 'get-file', file );
  1624. // 只预览图片格式。
  1625. if ( !opts || !~'image/jpeg,image/jpg'.indexOf( file.type ) ||
  1626. file.size < compressSize ||
  1627. file._compressed ) {
  1628. return;
  1629. }
  1630. opts = $.extend({}, opts );
  1631. deferred = Base.Deferred();
  1632. image = new Image( opts );
  1633. deferred.always(function() {
  1634. image.destroy();
  1635. image = null;
  1636. });
  1637. image.once( 'error', deferred.reject );
  1638. image.once( 'load', function() {
  1639. file._info = file._info || image.info();
  1640. file._meta = file._meta || image.meta();
  1641. image.resize( opts.width, opts.height );
  1642. });
  1643. image.once( 'complete', function() {
  1644. var blob, size;
  1645. // 移动端 UC / qq 浏览器的无图模式下
  1646. // ctx.getImageData 处理大图的时候会报 Exception
  1647. // INDEX_SIZE_ERR: DOM Exception 1
  1648. try {
  1649. blob = image.getAsBlob( opts.type );
  1650. size = file.size;
  1651. // 如果压缩后,比原来还大则不用压缩后的。
  1652. if ( blob.size < size ) {
  1653. // file.source.destroy && file.source.destroy();
  1654. file.source = blob;
  1655. file.size = blob.size;
  1656. file.trigger( 'resize', blob.size, size );
  1657. }
  1658. // 标记,避免重复压缩。
  1659. file._compressed = true;
  1660. deferred.resolve();
  1661. } catch ( e ) {
  1662. // 出错了直接继续,让其上传原始图片
  1663. deferred.resolve();
  1664. }
  1665. });
  1666. file._info && image.info( file._info );
  1667. file._meta && image.meta( file._meta );
  1668. image.loadFromBlob( file.source );
  1669. return deferred.promise();
  1670. }
  1671. });
  1672. });
  1673. /**
  1674. * @fileOverview 文件属性封装
  1675. */
  1676. define('file',[
  1677. 'base',
  1678. 'mediator'
  1679. ], function( Base, Mediator ) {
  1680. var $ = Base.$,
  1681. idPrefix = 'WU_FILE_',
  1682. idSuffix = 0,
  1683. rExt = /\.([^.]+)$/,
  1684. statusMap = {};
  1685. function gid() {
  1686. return idPrefix + idSuffix++;
  1687. }
  1688. /**
  1689. * 文件类
  1690. * @class File
  1691. * @constructor 构造函数
  1692. * @grammar new File( source ) => File
  1693. * @param {Lib.File} source [lib.File](#Lib.File)实例, 此source对象是带有Runtime信息的
  1694. */
  1695. function WUFile( source ) {
  1696. /**
  1697. * 文件名包括扩展名后缀
  1698. * @property name
  1699. * @type {string}
  1700. */
  1701. this.name = source.name || 'Untitled';
  1702. /**
  1703. * 文件体积字节
  1704. * @property size
  1705. * @type {uint}
  1706. * @default 0
  1707. */
  1708. this.size = source.size || 0;
  1709. /**
  1710. * 文件MIMETYPE类型与文件类型的对应关系请参考[http://t.cn/z8ZnFny](http://t.cn/z8ZnFny)
  1711. * @property type
  1712. * @type {string}
  1713. * @default 'application'
  1714. */
  1715. this.type = source.type || 'application';
  1716. /**
  1717. * 文件最后修改日期
  1718. * @property lastModifiedDate
  1719. * @type {int}
  1720. * @default 当前时间戳
  1721. */
  1722. this.lastModifiedDate = source.lastModifiedDate || (new Date() * 1);
  1723. /**
  1724. * 文件ID每个对象具有唯一ID与文件名无关
  1725. * @property id
  1726. * @type {string}
  1727. */
  1728. this.id = gid();
  1729. /**
  1730. * 文件扩展名通过文件名获取例如test.png的扩展名为png
  1731. * @property ext
  1732. * @type {string}
  1733. */
  1734. this.ext = rExt.exec( this.name ) ? RegExp.$1 : '';
  1735. /**
  1736. * 状态文字说明在不同的status语境下有不同的用途
  1737. * @property statusText
  1738. * @type {string}
  1739. */
  1740. this.statusText = '';
  1741. // 存储文件状态,防止通过属性直接修改
  1742. statusMap[ this.id ] = WUFile.Status.INITED;
  1743. this.source = source;
  1744. this.loaded = 0;
  1745. this.on( 'error', function( msg ) {
  1746. this.setStatus( WUFile.Status.ERROR, msg );
  1747. });
  1748. }
  1749. $.extend( WUFile.prototype, {
  1750. /**
  1751. * 设置状态状态变化时会触发`change`事件
  1752. * @method setStatus
  1753. * @grammar setStatus( status[, statusText] );
  1754. * @param {File.Status|String} status [文件状态值](#WebUploader:File:File.Status)
  1755. * @param {String} [statusText=''] 状态说明常在error时使用用http, abort,server等来标记是由于什么原因导致文件错误
  1756. */
  1757. setStatus: function( status, text ) {
  1758. var prevStatus = statusMap[ this.id ];
  1759. typeof text !== 'undefined' && (this.statusText = text);
  1760. if ( status !== prevStatus ) {
  1761. statusMap[ this.id ] = status;
  1762. /**
  1763. * 文件状态变化
  1764. * @event statuschange
  1765. */
  1766. this.trigger( 'statuschange', status, prevStatus );
  1767. }
  1768. },
  1769. /**
  1770. * 获取文件状态
  1771. * @return {File.Status}
  1772. * @example
  1773. 文件状态具体包括以下几种类型
  1774. {
  1775. // 初始化
  1776. INITED: 0,
  1777. // 已入队列
  1778. QUEUED: 1,
  1779. // 正在上传
  1780. PROGRESS: 2,
  1781. // 上传出错
  1782. ERROR: 3,
  1783. // 上传成功
  1784. COMPLETE: 4,
  1785. // 上传取消
  1786. CANCELLED: 5
  1787. }
  1788. */
  1789. getStatus: function() {
  1790. return statusMap[ this.id ];
  1791. },
  1792. /**
  1793. * 获取文件原始信息
  1794. * @return {*}
  1795. */
  1796. getSource: function() {
  1797. return this.source;
  1798. },
  1799. destory: function() {
  1800. delete statusMap[ this.id ];
  1801. }
  1802. });
  1803. Mediator.installTo( WUFile.prototype );
  1804. /**
  1805. * 文件状态值具体包括以下几种类型
  1806. * * `inited` 初始状态
  1807. * * `queued` 已经进入队列, 等待上传
  1808. * * `progress` 上传中
  1809. * * `complete` 上传完成
  1810. * * `error` 上传出错可重试
  1811. * * `interrupt` 上传中断可续传
  1812. * * `invalid` 文件不合格不能重试上传会自动从队列中移除
  1813. * * `cancelled` 文件被移除
  1814. * @property {Object} Status
  1815. * @namespace File
  1816. * @class File
  1817. * @static
  1818. */
  1819. WUFile.Status = {
  1820. INITED: 'inited', // 初始状态
  1821. QUEUED: 'queued', // 已经进入队列, 等待上传
  1822. PROGRESS: 'progress', // 上传中
  1823. ERROR: 'error', // 上传出错,可重试
  1824. COMPLETE: 'complete', // 上传完成。
  1825. CANCELLED: 'cancelled', // 上传取消。
  1826. INTERRUPT: 'interrupt', // 上传中断,可续传。
  1827. INVALID: 'invalid' // 文件不合格,不能重试上传。
  1828. };
  1829. return WUFile;
  1830. });
  1831. /**
  1832. * @fileOverview 文件队列
  1833. */
  1834. define('queue',[
  1835. 'base',
  1836. 'mediator',
  1837. 'file'
  1838. ], function( Base, Mediator, WUFile ) {
  1839. var $ = Base.$,
  1840. STATUS = WUFile.Status;
  1841. /**
  1842. * 文件队列, 用来存储各个状态中的文件
  1843. * @class Queue
  1844. * @extends Mediator
  1845. */
  1846. function Queue() {
  1847. /**
  1848. * 统计文件数
  1849. * * `numOfQueue` 队列中的文件数
  1850. * * `numOfSuccess` 上传成功的文件数
  1851. * * `numOfCancel` 被移除的文件数
  1852. * * `numOfProgress` 正在上传中的文件数
  1853. * * `numOfUploadFailed` 上传错误的文件数
  1854. * * `numOfInvalid` 无效的文件数
  1855. * @property {Object} stats
  1856. */
  1857. this.stats = {
  1858. numOfQueue: 0,
  1859. numOfSuccess: 0,
  1860. numOfCancel: 0,
  1861. numOfProgress: 0,
  1862. numOfUploadFailed: 0,
  1863. numOfInvalid: 0
  1864. };
  1865. // 上传队列,仅包括等待上传的文件
  1866. this._queue = [];
  1867. // 存储所有文件
  1868. this._map = {};
  1869. }
  1870. $.extend( Queue.prototype, {
  1871. /**
  1872. * 将新文件加入对队列尾部
  1873. *
  1874. * @method append
  1875. * @param {File} file 文件对象
  1876. */
  1877. append: function( file ) {
  1878. this._queue.push( file );
  1879. this._fileAdded( file );
  1880. return this;
  1881. },
  1882. /**
  1883. * 将新文件加入对队列头部
  1884. *
  1885. * @method prepend
  1886. * @param {File} file 文件对象
  1887. */
  1888. prepend: function( file ) {
  1889. this._queue.unshift( file );
  1890. this._fileAdded( file );
  1891. return this;
  1892. },
  1893. /**
  1894. * 获取文件对象
  1895. *
  1896. * @method getFile
  1897. * @param {String} fileId 文件ID
  1898. * @return {File}
  1899. */
  1900. getFile: function( fileId ) {
  1901. if ( typeof fileId !== 'string' ) {
  1902. return fileId;
  1903. }
  1904. return this._map[ fileId ];
  1905. },
  1906. /**
  1907. * 从队列中取出一个指定状态的文件
  1908. * @grammar fetch( status ) => File
  1909. * @method fetch
  1910. * @param {String} status [文件状态值](#WebUploader:File:File.Status)
  1911. * @return {File} [File](#WebUploader:File)
  1912. */
  1913. fetch: function( status ) {
  1914. var len = this._queue.length,
  1915. i, file;
  1916. status = status || STATUS.QUEUED;
  1917. for ( i = 0; i < len; i++ ) {
  1918. file = this._queue[ i ];
  1919. if ( status === file.getStatus() ) {
  1920. return file;
  1921. }
  1922. }
  1923. return null;
  1924. },
  1925. /**
  1926. * 对队列进行排序能够控制文件上传顺序
  1927. * @grammar sort( fn ) => undefined
  1928. * @method sort
  1929. * @param {Function} fn 排序方法
  1930. */
  1931. sort: function( fn ) {
  1932. if ( typeof fn === 'function' ) {
  1933. this._queue.sort( fn );
  1934. }
  1935. },
  1936. /**
  1937. * 获取指定类型的文件列表, 列表中每一个成员为[File](#WebUploader:File)对象
  1938. * @grammar getFiles( [status1[, status2 ...]] ) => Array
  1939. * @method getFiles
  1940. * @param {String} [status] [文件状态值](#WebUploader:File:File.Status)
  1941. */
  1942. getFiles: function() {
  1943. var sts = [].slice.call( arguments, 0 ),
  1944. ret = [],
  1945. i = 0,
  1946. len = this._queue.length,
  1947. file;
  1948. for ( ; i < len; i++ ) {
  1949. file = this._queue[ i ];
  1950. if ( sts.length && !~$.inArray( file.getStatus(), sts ) ) {
  1951. continue;
  1952. }
  1953. ret.push( file );
  1954. }
  1955. return ret;
  1956. },
  1957. _fileAdded: function( file ) {
  1958. var me = this,
  1959. existing = this._map[ file.id ];
  1960. if ( !existing ) {
  1961. this._map[ file.id ] = file;
  1962. file.on( 'statuschange', function( cur, pre ) {
  1963. me._onFileStatusChange( cur, pre );
  1964. });
  1965. }
  1966. file.setStatus( STATUS.QUEUED );
  1967. },
  1968. _onFileStatusChange: function( curStatus, preStatus ) {
  1969. var stats = this.stats;
  1970. switch ( preStatus ) {
  1971. case STATUS.PROGRESS:
  1972. stats.numOfProgress--;
  1973. break;
  1974. case STATUS.QUEUED:
  1975. stats.numOfQueue --;
  1976. break;
  1977. case STATUS.ERROR:
  1978. stats.numOfUploadFailed--;
  1979. break;
  1980. case STATUS.INVALID:
  1981. stats.numOfInvalid--;
  1982. break;
  1983. }
  1984. switch ( curStatus ) {
  1985. case STATUS.QUEUED:
  1986. stats.numOfQueue++;
  1987. break;
  1988. case STATUS.PROGRESS:
  1989. stats.numOfProgress++;
  1990. break;
  1991. case STATUS.ERROR:
  1992. stats.numOfUploadFailed++;
  1993. break;
  1994. case STATUS.COMPLETE:
  1995. stats.numOfSuccess++;
  1996. break;
  1997. case STATUS.CANCELLED:
  1998. stats.numOfCancel++;
  1999. break;
  2000. case STATUS.INVALID:
  2001. stats.numOfInvalid++;
  2002. break;
  2003. }
  2004. }
  2005. });
  2006. Mediator.installTo( Queue.prototype );
  2007. return Queue;
  2008. });
  2009. /**
  2010. * @fileOverview 队列
  2011. */
  2012. define('widgets/queue',[
  2013. 'base',
  2014. 'uploader',
  2015. 'queue',
  2016. 'file',
  2017. 'lib/file',
  2018. 'runtime/client',
  2019. 'widgets/widget'
  2020. ], function( Base, Uploader, Queue, WUFile, File, RuntimeClient ) {
  2021. var $ = Base.$,
  2022. rExt = /\.\w+$/,
  2023. Status = WUFile.Status;
  2024. return Uploader.register({
  2025. 'sort-files': 'sortFiles',
  2026. 'add-file': 'addFiles',
  2027. 'get-file': 'getFile',
  2028. 'fetch-file': 'fetchFile',
  2029. 'get-stats': 'getStats',
  2030. 'get-files': 'getFiles',
  2031. 'remove-file': 'removeFile',
  2032. 'retry': 'retry',
  2033. 'reset': 'reset',
  2034. 'accept-file': 'acceptFile'
  2035. }, {
  2036. init: function( opts ) {
  2037. var me = this,
  2038. deferred, len, i, item, arr, accept, runtime;
  2039. if ( $.isPlainObject( opts.accept ) ) {
  2040. opts.accept = [ opts.accept ];
  2041. }
  2042. // accept中的中生成匹配正则。
  2043. if ( opts.accept ) {
  2044. arr = [];
  2045. for ( i = 0, len = opts.accept.length; i < len; i++ ) {
  2046. item = opts.accept[ i ].extensions;
  2047. item && arr.push( item );
  2048. }
  2049. if ( arr.length ) {
  2050. accept = '\\.' + arr.join(',')
  2051. .replace( /,/g, '$|\\.' )
  2052. .replace( /\*/g, '.*' ) + '$';
  2053. }
  2054. me.accept = new RegExp( accept, 'i' );
  2055. }
  2056. me.queue = new Queue();
  2057. me.stats = me.queue.stats;
  2058. // 如果当前不是html5运行时,那就算了。
  2059. // 不执行后续操作
  2060. if ( this.request('predict-runtime-type') !== 'html5' ) {
  2061. return;
  2062. }
  2063. // 创建一个 html5 运行时的 placeholder
  2064. // 以至于外部添加原生 File 对象的时候能正确包裹一下供 webuploader 使用。
  2065. deferred = Base.Deferred();
  2066. runtime = new RuntimeClient('Placeholder');
  2067. runtime.connectRuntime({
  2068. runtimeOrder: 'html5'
  2069. }, function() {
  2070. me._ruid = runtime.getRuid();
  2071. deferred.resolve();
  2072. });
  2073. return deferred.promise();
  2074. },
  2075. // 为了支持外部直接添加一个原生File对象。
  2076. _wrapFile: function( file ) {
  2077. if ( !(file instanceof WUFile) ) {
  2078. if ( !(file instanceof File) ) {
  2079. if ( !this._ruid ) {
  2080. throw new Error('Can\'t add external files.');
  2081. }
  2082. file = new File( this._ruid, file );
  2083. }
  2084. file = new WUFile( file );
  2085. }
  2086. return file;
  2087. },
  2088. // 判断文件是否可以被加入队列
  2089. acceptFile: function( file ) {
  2090. var invalid = !file || file.size < 6 || this.accept &&
  2091. // 如果名字中有后缀,才做后缀白名单处理。
  2092. rExt.exec( file.name ) && !this.accept.test( file.name );
  2093. return !invalid;
  2094. },
  2095. /**
  2096. * @event beforeFileQueued
  2097. * @param {File} file File对象
  2098. * @description 当文件被加入队列之前触发此事件的handler返回值为`false`则此文件不会被添加进入队列
  2099. * @for Uploader
  2100. */
  2101. /**
  2102. * @event fileQueued
  2103. * @param {File} file File对象
  2104. * @description 当文件被加入队列以后触发
  2105. * @for Uploader
  2106. */
  2107. _addFile: function( file ) {
  2108. var me = this;
  2109. file = me._wrapFile( file );
  2110. // 不过类型判断允许不允许,先派送 `beforeFileQueued`
  2111. if ( !me.owner.trigger( 'beforeFileQueued', file ) ) {
  2112. return;
  2113. }
  2114. // 类型不匹配,则派送错误事件,并返回。
  2115. if ( !me.acceptFile( file ) ) {
  2116. me.owner.trigger( 'error', 'Q_TYPE_DENIED', file );
  2117. return;
  2118. }
  2119. me.queue.append( file );
  2120. me.owner.trigger( 'fileQueued', file );
  2121. return file;
  2122. },
  2123. getFile: function( fileId ) {
  2124. return this.queue.getFile( fileId );
  2125. },
  2126. /**
  2127. * @event filesQueued
  2128. * @param {File} files 数组内容为原始File(lib/File对象
  2129. * @description 当一批文件添加进队列以后触发
  2130. * @for Uploader
  2131. */
  2132. /**
  2133. * @method addFiles
  2134. * @grammar addFiles( file ) => undefined
  2135. * @grammar addFiles( [file1, file2 ...] ) => undefined
  2136. * @param {Array of File or File} [files] Files 对象 数组
  2137. * @description 添加文件到队列
  2138. * @for Uploader
  2139. */
  2140. addFiles: function( files ) {
  2141. var me = this;
  2142. if ( !files.length ) {
  2143. files = [ files ];
  2144. }
  2145. files = $.map( files, function( file ) {
  2146. return me._addFile( file );
  2147. });
  2148. me.owner.trigger( 'filesQueued', files );
  2149. if ( me.options.auto ) {
  2150. me.request('start-upload');
  2151. }
  2152. },
  2153. getStats: function() {
  2154. return this.stats;
  2155. },
  2156. /**
  2157. * @event fileDequeued
  2158. * @param {File} file File对象
  2159. * @description 当文件被移除队列后触发
  2160. * @for Uploader
  2161. */
  2162. /**
  2163. * @method removeFile
  2164. * @grammar removeFile( file ) => undefined
  2165. * @grammar removeFile( id ) => undefined
  2166. * @param {File|id} file File对象或这File对象的id
  2167. * @description 移除某一文件
  2168. * @for Uploader
  2169. * @example
  2170. *
  2171. * $li.on('click', '.remove-this', function() {
  2172. * uploader.removeFile( file );
  2173. * })
  2174. */
  2175. removeFile: function( file ) {
  2176. var me = this;
  2177. file = file.id ? file : me.queue.getFile( file );
  2178. file.setStatus( Status.CANCELLED );
  2179. me.owner.trigger( 'fileDequeued', file );
  2180. },
  2181. /**
  2182. * @method getFiles
  2183. * @grammar getFiles() => Array
  2184. * @grammar getFiles( status1, status2, status... ) => Array
  2185. * @description 返回指定状态的文件集合不传参数将返回所有状态的文件
  2186. * @for Uploader
  2187. * @example
  2188. * console.log( uploader.getFiles() ); // => all files
  2189. * console.log( uploader.getFiles('error') ) // => all error files.
  2190. */
  2191. getFiles: function() {
  2192. return this.queue.getFiles.apply( this.queue, arguments );
  2193. },
  2194. fetchFile: function() {
  2195. return this.queue.fetch.apply( this.queue, arguments );
  2196. },
  2197. /**
  2198. * @method retry
  2199. * @grammar retry() => undefined
  2200. * @grammar retry( file ) => undefined
  2201. * @description 重试上传重试指定文件或者从出错的文件开始重新上传
  2202. * @for Uploader
  2203. * @example
  2204. * function retry() {
  2205. * uploader.retry();
  2206. * }
  2207. */
  2208. retry: function( file, noForceStart ) {
  2209. var me = this,
  2210. files, i, len;
  2211. if ( file ) {
  2212. file = file.id ? file : me.queue.getFile( file );
  2213. file.setStatus( Status.QUEUED );
  2214. noForceStart || me.request('start-upload');
  2215. return;
  2216. }
  2217. files = me.queue.getFiles( Status.ERROR );
  2218. i = 0;
  2219. len = files.length;
  2220. for ( ; i < len; i++ ) {
  2221. file = files[ i ];
  2222. file.setStatus( Status.QUEUED );
  2223. }
  2224. me.request('start-upload');
  2225. },
  2226. /**
  2227. * @method sort
  2228. * @grammar sort( fn ) => undefined
  2229. * @description 排序队列中的文件在上传之前调整可以控制上传顺序
  2230. * @for Uploader
  2231. */
  2232. sortFiles: function() {
  2233. return this.queue.sort.apply( this.queue, arguments );
  2234. },
  2235. /**
  2236. * @method reset
  2237. * @grammar reset() => undefined
  2238. * @description 重置uploader目前只重置了队列
  2239. * @for Uploader
  2240. * @example
  2241. * uploader.reset();
  2242. */
  2243. reset: function() {
  2244. this.queue = new Queue();
  2245. this.stats = this.queue.stats;
  2246. }
  2247. });
  2248. });
  2249. /**
  2250. * @fileOverview 添加获取Runtime相关信息的方法
  2251. */
  2252. define('widgets/runtime',[
  2253. 'uploader',
  2254. 'runtime/runtime',
  2255. 'widgets/widget'
  2256. ], function( Uploader, Runtime ) {
  2257. Uploader.support = function() {
  2258. return Runtime.hasRuntime.apply( Runtime, arguments );
  2259. };
  2260. return Uploader.register({
  2261. 'predict-runtime-type': 'predictRuntmeType'
  2262. }, {
  2263. init: function() {
  2264. if ( !this.predictRuntmeType() ) {
  2265. throw Error('Runtime Error');
  2266. }
  2267. },
  2268. /**
  2269. * 预测Uploader将采用哪个`Runtime`
  2270. * @grammar predictRuntmeType() => String
  2271. * @method predictRuntmeType
  2272. * @for Uploader
  2273. */
  2274. predictRuntmeType: function() {
  2275. var orders = this.options.runtimeOrder || Runtime.orders,
  2276. type = this.type,
  2277. i, len;
  2278. if ( !type ) {
  2279. orders = orders.split( /\s*,\s*/g );
  2280. for ( i = 0, len = orders.length; i < len; i++ ) {
  2281. if ( Runtime.hasRuntime( orders[ i ] ) ) {
  2282. this.type = type = orders[ i ];
  2283. break;
  2284. }
  2285. }
  2286. }
  2287. return type;
  2288. }
  2289. });
  2290. });
  2291. /**
  2292. * @fileOverview Transport
  2293. */
  2294. define('lib/transport',[
  2295. 'base',
  2296. 'runtime/client',
  2297. 'mediator'
  2298. ], function( Base, RuntimeClient, Mediator ) {
  2299. var $ = Base.$;
  2300. function Transport( opts ) {
  2301. var me = this;
  2302. opts = me.options = $.extend( true, {}, Transport.options, opts || {} );
  2303. RuntimeClient.call( this, 'Transport' );
  2304. this._blob = null;
  2305. this._formData = opts.formData || {};
  2306. this._headers = opts.headers || {};
  2307. this.on( 'progress', this._timeout );
  2308. this.on( 'load error', function() {
  2309. me.trigger( 'progress', 1 );
  2310. clearTimeout( me._timer );
  2311. });
  2312. }
  2313. Transport.options = {
  2314. server: '',
  2315. method: 'POST',
  2316. // 跨域时,是否允许携带cookie, 只有html5 runtime才有效
  2317. withCredentials: false,
  2318. fileVal: 'file',
  2319. timeout: 2 * 60 * 1000, // 2分钟
  2320. formData: {},
  2321. headers: {},
  2322. sendAsBinary: false
  2323. };
  2324. $.extend( Transport.prototype, {
  2325. // 添加Blob, 只能添加一次,最后一次有效。
  2326. appendBlob: function( key, blob, filename ) {
  2327. var me = this,
  2328. opts = me.options;
  2329. if ( me.getRuid() ) {
  2330. me.disconnectRuntime();
  2331. }
  2332. // 连接到blob归属的同一个runtime.
  2333. me.connectRuntime( blob.ruid, function() {
  2334. me.exec('init');
  2335. });
  2336. me._blob = blob;
  2337. opts.fileVal = key || opts.fileVal;
  2338. opts.filename = filename || opts.filename;
  2339. },
  2340. // 添加其他字段
  2341. append: function( key, value ) {
  2342. if ( typeof key === 'object' ) {
  2343. $.extend( this._formData, key );
  2344. } else {
  2345. this._formData[ key ] = value;
  2346. }
  2347. },
  2348. setRequestHeader: function( key, value ) {
  2349. if ( typeof key === 'object' ) {
  2350. $.extend( this._headers, key );
  2351. } else {
  2352. this._headers[ key ] = value;
  2353. }
  2354. },
  2355. send: function( method ) {
  2356. this.exec( 'send', method );
  2357. this._timeout();
  2358. },
  2359. abort: function() {
  2360. clearTimeout( this._timer );
  2361. return this.exec('abort');
  2362. },
  2363. destroy: function() {
  2364. this.trigger('destroy');
  2365. this.off();
  2366. this.exec('destroy');
  2367. this.disconnectRuntime();
  2368. },
  2369. getResponse: function() {
  2370. return this.exec('getResponse');
  2371. },
  2372. getResponseAsJson: function() {
  2373. return this.exec('getResponseAsJson');
  2374. },
  2375. getStatus: function() {
  2376. return this.exec('getStatus');
  2377. },
  2378. _timeout: function() {
  2379. var me = this,
  2380. duration = me.options.timeout;
  2381. if ( !duration ) {
  2382. return;
  2383. }
  2384. clearTimeout( me._timer );
  2385. me._timer = setTimeout(function() {
  2386. me.abort();
  2387. me.trigger( 'error', 'timeout' );
  2388. }, duration );
  2389. }
  2390. });
  2391. // 让Transport具备事件功能。
  2392. Mediator.installTo( Transport.prototype );
  2393. return Transport;
  2394. });
  2395. /**
  2396. * @fileOverview 负责文件上传相关
  2397. */
  2398. define('widgets/upload',[
  2399. 'base',
  2400. 'uploader',
  2401. 'file',
  2402. 'lib/transport',
  2403. 'widgets/widget'
  2404. ], function( Base, Uploader, WUFile, Transport ) {
  2405. var $ = Base.$,
  2406. isPromise = Base.isPromise,
  2407. Status = WUFile.Status;
  2408. // 添加默认配置项
  2409. $.extend( Uploader.options, {
  2410. /**
  2411. * @property {Boolean} [prepareNextFile=false]
  2412. * @namespace options
  2413. * @for Uploader
  2414. * @description 是否允许在文件传输时提前把下一个文件准备好
  2415. * 对于一个文件的准备工作比较耗时比如图片压缩md5序列化
  2416. * 如果能提前在当前文件传输期处理可以节省总体耗时
  2417. */
  2418. prepareNextFile: false,
  2419. /**
  2420. * @property {Boolean} [chunked=false]
  2421. * @namespace options
  2422. * @for Uploader
  2423. * @description 是否要分片处理大文件上传
  2424. */
  2425. chunked: false,
  2426. /**
  2427. * @property {Boolean} [chunkSize=5242880]
  2428. * @namespace options
  2429. * @for Uploader
  2430. * @description 如果要分片分多大一片 默认大小为5M.
  2431. */
  2432. chunkSize: 5 * 1024 * 1024,
  2433. /**
  2434. * @property {Boolean} [chunkRetry=2]
  2435. * @namespace options
  2436. * @for Uploader
  2437. * @description 如果某个分片由于网络问题出错允许自动重传多少次
  2438. */
  2439. chunkRetry: 2,
  2440. /**
  2441. * @property {Boolean} [threads=3]
  2442. * @namespace options
  2443. * @for Uploader
  2444. * @description 上传并发数允许同时最大上传进程数
  2445. */
  2446. threads: 3,
  2447. /**
  2448. * @property {Object} [formData]
  2449. * @namespace options
  2450. * @for Uploader
  2451. * @description 文件上传请求的参数表每次发送都会发送此对象中的参数
  2452. */
  2453. formData: null
  2454. /**
  2455. * @property {Object} [fileVal='file']
  2456. * @namespace options
  2457. * @for Uploader
  2458. * @description 设置文件上传域的name
  2459. */
  2460. /**
  2461. * @property {Object} [method='POST']
  2462. * @namespace options
  2463. * @for Uploader
  2464. * @description 文件上传方式`POST`或者`GET`
  2465. */
  2466. /**
  2467. * @property {Object} [sendAsBinary=false]
  2468. * @namespace options
  2469. * @for Uploader
  2470. * @description 是否已二进制的流的方式发送文件这样整个上传内容`php://input`都为文件内容
  2471. * 其他参数在$_GET数组中
  2472. */
  2473. });
  2474. // 负责将文件切片。
  2475. function CuteFile( file, chunkSize ) {
  2476. var pending = [],
  2477. blob = file.source,
  2478. total = blob.size,
  2479. chunks = chunkSize ? Math.ceil( total / chunkSize ) : 1,
  2480. start = 0,
  2481. index = 0,
  2482. len;
  2483. while ( index < chunks ) {
  2484. len = Math.min( chunkSize, total - start );
  2485. pending.push({
  2486. file: file,
  2487. start: start,
  2488. end: chunkSize ? (start + len) : total,
  2489. total: total,
  2490. chunks: chunks,
  2491. chunk: index++
  2492. });
  2493. start += len;
  2494. }
  2495. file.blocks = pending.concat();
  2496. file.remaning = pending.length;
  2497. return {
  2498. file: file,
  2499. has: function() {
  2500. return !!pending.length;
  2501. },
  2502. fetch: function() {
  2503. return pending.shift();
  2504. }
  2505. };
  2506. }
  2507. Uploader.register({
  2508. 'start-upload': 'start',
  2509. 'stop-upload': 'stop',
  2510. 'skip-file': 'skipFile',
  2511. 'is-in-progress': 'isInProgress'
  2512. }, {
  2513. init: function() {
  2514. var owner = this.owner;
  2515. this.runing = false;
  2516. // 记录当前正在传的数据,跟threads相关
  2517. this.pool = [];
  2518. // 缓存即将上传的文件。
  2519. this.pending = [];
  2520. // 跟踪还有多少分片没有完成上传。
  2521. this.remaning = 0;
  2522. this.__tick = Base.bindFn( this._tick, this );
  2523. owner.on( 'uploadComplete', function( file ) {
  2524. // 把其他块取消了。
  2525. file.blocks && $.each( file.blocks, function( _, v ) {
  2526. v.transport && (v.transport.abort(), v.transport.destroy());
  2527. delete v.transport;
  2528. });
  2529. delete file.blocks;
  2530. delete file.remaning;
  2531. });
  2532. },
  2533. /**
  2534. * @event startUpload
  2535. * @description 当开始上传流程时触发
  2536. * @for Uploader
  2537. */
  2538. /**
  2539. * 开始上传此方法可以从初始状态调用开始上传流程也可以从暂停状态调用继续上传流程
  2540. * @grammar upload() => undefined
  2541. * @method upload
  2542. * @for Uploader
  2543. */
  2544. start: function() {
  2545. var me = this;
  2546. // 移出invalid的文件
  2547. $.each( me.request( 'get-files', Status.INVALID ), function() {
  2548. me.request( 'remove-file', this );
  2549. });
  2550. if ( me.runing ) {
  2551. return;
  2552. }
  2553. me.runing = true;
  2554. // 如果有暂停的,则续传
  2555. $.each( me.pool, function( _, v ) {
  2556. var file = v.file;
  2557. if ( file.getStatus() === Status.INTERRUPT ) {
  2558. file.setStatus( Status.PROGRESS );
  2559. me._trigged = false;
  2560. v.transport && v.transport.send();
  2561. }
  2562. });
  2563. me._trigged = false;
  2564. me.owner.trigger('startUpload');
  2565. Base.nextTick( me.__tick );
  2566. },
  2567. /**
  2568. * @event stopUpload
  2569. * @description 当开始上传流程暂停时触发
  2570. * @for Uploader
  2571. */
  2572. /**
  2573. * 暂停上传第一个参数为是否中断上传当前正在上传的文件
  2574. * @grammar stop() => undefined
  2575. * @grammar stop( true ) => undefined
  2576. * @method stop
  2577. * @for Uploader
  2578. */
  2579. stop: function( interrupt ) {
  2580. var me = this;
  2581. if ( me.runing === false ) {
  2582. return;
  2583. }
  2584. me.runing = false;
  2585. interrupt && $.each( me.pool, function( _, v ) {
  2586. v.transport && v.transport.abort();
  2587. v.file.setStatus( Status.INTERRUPT );
  2588. });
  2589. me.owner.trigger('stopUpload');
  2590. },
  2591. /**
  2592. * 判断`Uplaode`r是否正在上传中
  2593. * @grammar isInProgress() => Boolean
  2594. * @method isInProgress
  2595. * @for Uploader
  2596. */
  2597. isInProgress: function() {
  2598. return !!this.runing;
  2599. },
  2600. getStats: function() {
  2601. return this.request('get-stats');
  2602. },
  2603. /**
  2604. * 掉过一个文件上传直接标记指定文件为已上传状态
  2605. * @grammar skipFile( file ) => undefined
  2606. * @method skipFile
  2607. * @for Uploader
  2608. */
  2609. skipFile: function( file, status ) {
  2610. file = this.request( 'get-file', file );
  2611. file.setStatus( status || Status.COMPLETE );
  2612. file.skipped = true;
  2613. // 如果正在上传。
  2614. file.blocks && $.each( file.blocks, function( _, v ) {
  2615. var _tr = v.transport;
  2616. if ( _tr ) {
  2617. _tr.abort();
  2618. _tr.destroy();
  2619. delete v.transport;
  2620. }
  2621. });
  2622. this.owner.trigger( 'uploadSkip', file );
  2623. },
  2624. /**
  2625. * @event uploadFinished
  2626. * @description 当所有文件上传结束时触发
  2627. * @for Uploader
  2628. */
  2629. _tick: function() {
  2630. var me = this,
  2631. opts = me.options,
  2632. fn, val;
  2633. // 上一个promise还没有结束,则等待完成后再执行。
  2634. if ( me._promise ) {
  2635. return me._promise.always( me.__tick );
  2636. }
  2637. // 还有位置,且还有文件要处理的话。
  2638. if ( me.pool.length < opts.threads && (val = me._nextBlock()) ) {
  2639. me._trigged = false;
  2640. fn = function( val ) {
  2641. me._promise = null;
  2642. // 有可能是reject过来的,所以要检测val的类型。
  2643. val && val.file && me._startSend( val );
  2644. Base.nextTick( me.__tick );
  2645. };
  2646. me._promise = isPromise( val ) ? val.always( fn ) : fn( val );
  2647. // 没有要上传的了,且没有正在传输的了。
  2648. } else if ( !me.remaning && !me.getStats().numOfQueue ) {
  2649. me.runing = false;
  2650. me._trigged || Base.nextTick(function() {
  2651. me.owner.trigger('uploadFinished');
  2652. });
  2653. me._trigged = true;
  2654. }
  2655. },
  2656. _nextBlock: function() {
  2657. var me = this,
  2658. act = me._act,
  2659. opts = me.options,
  2660. next, done;
  2661. // 如果当前文件还有没有需要传输的,则直接返回剩下的。
  2662. if ( act && act.has() &&
  2663. act.file.getStatus() === Status.PROGRESS ) {
  2664. // 是否提前准备下一个文件
  2665. if ( opts.prepareNextFile && !me.pending.length ) {
  2666. me._prepareNextFile();
  2667. }
  2668. return act.fetch();
  2669. // 否则,如果正在运行,则准备下一个文件,并等待完成后返回下个分片。
  2670. } else if ( me.runing ) {
  2671. // 如果缓存中有,则直接在缓存中取,没有则去queue中取。
  2672. if ( !me.pending.length && me.getStats().numOfQueue ) {
  2673. me._prepareNextFile();
  2674. }
  2675. next = me.pending.shift();
  2676. done = function( file ) {
  2677. if ( !file ) {
  2678. return null;
  2679. }
  2680. act = CuteFile( file, opts.chunked ? opts.chunkSize : 0 );
  2681. me._act = act;
  2682. return act.fetch();
  2683. };
  2684. // 文件可能还在prepare中,也有可能已经完全准备好了。
  2685. return isPromise( next ) ?
  2686. next[ next.pipe ? 'pipe' : 'then']( done ) :
  2687. done( next );
  2688. }
  2689. },
  2690. /**
  2691. * @event uploadStart
  2692. * @param {File} file File对象
  2693. * @description 某个文件开始上传前触发一个文件只会触发一次
  2694. * @for Uploader
  2695. */
  2696. _prepareNextFile: function() {
  2697. var me = this,
  2698. file = me.request('fetch-file'),
  2699. pending = me.pending,
  2700. promise;
  2701. if ( file ) {
  2702. promise = me.request( 'before-send-file', file, function() {
  2703. // 有可能文件被skip掉了。文件被skip掉后,状态坑定不是Queued.
  2704. if ( file.getStatus() === Status.QUEUED ) {
  2705. me.owner.trigger( 'uploadStart', file );
  2706. file.setStatus( Status.PROGRESS );
  2707. return file;
  2708. }
  2709. return me._finishFile( file );
  2710. });
  2711. // 如果还在pending中,则替换成文件本身。
  2712. promise.done(function() {
  2713. var idx = $.inArray( promise, pending );
  2714. ~idx && pending.splice( idx, 1, file );
  2715. });
  2716. // befeore-send-file的钩子就有错误发生。
  2717. promise.fail(function( reason ) {
  2718. file.setStatus( Status.ERROR, reason );
  2719. me.owner.trigger( 'uploadError', file, reason );
  2720. me.owner.trigger( 'uploadComplete', file );
  2721. });
  2722. pending.push( promise );
  2723. }
  2724. },
  2725. // 让出位置了,可以让其他分片开始上传
  2726. _popBlock: function( block ) {
  2727. var idx = $.inArray( block, this.pool );
  2728. this.pool.splice( idx, 1 );
  2729. block.file.remaning--;
  2730. this.remaning--;
  2731. },
  2732. // 开始上传,可以被掉过。如果promise被reject了,则表示跳过此分片。
  2733. _startSend: function( block ) {
  2734. var me = this,
  2735. file = block.file,
  2736. promise;
  2737. me.pool.push( block );
  2738. me.remaning++;
  2739. // 如果没有分片,则直接使用原始的。
  2740. // 不会丢失content-type信息。
  2741. block.blob = block.chunks === 1 ? file.source :
  2742. file.source.slice( block.start, block.end );
  2743. // hook, 每个分片发送之前可能要做些异步的事情。
  2744. promise = me.request( 'before-send', block, function() {
  2745. // 有可能文件已经上传出错了,所以不需要再传输了。
  2746. if ( file.getStatus() === Status.PROGRESS ) {
  2747. me._doSend( block );
  2748. } else {
  2749. me._popBlock( block );
  2750. Base.nextTick( me.__tick );
  2751. }
  2752. });
  2753. // 如果为fail了,则跳过此分片。
  2754. promise.fail(function() {
  2755. if ( file.remaning === 1 ) {
  2756. me._finishFile( file ).always(function() {
  2757. block.percentage = 1;
  2758. me._popBlock( block );
  2759. me.owner.trigger( 'uploadComplete', file );
  2760. Base.nextTick( me.__tick );
  2761. });
  2762. } else {
  2763. block.percentage = 1;
  2764. me._popBlock( block );
  2765. Base.nextTick( me.__tick );
  2766. }
  2767. });
  2768. },
  2769. /**
  2770. * @event uploadBeforeSend
  2771. * @param {Object} object
  2772. * @param {Object} data 默认的上传参数可以扩展此对象来控制上传参数
  2773. * @description 当某个文件的分块在发送前触发主要用来询问是否要添加附带参数大文件在开起分片上传的前提下此事件可能会触发多次
  2774. * @for Uploader
  2775. */
  2776. /**
  2777. * @event uploadAccept
  2778. * @param {Object} object
  2779. * @param {Object} ret 服务端的返回数据json格式如果服务端不是json格式从ret._raw中取数据自行解析
  2780. * @description 当某个文件上传到服务端响应后会派送此事件来询问服务端响应是否有效如果此事件handler返回值为`false`, 则此文件将派送`server`类型的`uploadError`事件
  2781. * @for Uploader
  2782. */
  2783. /**
  2784. * @event uploadProgress
  2785. * @param {File} file File对象
  2786. * @param {Number} percentage 上传进度
  2787. * @description 上传过程中触发携带上传进度
  2788. * @for Uploader
  2789. */
  2790. /**
  2791. * @event uploadError
  2792. * @param {File} file File对象
  2793. * @param {String} reason 出错的code
  2794. * @description 当文件上传出错时触发
  2795. * @for Uploader
  2796. */
  2797. /**
  2798. * @event uploadSuccess
  2799. * @param {File} file File对象
  2800. * @param {Object} response 服务端返回的数据
  2801. * @description 当文件上传成功时触发
  2802. * @for Uploader
  2803. */
  2804. /**
  2805. * @event uploadComplete
  2806. * @param {File} [file] File对象
  2807. * @description 不管成功或者失败文件上传完成时触发
  2808. * @for Uploader
  2809. */
  2810. // 做上传操作。
  2811. _doSend: function( block ) {
  2812. var me = this,
  2813. owner = me.owner,
  2814. opts = me.options,
  2815. file = block.file,
  2816. tr = new Transport( opts ),
  2817. data = $.extend({}, opts.formData ),
  2818. headers = $.extend({}, opts.headers ),
  2819. requestAccept, ret;
  2820. block.transport = tr;
  2821. tr.on( 'destroy', function() {
  2822. delete block.transport;
  2823. me._popBlock( block );
  2824. Base.nextTick( me.__tick );
  2825. });
  2826. // 广播上传进度。以文件为单位。
  2827. tr.on( 'progress', function( percentage ) {
  2828. var totalPercent = 0,
  2829. uploaded = 0;
  2830. // 可能没有abort掉,progress还是执行进来了。
  2831. // if ( !file.blocks ) {
  2832. // return;
  2833. // }
  2834. totalPercent = block.percentage = percentage;
  2835. if ( block.chunks > 1 ) { // 计算文件的整体速度。
  2836. $.each( file.blocks, function( _, v ) {
  2837. uploaded += (v.percentage || 0) * (v.end - v.start);
  2838. });
  2839. totalPercent = uploaded / file.size;
  2840. }
  2841. owner.trigger( 'uploadProgress', file, totalPercent || 0 );
  2842. });
  2843. // 用来询问,是否返回的结果是有错误的。
  2844. requestAccept = function( reject ) {
  2845. var fn;
  2846. ret = tr.getResponseAsJson() || {};
  2847. ret._raw = tr.getResponse();
  2848. fn = function( value ) {
  2849. reject = value;
  2850. };
  2851. // 服务端响应了,不代表成功了,询问是否响应正确。
  2852. if ( !owner.trigger( 'uploadAccept', block, ret, fn ) ) {
  2853. reject = reject || 'server';
  2854. }
  2855. return reject;
  2856. };
  2857. // 尝试重试,然后广播文件上传出错。
  2858. tr.on( 'error', function( type, flag ) {
  2859. block.retried = block.retried || 0;
  2860. // 自动重试
  2861. if ( block.chunks > 1 && ~'http,abort'.indexOf( type ) &&
  2862. block.retried < opts.chunkRetry ) {
  2863. block.retried++;
  2864. tr.send();
  2865. } else {
  2866. // http status 500 ~ 600
  2867. if ( !flag && type === 'server' ) {
  2868. type = requestAccept( type );
  2869. }
  2870. file.setStatus( Status.ERROR, type );
  2871. owner.trigger( 'uploadError', file, type );
  2872. owner.trigger( 'uploadComplete', file );
  2873. }
  2874. });
  2875. // 上传成功
  2876. tr.on( 'load', function() {
  2877. var reason;
  2878. // 如果非预期,转向上传出错。
  2879. if ( (reason = requestAccept()) ) {
  2880. tr.trigger( 'error', reason, true );
  2881. return;
  2882. }
  2883. // 全部上传完成。
  2884. if ( file.remaning === 1 ) {
  2885. me._finishFile( file, ret );
  2886. } else {
  2887. tr.destroy();
  2888. }
  2889. });
  2890. // 配置默认的上传字段。
  2891. data = $.extend( data, {
  2892. id: file.id,
  2893. name: file.name,
  2894. type: file.type,
  2895. lastModifiedDate: file.lastModifiedDate,
  2896. size: file.size
  2897. });
  2898. block.chunks > 1 && $.extend( data, {
  2899. chunks: block.chunks,
  2900. chunk: block.chunk
  2901. });
  2902. // 在发送之间可以添加字段什么的。。。
  2903. // 如果默认的字段不够使用,可以通过监听此事件来扩展
  2904. owner.trigger( 'uploadBeforeSend', block, data, headers );
  2905. // 开始发送。
  2906. tr.appendBlob( opts.fileVal, block.blob, file.name );
  2907. tr.append( data );
  2908. tr.setRequestHeader( headers );
  2909. tr.send();
  2910. },
  2911. // 完成上传。
  2912. _finishFile: function( file, ret, hds ) {
  2913. var owner = this.owner;
  2914. return owner
  2915. .request( 'after-send-file', arguments, function() {
  2916. file.setStatus( Status.COMPLETE );
  2917. owner.trigger( 'uploadSuccess', file, ret, hds );
  2918. })
  2919. .fail(function( reason ) {
  2920. // 如果外部已经标记为invalid什么的,不再改状态。
  2921. if ( file.getStatus() === Status.PROGRESS ) {
  2922. file.setStatus( Status.ERROR, reason );
  2923. }
  2924. owner.trigger( 'uploadError', file, reason );
  2925. })
  2926. .always(function() {
  2927. owner.trigger( 'uploadComplete', file );
  2928. });
  2929. }
  2930. });
  2931. });
  2932. /**
  2933. * @fileOverview Runtime管理器负责Runtime的选择, 连接
  2934. */
  2935. define('runtime/compbase',[],function() {
  2936. function CompBase( owner, runtime ) {
  2937. this.owner = owner;
  2938. this.options = owner.options;
  2939. this.getRuntime = function() {
  2940. return runtime;
  2941. };
  2942. this.getRuid = function() {
  2943. return runtime.uid;
  2944. };
  2945. this.trigger = function() {
  2946. return owner.trigger.apply( owner, arguments );
  2947. };
  2948. }
  2949. return CompBase;
  2950. });
  2951. /**
  2952. * @fileOverview Html5Runtime
  2953. */
  2954. define('runtime/html5/runtime',[
  2955. 'base',
  2956. 'runtime/runtime',
  2957. 'runtime/compbase'
  2958. ], function( Base, Runtime, CompBase ) {
  2959. var type = 'html5',
  2960. components = {};
  2961. function Html5Runtime() {
  2962. var pool = {},
  2963. me = this,
  2964. destory = this.destory;
  2965. Runtime.apply( me, arguments );
  2966. me.type = type;
  2967. // 这个方法的调用者,实际上是RuntimeClient
  2968. me.exec = function( comp, fn/*, args...*/) {
  2969. var client = this,
  2970. uid = client.uid,
  2971. args = Base.slice( arguments, 2 ),
  2972. instance;
  2973. if ( components[ comp ] ) {
  2974. instance = pool[ uid ] = pool[ uid ] ||
  2975. new components[ comp ]( client, me );
  2976. if ( instance[ fn ] ) {
  2977. return instance[ fn ].apply( instance, args );
  2978. }
  2979. }
  2980. };
  2981. me.destory = function() {
  2982. // @todo 删除池子中的所有实例
  2983. return destory && destory.apply( this, arguments );
  2984. };
  2985. }
  2986. Base.inherits( Runtime, {
  2987. constructor: Html5Runtime,
  2988. // 不需要连接其他程序,直接执行callback
  2989. init: function() {
  2990. var me = this;
  2991. setTimeout(function() {
  2992. me.trigger('ready');
  2993. }, 1 );
  2994. }
  2995. });
  2996. // 注册Components
  2997. Html5Runtime.register = function( name, component ) {
  2998. var klass = components[ name ] = Base.inherits( CompBase, component );
  2999. return klass;
  3000. };
  3001. // 注册html5运行时。
  3002. // 只有在支持的前提下注册。
  3003. if ( window.Blob && window.FileReader && window.DataView ) {
  3004. Runtime.addRuntime( type, Html5Runtime );
  3005. }
  3006. return Html5Runtime;
  3007. });
  3008. /**
  3009. * @fileOverview Blob Html实现
  3010. */
  3011. define('runtime/html5/blob',[
  3012. 'runtime/html5/runtime',
  3013. 'lib/blob'
  3014. ], function( Html5Runtime, Blob ) {
  3015. return Html5Runtime.register( 'Blob', {
  3016. slice: function( start, end ) {
  3017. var blob = this.owner.source,
  3018. slice = blob.slice || blob.webkitSlice || blob.mozSlice;
  3019. blob = slice.call( blob, start, end );
  3020. return new Blob( this.getRuid(), blob );
  3021. }
  3022. });
  3023. });
  3024. /**
  3025. * @fileOverview FilePicker
  3026. */
  3027. define('runtime/html5/filepicker',[
  3028. 'base',
  3029. 'runtime/html5/runtime'
  3030. ], function( Base, Html5Runtime ) {
  3031. var $ = Base.$;
  3032. return Html5Runtime.register( 'FilePicker', {
  3033. init: function() {
  3034. var container = this.getRuntime().getContainer(),
  3035. me = this,
  3036. owner = me.owner,
  3037. opts = me.options,
  3038. lable = $( document.createElement('label') ),
  3039. input = $( document.createElement('input') ),
  3040. arr, i, len, mouseHandler;
  3041. input.attr( 'type', 'file' );
  3042. input.attr( 'name', opts.name );
  3043. input.addClass('webuploader-element-invisible');
  3044. lable.on( 'click', function() {
  3045. input.trigger('click');
  3046. });
  3047. lable.css({
  3048. opacity: 0,
  3049. width: '100%',
  3050. height: '100%',
  3051. display: 'block',
  3052. cursor: 'pointer',
  3053. background: '#ffffff'
  3054. });
  3055. if ( opts.multiple ) {
  3056. input.attr( 'multiple', 'multiple' );
  3057. }
  3058. // @todo Firefox不支持单独指定后缀
  3059. if ( opts.accept && opts.accept.length > 0 ) {
  3060. arr = [];
  3061. for ( i = 0, len = opts.accept.length; i < len; i++ ) {
  3062. arr.push( opts.accept[ i ].mimeTypes );
  3063. }
  3064. input.attr( 'accept', arr.join(',') );
  3065. }
  3066. container.append( input );
  3067. container.append( lable );
  3068. mouseHandler = function( e ) {
  3069. owner.trigger( e.type );
  3070. };
  3071. input.on( 'change', function( e ) {
  3072. var fn = arguments.callee,
  3073. clone;
  3074. me.files = e.target.files;
  3075. // reset input
  3076. clone = this.cloneNode( true );
  3077. this.parentNode.replaceChild( clone, this );
  3078. input.off();
  3079. input = $( clone ).on( 'change', fn )
  3080. .on( 'mouseenter mouseleave', mouseHandler );
  3081. owner.trigger('change');
  3082. });
  3083. lable.on( 'mouseenter mouseleave', mouseHandler );
  3084. },
  3085. getFiles: function() {
  3086. return this.files;
  3087. },
  3088. destroy: function() {
  3089. // todo
  3090. }
  3091. });
  3092. });
  3093. /**
  3094. * Terms:
  3095. *
  3096. * Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
  3097. * @fileOverview Image控件
  3098. */
  3099. define('runtime/html5/util',[
  3100. 'base'
  3101. ], function( Base ) {
  3102. var urlAPI = window.createObjectURL && window ||
  3103. window.URL && URL.revokeObjectURL && URL ||
  3104. window.webkitURL,
  3105. createObjectURL = Base.noop,
  3106. revokeObjectURL = createObjectURL;
  3107. if ( urlAPI ) {
  3108. // 更安全的方式调用,比如android里面就能把context改成其他的对象。
  3109. createObjectURL = function() {
  3110. return urlAPI.createObjectURL.apply( urlAPI, arguments );
  3111. };
  3112. revokeObjectURL = function() {
  3113. return urlAPI.revokeObjectURL.apply( urlAPI, arguments );
  3114. };
  3115. }
  3116. return {
  3117. createObjectURL: createObjectURL,
  3118. revokeObjectURL: revokeObjectURL,
  3119. dataURL2Blob: function( dataURI ) {
  3120. var byteStr, intArray, ab, i, mimetype, parts;
  3121. parts = dataURI.split(',');
  3122. if ( ~parts[ 0 ].indexOf('base64') ) {
  3123. byteStr = atob( parts[ 1 ] );
  3124. } else {
  3125. byteStr = decodeURIComponent( parts[ 1 ] );
  3126. }
  3127. ab = new ArrayBuffer( byteStr.length );
  3128. intArray = new Uint8Array( ab );
  3129. for ( i = 0; i < byteStr.length; i++ ) {
  3130. intArray[ i ] = byteStr.charCodeAt( i );
  3131. }
  3132. mimetype = parts[ 0 ].split(':')[ 1 ].split(';')[ 0 ];
  3133. return this.arrayBufferToBlob( ab, mimetype );
  3134. },
  3135. dataURL2ArrayBuffer: function( dataURI ) {
  3136. var byteStr, intArray, i, parts;
  3137. parts = dataURI.split(',');
  3138. if ( ~parts[ 0 ].indexOf('base64') ) {
  3139. byteStr = atob( parts[ 1 ] );
  3140. } else {
  3141. byteStr = decodeURIComponent( parts[ 1 ] );
  3142. }
  3143. intArray = new Uint8Array( byteStr.length );
  3144. for ( i = 0; i < byteStr.length; i++ ) {
  3145. intArray[ i ] = byteStr.charCodeAt( i );
  3146. }
  3147. return intArray.buffer;
  3148. },
  3149. arrayBufferToBlob: function( buffer, type ) {
  3150. var builder = window.BlobBuilder || window.WebKitBlobBuilder,
  3151. bb;
  3152. // android不支持直接new Blob, 只能借助blobbuilder.
  3153. if ( builder ) {
  3154. bb = new builder();
  3155. bb.append( buffer );
  3156. return bb.getBlob( type );
  3157. }
  3158. return new Blob([ buffer ], type ? { type: type } : {} );
  3159. },
  3160. // 抽出来主要是为了解决android下面canvas.toDataUrl不支持jpeg.
  3161. // 你得到的结果是png.
  3162. canvasToDataUrl: function( canvas, type, quality ) {
  3163. return canvas.toDataURL( type, quality / 100 );
  3164. },
  3165. // imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
  3166. parseMeta: function( blob, callback ) {
  3167. callback( false, {});
  3168. },
  3169. // imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
  3170. updateImageHead: function( data ) {
  3171. return data;
  3172. }
  3173. };
  3174. });
  3175. /**
  3176. * Terms:
  3177. *
  3178. * Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
  3179. * @fileOverview Image控件
  3180. */
  3181. define('runtime/html5/imagemeta',[
  3182. 'runtime/html5/util'
  3183. ], function( Util ) {
  3184. var api;
  3185. api = {
  3186. parsers: {
  3187. 0xffe1: []
  3188. },
  3189. maxMetaDataSize: 262144,
  3190. parse: function( blob, cb ) {
  3191. var me = this,
  3192. fr = new FileReader();
  3193. fr.onload = function() {
  3194. cb( false, me._parse( this.result ) );
  3195. fr = fr.onload = fr.onerror = null;
  3196. };
  3197. fr.onerror = function( e ) {
  3198. cb( e.message );
  3199. fr = fr.onload = fr.onerror = null;
  3200. };
  3201. blob = blob.slice( 0, me.maxMetaDataSize );
  3202. fr.readAsArrayBuffer( blob.getSource() );
  3203. },
  3204. _parse: function( buffer, noParse ) {
  3205. if ( buffer.byteLength < 6 ) {
  3206. return;
  3207. }
  3208. var dataview = new DataView( buffer ),
  3209. offset = 2,
  3210. maxOffset = dataview.byteLength - 4,
  3211. headLength = offset,
  3212. ret = {},
  3213. markerBytes, markerLength, parsers, i;
  3214. if ( dataview.getUint16( 0 ) === 0xffd8 ) {
  3215. while ( offset < maxOffset ) {
  3216. markerBytes = dataview.getUint16( offset );
  3217. if ( markerBytes >= 0xffe0 && markerBytes <= 0xffef ||
  3218. markerBytes === 0xfffe ) {
  3219. markerLength = dataview.getUint16( offset + 2 ) + 2;
  3220. if ( offset + markerLength > dataview.byteLength ) {
  3221. break;
  3222. }
  3223. parsers = api.parsers[ markerBytes ];
  3224. if ( !noParse && parsers ) {
  3225. for ( i = 0; i < parsers.length; i += 1 ) {
  3226. parsers[ i ].call( api, dataview, offset,
  3227. markerLength, ret );
  3228. }
  3229. }
  3230. offset += markerLength;
  3231. headLength = offset;
  3232. } else {
  3233. break;
  3234. }
  3235. }
  3236. if ( headLength > 6 ) {
  3237. if ( buffer.slice ) {
  3238. ret.imageHead = buffer.slice( 2, headLength );
  3239. } else {
  3240. // Workaround for IE10, which does not yet
  3241. // support ArrayBuffer.slice:
  3242. ret.imageHead = new Uint8Array( buffer )
  3243. .subarray( 2, headLength );
  3244. }
  3245. }
  3246. }
  3247. return ret;
  3248. },
  3249. updateImageHead: function( buffer, head ) {
  3250. var data = this._parse( buffer, true ),
  3251. buf1, buf2, bodyoffset;
  3252. bodyoffset = 2;
  3253. if ( data.imageHead ) {
  3254. bodyoffset = 2 + data.imageHead.byteLength;
  3255. }
  3256. if ( buffer.slice ) {
  3257. buf2 = buffer.slice( bodyoffset );
  3258. } else {
  3259. buf2 = new Uint8Array( buffer ).subarray( bodyoffset );
  3260. }
  3261. buf1 = new Uint8Array( head.byteLength + 2 + buf2.byteLength );
  3262. buf1[ 0 ] = 0xFF;
  3263. buf1[ 1 ] = 0xD8;
  3264. buf1.set( new Uint8Array( head ), 2 );
  3265. buf1.set( new Uint8Array( buf2 ), head.byteLength + 2 );
  3266. return buf1.buffer;
  3267. }
  3268. };
  3269. Util.parseMeta = function() {
  3270. return api.parse.apply( api, arguments );
  3271. };
  3272. Util.updateImageHead = function() {
  3273. return api.updateImageHead.apply( api, arguments );
  3274. };
  3275. return api;
  3276. });
  3277. /**
  3278. * 代码来自于https://github.com/blueimp/JavaScript-Load-Image
  3279. * 暂时项目中只用了orientation.
  3280. *
  3281. * 去除了 Exif Sub IFD Pointer, GPS Info IFD Pointer, Exif Thumbnail.
  3282. * @fileOverview EXIF解析
  3283. */
  3284. // Sample
  3285. // ====================================
  3286. // Make : Apple
  3287. // Model : iPhone 4S
  3288. // Orientation : 1
  3289. // XResolution : 72 [72/1]
  3290. // YResolution : 72 [72/1]
  3291. // ResolutionUnit : 2
  3292. // Software : QuickTime 7.7.1
  3293. // DateTime : 2013:09:01 22:53:55
  3294. // ExifIFDPointer : 190
  3295. // ExposureTime : 0.058823529411764705 [1/17]
  3296. // FNumber : 2.4 [12/5]
  3297. // ExposureProgram : Normal program
  3298. // ISOSpeedRatings : 800
  3299. // ExifVersion : 0220
  3300. // DateTimeOriginal : 2013:09:01 22:52:51
  3301. // DateTimeDigitized : 2013:09:01 22:52:51
  3302. // ComponentsConfiguration : YCbCr
  3303. // ShutterSpeedValue : 4.058893515764426
  3304. // ApertureValue : 2.5260688216892597 [4845/1918]
  3305. // BrightnessValue : -0.3126686601998395
  3306. // MeteringMode : Pattern
  3307. // Flash : Flash did not fire, compulsory flash mode
  3308. // FocalLength : 4.28 [107/25]
  3309. // SubjectArea : [4 values]
  3310. // FlashpixVersion : 0100
  3311. // ColorSpace : 1
  3312. // PixelXDimension : 2448
  3313. // PixelYDimension : 3264
  3314. // SensingMethod : One-chip color area sensor
  3315. // ExposureMode : 0
  3316. // WhiteBalance : Auto white balance
  3317. // FocalLengthIn35mmFilm : 35
  3318. // SceneCaptureType : Standard
  3319. define('runtime/html5/imagemeta/exif',[
  3320. 'base',
  3321. 'runtime/html5/imagemeta'
  3322. ], function( Base, ImageMeta ) {
  3323. var EXIF = {};
  3324. EXIF.ExifMap = function() {
  3325. return this;
  3326. };
  3327. EXIF.ExifMap.prototype.map = {
  3328. 'Orientation': 0x0112
  3329. };
  3330. EXIF.ExifMap.prototype.get = function( id ) {
  3331. return this[ id ] || this[ this.map[ id ] ];
  3332. };
  3333. EXIF.exifTagTypes = {
  3334. // byte, 8-bit unsigned int:
  3335. 1: {
  3336. getValue: function( dataView, dataOffset ) {
  3337. return dataView.getUint8( dataOffset );
  3338. },
  3339. size: 1
  3340. },
  3341. // ascii, 8-bit byte:
  3342. 2: {
  3343. getValue: function( dataView, dataOffset ) {
  3344. return String.fromCharCode( dataView.getUint8( dataOffset ) );
  3345. },
  3346. size: 1,
  3347. ascii: true
  3348. },
  3349. // short, 16 bit int:
  3350. 3: {
  3351. getValue: function( dataView, dataOffset, littleEndian ) {
  3352. return dataView.getUint16( dataOffset, littleEndian );
  3353. },
  3354. size: 2
  3355. },
  3356. // long, 32 bit int:
  3357. 4: {
  3358. getValue: function( dataView, dataOffset, littleEndian ) {
  3359. return dataView.getUint32( dataOffset, littleEndian );
  3360. },
  3361. size: 4
  3362. },
  3363. // rational = two long values,
  3364. // first is numerator, second is denominator:
  3365. 5: {
  3366. getValue: function( dataView, dataOffset, littleEndian ) {
  3367. return dataView.getUint32( dataOffset, littleEndian ) /
  3368. dataView.getUint32( dataOffset + 4, littleEndian );
  3369. },
  3370. size: 8
  3371. },
  3372. // slong, 32 bit signed int:
  3373. 9: {
  3374. getValue: function( dataView, dataOffset, littleEndian ) {
  3375. return dataView.getInt32( dataOffset, littleEndian );
  3376. },
  3377. size: 4
  3378. },
  3379. // srational, two slongs, first is numerator, second is denominator:
  3380. 10: {
  3381. getValue: function( dataView, dataOffset, littleEndian ) {
  3382. return dataView.getInt32( dataOffset, littleEndian ) /
  3383. dataView.getInt32( dataOffset + 4, littleEndian );
  3384. },
  3385. size: 8
  3386. }
  3387. };
  3388. // undefined, 8-bit byte, value depending on field:
  3389. EXIF.exifTagTypes[ 7 ] = EXIF.exifTagTypes[ 1 ];
  3390. EXIF.getExifValue = function( dataView, tiffOffset, offset, type, length,
  3391. littleEndian ) {
  3392. var tagType = EXIF.exifTagTypes[ type ],
  3393. tagSize, dataOffset, values, i, str, c;
  3394. if ( !tagType ) {
  3395. Base.log('Invalid Exif data: Invalid tag type.');
  3396. return;
  3397. }
  3398. tagSize = tagType.size * length;
  3399. // Determine if the value is contained in the dataOffset bytes,
  3400. // or if the value at the dataOffset is a pointer to the actual data:
  3401. dataOffset = tagSize > 4 ? tiffOffset + dataView.getUint32( offset + 8,
  3402. littleEndian ) : (offset + 8);
  3403. if ( dataOffset + tagSize > dataView.byteLength ) {
  3404. Base.log('Invalid Exif data: Invalid data offset.');
  3405. return;
  3406. }
  3407. if ( length === 1 ) {
  3408. return tagType.getValue( dataView, dataOffset, littleEndian );
  3409. }
  3410. values = [];
  3411. for ( i = 0; i < length; i += 1 ) {
  3412. values[ i ] = tagType.getValue( dataView,
  3413. dataOffset + i * tagType.size, littleEndian );
  3414. }
  3415. if ( tagType.ascii ) {
  3416. str = '';
  3417. // Concatenate the chars:
  3418. for ( i = 0; i < values.length; i += 1 ) {
  3419. c = values[ i ];
  3420. // Ignore the terminating NULL byte(s):
  3421. if ( c === '\u0000' ) {
  3422. break;
  3423. }
  3424. str += c;
  3425. }
  3426. return str;
  3427. }
  3428. return values;
  3429. };
  3430. EXIF.parseExifTag = function( dataView, tiffOffset, offset, littleEndian,
  3431. data ) {
  3432. var tag = dataView.getUint16( offset, littleEndian );
  3433. data.exif[ tag ] = EXIF.getExifValue( dataView, tiffOffset, offset,
  3434. dataView.getUint16( offset + 2, littleEndian ), // tag type
  3435. dataView.getUint32( offset + 4, littleEndian ), // tag length
  3436. littleEndian );
  3437. };
  3438. EXIF.parseExifTags = function( dataView, tiffOffset, dirOffset,
  3439. littleEndian, data ) {
  3440. var tagsNumber, dirEndOffset, i;
  3441. if ( dirOffset + 6 > dataView.byteLength ) {
  3442. Base.log('Invalid Exif data: Invalid directory offset.');
  3443. return;
  3444. }
  3445. tagsNumber = dataView.getUint16( dirOffset, littleEndian );
  3446. dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
  3447. if ( dirEndOffset + 4 > dataView.byteLength ) {
  3448. Base.log('Invalid Exif data: Invalid directory size.');
  3449. return;
  3450. }
  3451. for ( i = 0; i < tagsNumber; i += 1 ) {
  3452. this.parseExifTag( dataView, tiffOffset,
  3453. dirOffset + 2 + 12 * i, // tag offset
  3454. littleEndian, data );
  3455. }
  3456. // Return the offset to the next directory:
  3457. return dataView.getUint32( dirEndOffset, littleEndian );
  3458. };
  3459. // EXIF.getExifThumbnail = function(dataView, offset, length) {
  3460. // var hexData,
  3461. // i,
  3462. // b;
  3463. // if (!length || offset + length > dataView.byteLength) {
  3464. // Base.log('Invalid Exif data: Invalid thumbnail data.');
  3465. // return;
  3466. // }
  3467. // hexData = [];
  3468. // for (i = 0; i < length; i += 1) {
  3469. // b = dataView.getUint8(offset + i);
  3470. // hexData.push((b < 16 ? '0' : '') + b.toString(16));
  3471. // }
  3472. // return 'data:image/jpeg,%' + hexData.join('%');
  3473. // };
  3474. EXIF.parseExifData = function( dataView, offset, length, data ) {
  3475. var tiffOffset = offset + 10,
  3476. littleEndian, dirOffset;
  3477. // Check for the ASCII code for "Exif" (0x45786966):
  3478. if ( dataView.getUint32( offset + 4 ) !== 0x45786966 ) {
  3479. // No Exif data, might be XMP data instead
  3480. return;
  3481. }
  3482. if ( tiffOffset + 8 > dataView.byteLength ) {
  3483. Base.log('Invalid Exif data: Invalid segment size.');
  3484. return;
  3485. }
  3486. // Check for the two null bytes:
  3487. if ( dataView.getUint16( offset + 8 ) !== 0x0000 ) {
  3488. Base.log('Invalid Exif data: Missing byte alignment offset.');
  3489. return;
  3490. }
  3491. // Check the byte alignment:
  3492. switch ( dataView.getUint16( tiffOffset ) ) {
  3493. case 0x4949:
  3494. littleEndian = true;
  3495. break;
  3496. case 0x4D4D:
  3497. littleEndian = false;
  3498. break;
  3499. default:
  3500. Base.log('Invalid Exif data: Invalid byte alignment marker.');
  3501. return;
  3502. }
  3503. // Check for the TIFF tag marker (0x002A):
  3504. if ( dataView.getUint16( tiffOffset + 2, littleEndian ) !== 0x002A ) {
  3505. Base.log('Invalid Exif data: Missing TIFF marker.');
  3506. return;
  3507. }
  3508. // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
  3509. dirOffset = dataView.getUint32( tiffOffset + 4, littleEndian );
  3510. // Create the exif object to store the tags:
  3511. data.exif = new EXIF.ExifMap();
  3512. // Parse the tags of the main image directory and retrieve the
  3513. // offset to the next directory, usually the thumbnail directory:
  3514. dirOffset = EXIF.parseExifTags( dataView, tiffOffset,
  3515. tiffOffset + dirOffset, littleEndian, data );
  3516. // 尝试读取缩略图
  3517. // if ( dirOffset ) {
  3518. // thumbnailData = {exif: {}};
  3519. // dirOffset = EXIF.parseExifTags(
  3520. // dataView,
  3521. // tiffOffset,
  3522. // tiffOffset + dirOffset,
  3523. // littleEndian,
  3524. // thumbnailData
  3525. // );
  3526. // // Check for JPEG Thumbnail offset:
  3527. // if (thumbnailData.exif[0x0201]) {
  3528. // data.exif.Thumbnail = EXIF.getExifThumbnail(
  3529. // dataView,
  3530. // tiffOffset + thumbnailData.exif[0x0201],
  3531. // thumbnailData.exif[0x0202] // Thumbnail data length
  3532. // );
  3533. // }
  3534. // }
  3535. };
  3536. ImageMeta.parsers[ 0xffe1 ].push( EXIF.parseExifData );
  3537. return EXIF;
  3538. });
  3539. /**
  3540. * @fileOverview Image
  3541. */
  3542. define('runtime/html5/image',[
  3543. 'base',
  3544. 'runtime/html5/runtime',
  3545. 'runtime/html5/util'
  3546. ], function( Base, Html5Runtime, Util ) {
  3547. var BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D';
  3548. return Html5Runtime.register( 'Image', {
  3549. // flag: 标记是否被修改过。
  3550. modified: false,
  3551. init: function() {
  3552. var me = this,
  3553. img = new Image();
  3554. img.onload = function() {
  3555. me._info = {
  3556. type: me.type,
  3557. width: this.width,
  3558. height: this.height
  3559. };
  3560. // 读取meta信息。
  3561. if ( !me._metas && 'image/jpeg' === me.type ) {
  3562. Util.parseMeta( me._blob, function( error, ret ) {
  3563. me._metas = ret;
  3564. me.owner.trigger('load');
  3565. });
  3566. } else {
  3567. me.owner.trigger('load');
  3568. }
  3569. };
  3570. img.onerror = function() {
  3571. me.owner.trigger('error');
  3572. };
  3573. me._img = img;
  3574. },
  3575. loadFromBlob: function( blob ) {
  3576. var me = this,
  3577. img = me._img;
  3578. me._blob = blob;
  3579. me.type = blob.type;
  3580. img.src = Util.createObjectURL( blob.getSource() );
  3581. me.owner.once( 'load', function() {
  3582. Util.revokeObjectURL( img.src );
  3583. });
  3584. },
  3585. resize: function( width, height ) {
  3586. var canvas = this._canvas ||
  3587. (this._canvas = document.createElement('canvas'));
  3588. this._resize( this._img, canvas, width, height );
  3589. this._blob = null; // 没用了,可以删掉了。
  3590. this.modified = true;
  3591. this.owner.trigger('complete');
  3592. },
  3593. getAsBlob: function( type ) {
  3594. var blob = this._blob,
  3595. opts = this.options,
  3596. canvas;
  3597. type = type || this.type;
  3598. // blob需要重新生成。
  3599. if ( this.modified || this.type !== type ) {
  3600. canvas = this._canvas;
  3601. if ( type === 'image/jpeg' ) {
  3602. blob = Util.canvasToDataUrl( canvas, 'image/jpeg',
  3603. opts.quality );
  3604. if ( opts.preserveHeaders && this._metas &&
  3605. this._metas.imageHead ) {
  3606. blob = Util.dataURL2ArrayBuffer( blob );
  3607. blob = Util.updateImageHead( blob,
  3608. this._metas.imageHead );
  3609. blob = Util.arrayBufferToBlob( blob, type );
  3610. return blob;
  3611. }
  3612. } else {
  3613. blob = Util.canvasToDataUrl( canvas, type );
  3614. }
  3615. blob = Util.dataURL2Blob( blob );
  3616. }
  3617. return blob;
  3618. },
  3619. getAsDataUrl: function( type ) {
  3620. var opts = this.options;
  3621. type = type || this.type;
  3622. if ( type === 'image/jpeg' ) {
  3623. return Util.canvasToDataUrl( this._canvas, type, opts.quality );
  3624. } else {
  3625. return this._canvas.toDataURL( type );
  3626. }
  3627. },
  3628. getOrientation: function() {
  3629. return this._metas && this._metas.exif &&
  3630. this._metas.exif.get('Orientation') || 1;
  3631. },
  3632. info: function( val ) {
  3633. // setter
  3634. if ( val ) {
  3635. this._info = val;
  3636. return this;
  3637. }
  3638. // getter
  3639. return this._info;
  3640. },
  3641. meta: function( val ) {
  3642. // setter
  3643. if ( val ) {
  3644. this._meta = val;
  3645. return this;
  3646. }
  3647. // getter
  3648. return this._meta;
  3649. },
  3650. destroy: function() {
  3651. var canvas = this._canvas;
  3652. this._img.onload = null;
  3653. if ( canvas ) {
  3654. canvas.getContext('2d')
  3655. .clearRect( 0, 0, canvas.width, canvas.height );
  3656. canvas.width = canvas.height = 0;
  3657. this._canvas = null;
  3658. }
  3659. // 释放内存。非常重要,否则释放不了image的内存。
  3660. this._img.src = BLANK;
  3661. this._img = this._blob = null;
  3662. },
  3663. _resize: function( img, cvs, width, height ) {
  3664. var opts = this.options,
  3665. naturalWidth = img.width,
  3666. naturalHeight = img.height,
  3667. orientation = this.getOrientation(),
  3668. scale, w, h, x, y;
  3669. // values that require 90 degree rotation
  3670. if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) {
  3671. // 交换width, height的值。
  3672. width ^= height;
  3673. height ^= width;
  3674. width ^= height;
  3675. }
  3676. scale = Math[ opts.crop ? 'max' : 'min' ]( width / naturalWidth,
  3677. height / naturalHeight );
  3678. // 不允许放大。
  3679. opts.allowMagnify || (scale = Math.min( 1, scale ));
  3680. w = naturalWidth * scale;
  3681. h = naturalHeight * scale;
  3682. if ( opts.crop ) {
  3683. cvs.width = width;
  3684. cvs.height = height;
  3685. } else {
  3686. cvs.width = w;
  3687. cvs.height = h;
  3688. }
  3689. x = (cvs.width - w) / 2;
  3690. y = (cvs.height - h) / 2;
  3691. opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation );
  3692. this._renderImageToCanvas( cvs, img, x, y, w, h );
  3693. },
  3694. _rotate2Orientaion: function( canvas, orientation ) {
  3695. var width = canvas.width,
  3696. height = canvas.height,
  3697. ctx = canvas.getContext('2d');
  3698. switch ( orientation ) {
  3699. case 5:
  3700. case 6:
  3701. case 7:
  3702. case 8:
  3703. canvas.width = height;
  3704. canvas.height = width;
  3705. break;
  3706. }
  3707. switch ( orientation ) {
  3708. case 2: // horizontal flip
  3709. ctx.translate( width, 0 );
  3710. ctx.scale( -1, 1 );
  3711. break;
  3712. case 3: // 180 rotate left
  3713. ctx.translate( width, height );
  3714. ctx.rotate( Math.PI );
  3715. break;
  3716. case 4: // vertical flip
  3717. ctx.translate( 0, height );
  3718. ctx.scale( 1, -1 );
  3719. break;
  3720. case 5: // vertical flip + 90 rotate right
  3721. ctx.rotate( 0.5 * Math.PI );
  3722. ctx.scale( 1, -1 );
  3723. break;
  3724. case 6: // 90 rotate right
  3725. ctx.rotate( 0.5 * Math.PI );
  3726. ctx.translate( 0, -height );
  3727. break;
  3728. case 7: // horizontal flip + 90 rotate right
  3729. ctx.rotate( 0.5 * Math.PI );
  3730. ctx.translate( width, -height );
  3731. ctx.scale( -1, 1 );
  3732. break;
  3733. case 8: // 90 rotate left
  3734. ctx.rotate( -0.5 * Math.PI );
  3735. ctx.translate( -width, 0 );
  3736. break;
  3737. }
  3738. },
  3739. // https://github.com/stomita/ios-imagefile-megapixel/
  3740. // blob/master/src/megapix-image.js
  3741. _renderImageToCanvas: (function() {
  3742. // 如果不是ios, 不需要这么复杂!
  3743. if ( !Base.os.ios ) {
  3744. return function( canvas, img, x, y, w, h ) {
  3745. canvas.getContext('2d').drawImage( img, x, y, w, h );
  3746. };
  3747. }
  3748. /**
  3749. * Detecting vertical squash in loaded image.
  3750. * Fixes a bug which squash image vertically while drawing into
  3751. * canvas for some images.
  3752. */
  3753. function detectVerticalSquash( img, iw, ih ) {
  3754. var canvas = document.createElement('canvas'),
  3755. ctx = canvas.getContext('2d'),
  3756. sy = 0,
  3757. ey = ih,
  3758. py = ih,
  3759. data, alpha, ratio;
  3760. canvas.width = 1;
  3761. canvas.height = ih;
  3762. ctx.drawImage( img, 0, 0 );
  3763. data = ctx.getImageData( 0, 0, 1, ih ).data;
  3764. // search image edge pixel position in case
  3765. // it is squashed vertically.
  3766. while ( py > sy ) {
  3767. alpha = data[ (py - 1) * 4 + 3 ];
  3768. if ( alpha === 0 ) {
  3769. ey = py;
  3770. } else {
  3771. sy = py;
  3772. }
  3773. py = (ey + sy) >> 1;
  3774. }
  3775. ratio = (py / ih);
  3776. return (ratio === 0) ? 1 : ratio;
  3777. }
  3778. // fix ie7 bug
  3779. // http://stackoverflow.com/questions/11929099/
  3780. // html5-canvas-drawimage-ratio-bug-ios
  3781. if ( Base.os.ios >= 7 ) {
  3782. return function( canvas, img, x, y, w, h ) {
  3783. var iw = img.naturalWidth,
  3784. ih = img.naturalHeight,
  3785. vertSquashRatio = detectVerticalSquash( img, iw, ih );
  3786. return canvas.getContext('2d').drawImage( img, 0, 0,
  3787. iw * vertSquashRatio, ih * vertSquashRatio,
  3788. x, y, w, h );
  3789. };
  3790. }
  3791. /**
  3792. * Detect subsampling in loaded image.
  3793. * In iOS, larger images than 2M pixels may be
  3794. * subsampled in rendering.
  3795. */
  3796. function detectSubsampling( img ) {
  3797. var iw = img.naturalWidth,
  3798. ih = img.naturalHeight,
  3799. canvas, ctx;
  3800. // subsampling may happen overmegapixel image
  3801. if ( iw * ih > 1024 * 1024 ) {
  3802. canvas = document.createElement('canvas');
  3803. canvas.width = canvas.height = 1;
  3804. ctx = canvas.getContext('2d');
  3805. ctx.drawImage( img, -iw + 1, 0 );
  3806. // subsampled image becomes half smaller in rendering size.
  3807. // check alpha channel value to confirm image is covering
  3808. // edge pixel or not. if alpha value is 0
  3809. // image is not covering, hence subsampled.
  3810. return ctx.getImageData( 0, 0, 1, 1 ).data[ 3 ] === 0;
  3811. } else {
  3812. return false;
  3813. }
  3814. }
  3815. return function( canvas, img, x, y, width, height ) {
  3816. var iw = img.naturalWidth,
  3817. ih = img.naturalHeight,
  3818. ctx = canvas.getContext('2d'),
  3819. subsampled = detectSubsampling( img ),
  3820. doSquash = this.type === 'image/jpeg',
  3821. d = 1024,
  3822. sy = 0,
  3823. dy = 0,
  3824. tmpCanvas, tmpCtx, vertSquashRatio, dw, dh, sx, dx;
  3825. if ( subsampled ) {
  3826. iw /= 2;
  3827. ih /= 2;
  3828. }
  3829. ctx.save();
  3830. tmpCanvas = document.createElement('canvas');
  3831. tmpCanvas.width = tmpCanvas.height = d;
  3832. tmpCtx = tmpCanvas.getContext('2d');
  3833. vertSquashRatio = doSquash ?
  3834. detectVerticalSquash( img, iw, ih ) : 1;
  3835. dw = Math.ceil( d * width / iw );
  3836. dh = Math.ceil( d * height / ih / vertSquashRatio );
  3837. while ( sy < ih ) {
  3838. sx = 0;
  3839. dx = 0;
  3840. while ( sx < iw ) {
  3841. tmpCtx.clearRect( 0, 0, d, d );
  3842. tmpCtx.drawImage( img, -sx, -sy );
  3843. ctx.drawImage( tmpCanvas, 0, 0, d, d,
  3844. x + dx, y + dy, dw, dh );
  3845. sx += d;
  3846. dx += dw;
  3847. }
  3848. sy += d;
  3849. dy += dh;
  3850. }
  3851. ctx.restore();
  3852. tmpCanvas = tmpCtx = null;
  3853. };
  3854. })()
  3855. });
  3856. });
  3857. /**
  3858. * 这个方式性能不行但是可以解决android里面的toDataUrl的bug
  3859. * android里面toDataUrl('image/jpege')得到的结果却是png.
  3860. *
  3861. * 所以这里没辙只能借助这个工具
  3862. * @fileOverview jpeg encoder
  3863. */
  3864. define('runtime/html5/jpegencoder',[], function( require, exports, module ) {
  3865. /*
  3866. Copyright (c) 2008, Adobe Systems Incorporated
  3867. All rights reserved.
  3868. Redistribution and use in source and binary forms, with or without
  3869. modification, are permitted provided that the following conditions are
  3870. met:
  3871. * Redistributions of source code must retain the above copyright notice,
  3872. this list of conditions and the following disclaimer.
  3873. * Redistributions in binary form must reproduce the above copyright
  3874. notice, this list of conditions and the following disclaimer in the
  3875. documentation and/or other materials provided with the distribution.
  3876. * Neither the name of Adobe Systems Incorporated nor the names of its
  3877. contributors may be used to endorse or promote products derived from
  3878. this software without specific prior written permission.
  3879. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  3880. IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  3881. THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  3882. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  3883. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  3884. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  3885. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  3886. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  3887. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  3888. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  3889. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  3890. */
  3891. /*
  3892. JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009
  3893. Basic GUI blocking jpeg encoder
  3894. */
  3895. function JPEGEncoder(quality) {
  3896. var self = this;
  3897. var fround = Math.round;
  3898. var ffloor = Math.floor;
  3899. var YTable = new Array(64);
  3900. var UVTable = new Array(64);
  3901. var fdtbl_Y = new Array(64);
  3902. var fdtbl_UV = new Array(64);
  3903. var YDC_HT;
  3904. var UVDC_HT;
  3905. var YAC_HT;
  3906. var UVAC_HT;
  3907. var bitcode = new Array(65535);
  3908. var category = new Array(65535);
  3909. var outputfDCTQuant = new Array(64);
  3910. var DU = new Array(64);
  3911. var byteout = [];
  3912. var bytenew = 0;
  3913. var bytepos = 7;
  3914. var YDU = new Array(64);
  3915. var UDU = new Array(64);
  3916. var VDU = new Array(64);
  3917. var clt = new Array(256);
  3918. var RGB_YUV_TABLE = new Array(2048);
  3919. var currentQuality;
  3920. var ZigZag = [
  3921. 0, 1, 5, 6,14,15,27,28,
  3922. 2, 4, 7,13,16,26,29,42,
  3923. 3, 8,12,17,25,30,41,43,
  3924. 9,11,18,24,31,40,44,53,
  3925. 10,19,23,32,39,45,52,54,
  3926. 20,22,33,38,46,51,55,60,
  3927. 21,34,37,47,50,56,59,61,
  3928. 35,36,48,49,57,58,62,63
  3929. ];
  3930. var std_dc_luminance_nrcodes = [0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0];
  3931. var std_dc_luminance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
  3932. var std_ac_luminance_nrcodes = [0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d];
  3933. var std_ac_luminance_values = [
  3934. 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,
  3935. 0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,
  3936. 0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,
  3937. 0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,
  3938. 0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,
  3939. 0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,
  3940. 0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,
  3941. 0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,
  3942. 0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,
  3943. 0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,
  3944. 0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,
  3945. 0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
  3946. 0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,
  3947. 0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,
  3948. 0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,
  3949. 0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,
  3950. 0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,
  3951. 0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,
  3952. 0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,
  3953. 0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
  3954. 0xf9,0xfa
  3955. ];
  3956. var std_dc_chrominance_nrcodes = [0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0];
  3957. var std_dc_chrominance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
  3958. var std_ac_chrominance_nrcodes = [0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77];
  3959. var std_ac_chrominance_values = [
  3960. 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,
  3961. 0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,
  3962. 0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,
  3963. 0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,
  3964. 0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,
  3965. 0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,
  3966. 0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,
  3967. 0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,
  3968. 0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,
  3969. 0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,
  3970. 0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,
  3971. 0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
  3972. 0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,
  3973. 0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,
  3974. 0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,
  3975. 0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,
  3976. 0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,
  3977. 0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,
  3978. 0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,
  3979. 0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
  3980. 0xf9,0xfa
  3981. ];
  3982. function initQuantTables(sf){
  3983. var YQT = [
  3984. 16, 11, 10, 16, 24, 40, 51, 61,
  3985. 12, 12, 14, 19, 26, 58, 60, 55,
  3986. 14, 13, 16, 24, 40, 57, 69, 56,
  3987. 14, 17, 22, 29, 51, 87, 80, 62,
  3988. 18, 22, 37, 56, 68,109,103, 77,
  3989. 24, 35, 55, 64, 81,104,113, 92,
  3990. 49, 64, 78, 87,103,121,120,101,
  3991. 72, 92, 95, 98,112,100,103, 99
  3992. ];
  3993. for (var i = 0; i < 64; i++) {
  3994. var t = ffloor((YQT[i]*sf+50)/100);
  3995. if (t < 1) {
  3996. t = 1;
  3997. } else if (t > 255) {
  3998. t = 255;
  3999. }
  4000. YTable[ZigZag[i]] = t;
  4001. }
  4002. var UVQT = [
  4003. 17, 18, 24, 47, 99, 99, 99, 99,
  4004. 18, 21, 26, 66, 99, 99, 99, 99,
  4005. 24, 26, 56, 99, 99, 99, 99, 99,
  4006. 47, 66, 99, 99, 99, 99, 99, 99,
  4007. 99, 99, 99, 99, 99, 99, 99, 99,
  4008. 99, 99, 99, 99, 99, 99, 99, 99,
  4009. 99, 99, 99, 99, 99, 99, 99, 99,
  4010. 99, 99, 99, 99, 99, 99, 99, 99
  4011. ];
  4012. for (var j = 0; j < 64; j++) {
  4013. var u = ffloor((UVQT[j]*sf+50)/100);
  4014. if (u < 1) {
  4015. u = 1;
  4016. } else if (u > 255) {
  4017. u = 255;
  4018. }
  4019. UVTable[ZigZag[j]] = u;
  4020. }
  4021. var aasf = [
  4022. 1.0, 1.387039845, 1.306562965, 1.175875602,
  4023. 1.0, 0.785694958, 0.541196100, 0.275899379
  4024. ];
  4025. var k = 0;
  4026. for (var row = 0; row < 8; row++)
  4027. {
  4028. for (var col = 0; col < 8; col++)
  4029. {
  4030. fdtbl_Y[k] = (1.0 / (YTable [ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
  4031. fdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
  4032. k++;
  4033. }
  4034. }
  4035. }
  4036. function computeHuffmanTbl(nrcodes, std_table){
  4037. var codevalue = 0;
  4038. var pos_in_table = 0;
  4039. var HT = new Array();
  4040. for (var k = 1; k <= 16; k++) {
  4041. for (var j = 1; j <= nrcodes[k]; j++) {
  4042. HT[std_table[pos_in_table]] = [];
  4043. HT[std_table[pos_in_table]][0] = codevalue;
  4044. HT[std_table[pos_in_table]][1] = k;
  4045. pos_in_table++;
  4046. codevalue++;
  4047. }
  4048. codevalue*=2;
  4049. }
  4050. return HT;
  4051. }
  4052. function initHuffmanTbl()
  4053. {
  4054. YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values);
  4055. UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values);
  4056. YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values);
  4057. UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values);
  4058. }
  4059. function initCategoryNumber()
  4060. {
  4061. var nrlower = 1;
  4062. var nrupper = 2;
  4063. for (var cat = 1; cat <= 15; cat++) {
  4064. //Positive numbers
  4065. for (var nr = nrlower; nr<nrupper; nr++) {
  4066. category[32767+nr] = cat;
  4067. bitcode[32767+nr] = [];
  4068. bitcode[32767+nr][1] = cat;
  4069. bitcode[32767+nr][0] = nr;
  4070. }
  4071. //Negative numbers
  4072. for (var nrneg =-(nrupper-1); nrneg<=-nrlower; nrneg++) {
  4073. category[32767+nrneg] = cat;
  4074. bitcode[32767+nrneg] = [];
  4075. bitcode[32767+nrneg][1] = cat;
  4076. bitcode[32767+nrneg][0] = nrupper-1+nrneg;
  4077. }
  4078. nrlower <<= 1;
  4079. nrupper <<= 1;
  4080. }
  4081. }
  4082. function initRGBYUVTable() {
  4083. for(var i = 0; i < 256;i++) {
  4084. RGB_YUV_TABLE[i] = 19595 * i;
  4085. RGB_YUV_TABLE[(i+ 256)>>0] = 38470 * i;
  4086. RGB_YUV_TABLE[(i+ 512)>>0] = 7471 * i + 0x8000;
  4087. RGB_YUV_TABLE[(i+ 768)>>0] = -11059 * i;
  4088. RGB_YUV_TABLE[(i+1024)>>0] = -21709 * i;
  4089. RGB_YUV_TABLE[(i+1280)>>0] = 32768 * i + 0x807FFF;
  4090. RGB_YUV_TABLE[(i+1536)>>0] = -27439 * i;
  4091. RGB_YUV_TABLE[(i+1792)>>0] = - 5329 * i;
  4092. }
  4093. }
  4094. // IO functions
  4095. function writeBits(bs)
  4096. {
  4097. var value = bs[0];
  4098. var posval = bs[1]-1;
  4099. while ( posval >= 0 ) {
  4100. if (value & (1 << posval) ) {
  4101. bytenew |= (1 << bytepos);
  4102. }
  4103. posval--;
  4104. bytepos--;
  4105. if (bytepos < 0) {
  4106. if (bytenew == 0xFF) {
  4107. writeByte(0xFF);
  4108. writeByte(0);
  4109. }
  4110. else {
  4111. writeByte(bytenew);
  4112. }
  4113. bytepos=7;
  4114. bytenew=0;
  4115. }
  4116. }
  4117. }
  4118. function writeByte(value)
  4119. {
  4120. byteout.push(clt[value]); // write char directly instead of converting later
  4121. }
  4122. function writeWord(value)
  4123. {
  4124. writeByte((value>>8)&0xFF);
  4125. writeByte((value )&0xFF);
  4126. }
  4127. // DCT & quantization core
  4128. function fDCTQuant(data, fdtbl)
  4129. {
  4130. var d0, d1, d2, d3, d4, d5, d6, d7;
  4131. /* Pass 1: process rows. */
  4132. var dataOff=0;
  4133. var i;
  4134. var I8 = 8;
  4135. var I64 = 64;
  4136. for (i=0; i<I8; ++i)
  4137. {
  4138. d0 = data[dataOff];
  4139. d1 = data[dataOff+1];
  4140. d2 = data[dataOff+2];
  4141. d3 = data[dataOff+3];
  4142. d4 = data[dataOff+4];
  4143. d5 = data[dataOff+5];
  4144. d6 = data[dataOff+6];
  4145. d7 = data[dataOff+7];
  4146. var tmp0 = d0 + d7;
  4147. var tmp7 = d0 - d7;
  4148. var tmp1 = d1 + d6;
  4149. var tmp6 = d1 - d6;
  4150. var tmp2 = d2 + d5;
  4151. var tmp5 = d2 - d5;
  4152. var tmp3 = d3 + d4;
  4153. var tmp4 = d3 - d4;
  4154. /* Even part */
  4155. var tmp10 = tmp0 + tmp3; /* phase 2 */
  4156. var tmp13 = tmp0 - tmp3;
  4157. var tmp11 = tmp1 + tmp2;
  4158. var tmp12 = tmp1 - tmp2;
  4159. data[dataOff] = tmp10 + tmp11; /* phase 3 */
  4160. data[dataOff+4] = tmp10 - tmp11;
  4161. var z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */
  4162. data[dataOff+2] = tmp13 + z1; /* phase 5 */
  4163. data[dataOff+6] = tmp13 - z1;
  4164. /* Odd part */
  4165. tmp10 = tmp4 + tmp5; /* phase 2 */
  4166. tmp11 = tmp5 + tmp6;
  4167. tmp12 = tmp6 + tmp7;
  4168. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  4169. var z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */
  4170. var z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */
  4171. var z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */
  4172. var z3 = tmp11 * 0.707106781; /* c4 */
  4173. var z11 = tmp7 + z3; /* phase 5 */
  4174. var z13 = tmp7 - z3;
  4175. data[dataOff+5] = z13 + z2; /* phase 6 */
  4176. data[dataOff+3] = z13 - z2;
  4177. data[dataOff+1] = z11 + z4;
  4178. data[dataOff+7] = z11 - z4;
  4179. dataOff += 8; /* advance pointer to next row */
  4180. }
  4181. /* Pass 2: process columns. */
  4182. dataOff = 0;
  4183. for (i=0; i<I8; ++i)
  4184. {
  4185. d0 = data[dataOff];
  4186. d1 = data[dataOff + 8];
  4187. d2 = data[dataOff + 16];
  4188. d3 = data[dataOff + 24];
  4189. d4 = data[dataOff + 32];
  4190. d5 = data[dataOff + 40];
  4191. d6 = data[dataOff + 48];
  4192. d7 = data[dataOff + 56];
  4193. var tmp0p2 = d0 + d7;
  4194. var tmp7p2 = d0 - d7;
  4195. var tmp1p2 = d1 + d6;
  4196. var tmp6p2 = d1 - d6;
  4197. var tmp2p2 = d2 + d5;
  4198. var tmp5p2 = d2 - d5;
  4199. var tmp3p2 = d3 + d4;
  4200. var tmp4p2 = d3 - d4;
  4201. /* Even part */
  4202. var tmp10p2 = tmp0p2 + tmp3p2; /* phase 2 */
  4203. var tmp13p2 = tmp0p2 - tmp3p2;
  4204. var tmp11p2 = tmp1p2 + tmp2p2;
  4205. var tmp12p2 = tmp1p2 - tmp2p2;
  4206. data[dataOff] = tmp10p2 + tmp11p2; /* phase 3 */
  4207. data[dataOff+32] = tmp10p2 - tmp11p2;
  4208. var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781; /* c4 */
  4209. data[dataOff+16] = tmp13p2 + z1p2; /* phase 5 */
  4210. data[dataOff+48] = tmp13p2 - z1p2;
  4211. /* Odd part */
  4212. tmp10p2 = tmp4p2 + tmp5p2; /* phase 2 */
  4213. tmp11p2 = tmp5p2 + tmp6p2;
  4214. tmp12p2 = tmp6p2 + tmp7p2;
  4215. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  4216. var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433; /* c6 */
  4217. var z2p2 = 0.541196100 * tmp10p2 + z5p2; /* c2-c6 */
  4218. var z4p2 = 1.306562965 * tmp12p2 + z5p2; /* c2+c6 */
  4219. var z3p2 = tmp11p2 * 0.707106781; /* c4 */
  4220. var z11p2 = tmp7p2 + z3p2; /* phase 5 */
  4221. var z13p2 = tmp7p2 - z3p2;
  4222. data[dataOff+40] = z13p2 + z2p2; /* phase 6 */
  4223. data[dataOff+24] = z13p2 - z2p2;
  4224. data[dataOff+ 8] = z11p2 + z4p2;
  4225. data[dataOff+56] = z11p2 - z4p2;
  4226. dataOff++; /* advance pointer to next column */
  4227. }
  4228. // Quantize/descale the coefficients
  4229. var fDCTQuant;
  4230. for (i=0; i<I64; ++i)
  4231. {
  4232. // Apply the quantization and scaling factor & Round to nearest integer
  4233. fDCTQuant = data[i]*fdtbl[i];
  4234. outputfDCTQuant[i] = (fDCTQuant > 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0);
  4235. //outputfDCTQuant[i] = fround(fDCTQuant);
  4236. }
  4237. return outputfDCTQuant;
  4238. }
  4239. function writeAPP0()
  4240. {
  4241. writeWord(0xFFE0); // marker
  4242. writeWord(16); // length
  4243. writeByte(0x4A); // J
  4244. writeByte(0x46); // F
  4245. writeByte(0x49); // I
  4246. writeByte(0x46); // F
  4247. writeByte(0); // = "JFIF",'\0'
  4248. writeByte(1); // versionhi
  4249. writeByte(1); // versionlo
  4250. writeByte(0); // xyunits
  4251. writeWord(1); // xdensity
  4252. writeWord(1); // ydensity
  4253. writeByte(0); // thumbnwidth
  4254. writeByte(0); // thumbnheight
  4255. }
  4256. function writeSOF0(width, height)
  4257. {
  4258. writeWord(0xFFC0); // marker
  4259. writeWord(17); // length, truecolor YUV JPG
  4260. writeByte(8); // precision
  4261. writeWord(height);
  4262. writeWord(width);
  4263. writeByte(3); // nrofcomponents
  4264. writeByte(1); // IdY
  4265. writeByte(0x11); // HVY
  4266. writeByte(0); // QTY
  4267. writeByte(2); // IdU
  4268. writeByte(0x11); // HVU
  4269. writeByte(1); // QTU
  4270. writeByte(3); // IdV
  4271. writeByte(0x11); // HVV
  4272. writeByte(1); // QTV
  4273. }
  4274. function writeDQT()
  4275. {
  4276. writeWord(0xFFDB); // marker
  4277. writeWord(132); // length
  4278. writeByte(0);
  4279. for (var i=0; i<64; i++) {
  4280. writeByte(YTable[i]);
  4281. }
  4282. writeByte(1);
  4283. for (var j=0; j<64; j++) {
  4284. writeByte(UVTable[j]);
  4285. }
  4286. }
  4287. function writeDHT()
  4288. {
  4289. writeWord(0xFFC4); // marker
  4290. writeWord(0x01A2); // length
  4291. writeByte(0); // HTYDCinfo
  4292. for (var i=0; i<16; i++) {
  4293. writeByte(std_dc_luminance_nrcodes[i+1]);
  4294. }
  4295. for (var j=0; j<=11; j++) {
  4296. writeByte(std_dc_luminance_values[j]);
  4297. }
  4298. writeByte(0x10); // HTYACinfo
  4299. for (var k=0; k<16; k++) {
  4300. writeByte(std_ac_luminance_nrcodes[k+1]);
  4301. }
  4302. for (var l=0; l<=161; l++) {
  4303. writeByte(std_ac_luminance_values[l]);
  4304. }
  4305. writeByte(1); // HTUDCinfo
  4306. for (var m=0; m<16; m++) {
  4307. writeByte(std_dc_chrominance_nrcodes[m+1]);
  4308. }
  4309. for (var n=0; n<=11; n++) {
  4310. writeByte(std_dc_chrominance_values[n]);
  4311. }
  4312. writeByte(0x11); // HTUACinfo
  4313. for (var o=0; o<16; o++) {
  4314. writeByte(std_ac_chrominance_nrcodes[o+1]);
  4315. }
  4316. for (var p=0; p<=161; p++) {
  4317. writeByte(std_ac_chrominance_values[p]);
  4318. }
  4319. }
  4320. function writeSOS()
  4321. {
  4322. writeWord(0xFFDA); // marker
  4323. writeWord(12); // length
  4324. writeByte(3); // nrofcomponents
  4325. writeByte(1); // IdY
  4326. writeByte(0); // HTY
  4327. writeByte(2); // IdU
  4328. writeByte(0x11); // HTU
  4329. writeByte(3); // IdV
  4330. writeByte(0x11); // HTV
  4331. writeByte(0); // Ss
  4332. writeByte(0x3f); // Se
  4333. writeByte(0); // Bf
  4334. }
  4335. function processDU(CDU, fdtbl, DC, HTDC, HTAC){
  4336. var EOB = HTAC[0x00];
  4337. var M16zeroes = HTAC[0xF0];
  4338. var pos;
  4339. var I16 = 16;
  4340. var I63 = 63;
  4341. var I64 = 64;
  4342. var DU_DCT = fDCTQuant(CDU, fdtbl);
  4343. //ZigZag reorder
  4344. for (var j=0;j<I64;++j) {
  4345. DU[ZigZag[j]]=DU_DCT[j];
  4346. }
  4347. var Diff = DU[0] - DC; DC = DU[0];
  4348. //Encode DC
  4349. if (Diff==0) {
  4350. writeBits(HTDC[0]); // Diff might be 0
  4351. } else {
  4352. pos = 32767+Diff;
  4353. writeBits(HTDC[category[pos]]);
  4354. writeBits(bitcode[pos]);
  4355. }
  4356. //Encode ACs
  4357. var end0pos = 63; // was const... which is crazy
  4358. for (; (end0pos>0)&&(DU[end0pos]==0); end0pos--) {};
  4359. //end0pos = first element in reverse order !=0
  4360. if ( end0pos == 0) {
  4361. writeBits(EOB);
  4362. return DC;
  4363. }
  4364. var i = 1;
  4365. var lng;
  4366. while ( i <= end0pos ) {
  4367. var startpos = i;
  4368. for (; (DU[i]==0) && (i<=end0pos); ++i) {}
  4369. var nrzeroes = i-startpos;
  4370. if ( nrzeroes >= I16 ) {
  4371. lng = nrzeroes>>4;
  4372. for (var nrmarker=1; nrmarker <= lng; ++nrmarker)
  4373. writeBits(M16zeroes);
  4374. nrzeroes = nrzeroes&0xF;
  4375. }
  4376. pos = 32767+DU[i];
  4377. writeBits(HTAC[(nrzeroes<<4)+category[pos]]);
  4378. writeBits(bitcode[pos]);
  4379. i++;
  4380. }
  4381. if ( end0pos != I63 ) {
  4382. writeBits(EOB);
  4383. }
  4384. return DC;
  4385. }
  4386. function initCharLookupTable(){
  4387. var sfcc = String.fromCharCode;
  4388. for(var i=0; i < 256; i++){ ///// ACHTUNG // 255
  4389. clt[i] = sfcc(i);
  4390. }
  4391. }
  4392. this.encode = function(image,quality) // image data object
  4393. {
  4394. // var time_start = new Date().getTime();
  4395. if(quality) setQuality(quality);
  4396. // Initialize bit writer
  4397. byteout = new Array();
  4398. bytenew=0;
  4399. bytepos=7;
  4400. // Add JPEG headers
  4401. writeWord(0xFFD8); // SOI
  4402. writeAPP0();
  4403. writeDQT();
  4404. writeSOF0(image.width,image.height);
  4405. writeDHT();
  4406. writeSOS();
  4407. // Encode 8x8 macroblocks
  4408. var DCY=0;
  4409. var DCU=0;
  4410. var DCV=0;
  4411. bytenew=0;
  4412. bytepos=7;
  4413. this.encode.displayName = "_encode_";
  4414. var imageData = image.data;
  4415. var width = image.width;
  4416. var height = image.height;
  4417. var quadWidth = width*4;
  4418. var tripleWidth = width*3;
  4419. var x, y = 0;
  4420. var r, g, b;
  4421. var start,p, col,row,pos;
  4422. while(y < height){
  4423. x = 0;
  4424. while(x < quadWidth){
  4425. start = quadWidth * y + x;
  4426. p = start;
  4427. col = -1;
  4428. row = 0;
  4429. for(pos=0; pos < 64; pos++){
  4430. row = pos >> 3;// /8
  4431. col = ( pos & 7 ) * 4; // %8
  4432. p = start + ( row * quadWidth ) + col;
  4433. if(y+row >= height){ // padding bottom
  4434. p-= (quadWidth*(y+1+row-height));
  4435. }
  4436. if(x+col >= quadWidth){ // padding right
  4437. p-= ((x+col) - quadWidth +4)
  4438. }
  4439. r = imageData[ p++ ];
  4440. g = imageData[ p++ ];
  4441. b = imageData[ p++ ];
  4442. /* // calculate YUV values dynamically
  4443. YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80
  4444. UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));
  4445. VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));
  4446. */
  4447. // use lookup table (slightly faster)
  4448. YDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256)>>0] + RGB_YUV_TABLE[(b + 512)>>0]) >> 16)-128;
  4449. UDU[pos] = ((RGB_YUV_TABLE[(r + 768)>>0] + RGB_YUV_TABLE[(g + 1024)>>0] + RGB_YUV_TABLE[(b + 1280)>>0]) >> 16)-128;
  4450. VDU[pos] = ((RGB_YUV_TABLE[(r + 1280)>>0] + RGB_YUV_TABLE[(g + 1536)>>0] + RGB_YUV_TABLE[(b + 1792)>>0]) >> 16)-128;
  4451. }
  4452. DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
  4453. DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
  4454. DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
  4455. x+=32;
  4456. }
  4457. y+=8;
  4458. }
  4459. ////////////////////////////////////////////////////////////////
  4460. // Do the bit alignment of the EOI marker
  4461. if ( bytepos >= 0 ) {
  4462. var fillbits = [];
  4463. fillbits[1] = bytepos+1;
  4464. fillbits[0] = (1<<(bytepos+1))-1;
  4465. writeBits(fillbits);
  4466. }
  4467. writeWord(0xFFD9); //EOI
  4468. var jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join(''));
  4469. byteout = [];
  4470. // benchmarking
  4471. // var duration = new Date().getTime() - time_start;
  4472. // console.log('Encoding time: '+ currentQuality + 'ms');
  4473. //
  4474. return jpegDataUri
  4475. }
  4476. function setQuality(quality){
  4477. if (quality <= 0) {
  4478. quality = 1;
  4479. }
  4480. if (quality > 100) {
  4481. quality = 100;
  4482. }
  4483. if(currentQuality == quality) return // don't recalc if unchanged
  4484. var sf = 0;
  4485. if (quality < 50) {
  4486. sf = Math.floor(5000 / quality);
  4487. } else {
  4488. sf = Math.floor(200 - quality*2);
  4489. }
  4490. initQuantTables(sf);
  4491. currentQuality = quality;
  4492. // console.log('Quality set to: '+quality +'%');
  4493. }
  4494. function init(){
  4495. // var time_start = new Date().getTime();
  4496. if(!quality) quality = 50;
  4497. // Create tables
  4498. initCharLookupTable()
  4499. initHuffmanTbl();
  4500. initCategoryNumber();
  4501. initRGBYUVTable();
  4502. setQuality(quality);
  4503. // var duration = new Date().getTime() - time_start;
  4504. // console.log('Initialization '+ duration + 'ms');
  4505. }
  4506. init();
  4507. };
  4508. JPEGEncoder.encode = function( data, quality ) {
  4509. var encoder = new JPEGEncoder( quality );
  4510. return encoder.encode( data );
  4511. }
  4512. return JPEGEncoder;
  4513. });
  4514. /**
  4515. * @fileOverview Fix android canvas.toDataUrl bug.
  4516. */
  4517. define('runtime/html5/androidpatch',[
  4518. 'runtime/html5/util',
  4519. 'runtime/html5/jpegencoder',
  4520. 'base'
  4521. ], function( Util, encoder, Base ) {
  4522. var origin = Util.canvasToDataUrl,
  4523. supportJpeg;
  4524. Util.canvasToDataUrl = function( canvas, type, quality ) {
  4525. var ctx, w, h, fragement, parts;
  4526. // 非android手机直接跳过。
  4527. if ( !Base.os.android ) {
  4528. return origin.apply( null, arguments );
  4529. }
  4530. // 检测是否canvas支持jpeg导出,根据数据格式来判断。
  4531. // JPEG 前两位分别是:255, 216
  4532. if ( type === 'image/jpeg' && typeof supportJpeg === 'undefined' ) {
  4533. fragement = origin.apply( null, arguments );
  4534. parts = fragement.split(',');
  4535. if ( ~parts[ 0 ].indexOf('base64') ) {
  4536. fragement = atob( parts[ 1 ] );
  4537. } else {
  4538. fragement = decodeURIComponent( parts[ 1 ] );
  4539. }
  4540. fragement = fragement.substring( 0, 2 );
  4541. supportJpeg = fragement.charCodeAt( 0 ) === 255 &&
  4542. fragement.charCodeAt( 1 ) === 216;
  4543. }
  4544. // 只有在android环境下才修复
  4545. if ( type === 'image/jpeg' && !supportJpeg ) {
  4546. w = canvas.width;
  4547. h = canvas.height;
  4548. ctx = canvas.getContext('2d');
  4549. return encoder.encode( ctx.getImageData( 0, 0, w, h ), quality );
  4550. }
  4551. return origin.apply( null, arguments );
  4552. };
  4553. });
  4554. /**
  4555. * @fileOverview Transport
  4556. * @todo 支持chunked传输优势
  4557. * 可以将大文件分成小块挨个传输可以提高大文件成功率当失败的时候也只需要重传那小部分
  4558. * 而不需要重头再传一次另外断点续传也需要用chunked方式
  4559. */
  4560. define('runtime/html5/transport',[
  4561. 'base',
  4562. 'runtime/html5/runtime'
  4563. ], function( Base, Html5Runtime ) {
  4564. var noop = Base.noop,
  4565. $ = Base.$;
  4566. return Html5Runtime.register( 'Transport', {
  4567. init: function() {
  4568. this._status = 0;
  4569. this._response = null;
  4570. },
  4571. send: function() {
  4572. var owner = this.owner,
  4573. opts = this.options,
  4574. xhr = this._initAjax(),
  4575. blob = owner._blob,
  4576. server = opts.server,
  4577. formData, binary, fr;
  4578. if ( opts.sendAsBinary ) {
  4579. server += (/\?/.test( server ) ? '&' : '?') +
  4580. $.param( owner._formData );
  4581. binary = blob.getSource();
  4582. } else {
  4583. formData = new FormData();
  4584. $.each( owner._formData, function( k, v ) {
  4585. formData.append( k, v );
  4586. });
  4587. formData.append( opts.fileVal, blob.getSource(),
  4588. opts.filename || owner._formData.name || '' );
  4589. }
  4590. if ( opts.withCredentials && 'withCredentials' in xhr ) {
  4591. xhr.open( opts.method, server, true );
  4592. xhr.withCredentials = true;
  4593. } else {
  4594. xhr.open( opts.method, server );
  4595. }
  4596. this._setRequestHeader( xhr, opts.headers );
  4597. if ( binary ) {
  4598. xhr.overrideMimeType('application/octet-stream');
  4599. // android直接发送blob会导致服务端接收到的是空文件。
  4600. // bug详情。
  4601. // https://code.google.com/p/android/issues/detail?id=39882
  4602. // 所以先用fileReader读取出来再通过arraybuffer的方式发送。
  4603. if ( Base.os.android ) {
  4604. fr = new FileReader();
  4605. fr.onload = function() {
  4606. xhr.send( this.result );
  4607. fr = fr.onload = null;
  4608. };
  4609. fr.readAsArrayBuffer( binary );
  4610. } else {
  4611. xhr.send( binary );
  4612. }
  4613. } else {
  4614. xhr.send( formData );
  4615. }
  4616. },
  4617. getResponse: function() {
  4618. return this._response;
  4619. },
  4620. getResponseAsJson: function() {
  4621. return this._parseJson( this._response );
  4622. },
  4623. getStatus: function() {
  4624. return this._status;
  4625. },
  4626. abort: function() {
  4627. var xhr = this._xhr;
  4628. if ( xhr ) {
  4629. xhr.upload.onprogress = noop;
  4630. xhr.onreadystatechange = noop;
  4631. xhr.abort();
  4632. this._xhr = xhr = null;
  4633. }
  4634. },
  4635. destroy: function() {
  4636. this.abort();
  4637. },
  4638. _initAjax: function() {
  4639. var me = this,
  4640. xhr = new XMLHttpRequest(),
  4641. opts = this.options;
  4642. if ( opts.withCredentials && !('withCredentials' in xhr) &&
  4643. typeof XDomainRequest !== 'undefined' ) {
  4644. xhr = new XDomainRequest();
  4645. }
  4646. xhr.upload.onprogress = function( e ) {
  4647. var percentage = 0;
  4648. if ( e.lengthComputable ) {
  4649. percentage = e.loaded / e.total;
  4650. }
  4651. return me.trigger( 'progress', percentage );
  4652. };
  4653. xhr.onreadystatechange = function() {
  4654. if ( xhr.readyState !== 4 ) {
  4655. return;
  4656. }
  4657. xhr.upload.onprogress = noop;
  4658. xhr.onreadystatechange = noop;
  4659. me._xhr = null;
  4660. me._status = xhr.status;
  4661. if ( xhr.status >= 200 && xhr.status < 300 ) {
  4662. me._response = xhr.responseText;
  4663. return me.trigger('load');
  4664. } else if ( xhr.status >= 500 && xhr.status < 600 ) {
  4665. me._response = xhr.responseText;
  4666. return me.trigger( 'error', 'server' );
  4667. }
  4668. return me.trigger( 'error', me._status ? 'http' : 'abort' );
  4669. };
  4670. me._xhr = xhr;
  4671. return xhr;
  4672. },
  4673. _setRequestHeader: function( xhr, headers ) {
  4674. $.each( headers, function( key, val ) {
  4675. xhr.setRequestHeader( key, val );
  4676. });
  4677. },
  4678. _parseJson: function( str ) {
  4679. var json;
  4680. try {
  4681. json = JSON.parse( str );
  4682. } catch ( ex ) {
  4683. json = {};
  4684. }
  4685. return json;
  4686. }
  4687. });
  4688. });
  4689. define('webuploader',[
  4690. 'base',
  4691. 'widgets/filepicker',
  4692. 'widgets/image',
  4693. 'widgets/queue',
  4694. 'widgets/runtime',
  4695. 'widgets/upload',
  4696. 'runtime/html5/blob',
  4697. 'runtime/html5/filepicker',
  4698. 'runtime/html5/imagemeta/exif',
  4699. 'runtime/html5/image',
  4700. 'runtime/html5/androidpatch',
  4701. 'runtime/html5/transport'
  4702. ], function( Base ) {
  4703. return Base;
  4704. });
  4705. return require('webuploader');
  4706. });