-凯发官网注册
/*! webuploader 0.1.5 */
/**
* @fileoverview 让内部各个部件的代码可以用[amd](https://github.com/amdjs/amdjs-api/wiki/amd)模块定义方式组织起来。
*
* amd api 内部的简单不完全实现,请忽略。只有当webuploader被合并成一个文件的时候才会引入。
*/
(function( root, factory ) {
var modules = {},
// 内部require, 简单不完全实现。
// https://github.com/amdjs/amdjs-api/wiki/require
_require = function( deps, callback ) {
var args, len, i;
// 如果deps不是数组,则直接返回指定module
if ( typeof deps === 'string' ) {
return getmodule( deps );
} else {
args = [];
for( len = deps.length, i = 0; i < len; i ) {
args.push( getmodule( deps[ i ] ) );
}
return callback.apply( null, args );
}
},
// 内部define,暂时不支持不指定id.
_define = function( id, deps, factory ) {
if ( arguments.length === 2 ) {
factory = deps;
deps = null;
}
_require( deps || [], function() {
setmodule( id, factory, arguments );
});
},
// 设置module, 兼容commonjs写法。
setmodule = function( id, factory, args ) {
var module = {
exports: factory
},
returned;
if ( typeof factory === 'function' ) {
args.length || (args = [ _require, module.exports, module ]);
returned = factory.apply( null, args );
returned !== undefined && (module.exports = returned);
}
modules[ id ] = module.exports;
},
// 根据id获取module
getmodule = function( id ) {
var module = modules[ id ] || root[ id ];
if ( !module ) {
throw new error( '`' id '` is undefined' );
}
return module;
},
// 将所有modules,将路径ids装换成对象。
exportsto = function( obj ) {
var key, host, parts, part, last, ucfirst;
// make the first character upper case.
ucfirst = function( str ) {
return str && (str.charat( 0 ).touppercase() str.substr( 1 ));
};
for ( key in modules ) {
host = obj;
if ( !modules.hasownproperty( key ) ) {
continue;
}
parts = key.split('/');
last = ucfirst( parts.pop() );
while( (part = ucfirst( parts.shift() )) ) {
host[ part ] = host[ part ] || {};
host = host[ part ];
}
host[ last ] = modules[ key ];
}
return obj;
},
makeexport = function( dollar ) {
root.__dollar = dollar;
// exports every module.
return exportsto( factory( root, _define, _require ) );
},
origin;
if ( typeof module === 'object' && typeof module.exports === 'object' ) {
// for commonjs and commonjs-like environments where a proper window is present,
module.exports = makeexport();
} else if ( typeof define === 'function' && define.amd ) {
// allow using this built library as an amd module
// in another project. that other project will only
// see this amd call, not the internal modules in
// the closure below.
define([ 'jquery' ], makeexport );
} else {
// browser globals case. just assign the
// result to a property on the global.
origin = root.webuploader;
root.webuploader = makeexport();
root.webuploader.noconflict = function() {
root.webuploader = origin;
};
}
})( window, function( window, define, require ) {
/**
* @fileoverview jquery or zepto
*/
define('dollar-third',[],function() {
var $ = window.__dollar || window.jquery || window.zepto;
if ( !$ ) {
throw new error('jquery or zepto not found!');
}
return $;
});
/**
* @fileoverview dom 操作相关
*/
define('dollar',[
'dollar-third'
], function( _ ) {
return _;
});
/**
* @fileoverview 使用jquery的promise
*/
define('promise-third',[
'dollar'
], function( $ ) {
return {
deferred: $.deferred,
when: $.when,
ispromise: function( anything ) {
return anything && typeof anything.then === 'function';
}
};
});
/**
* @fileoverview promise/a
*/
define('promise',[
'promise-third'
], function( _ ) {
return _;
});
/**
* @fileoverview 基础类方法。
*/
/**
* web uploader内部类的详细说明,以下提及的功能类,都可以在`webuploader`这个变量中访问到。
*
* as you know, web uploader的每个文件都是用过[amd](https://github.com/amdjs/amdjs-api/wiki/amd)规范中的`define`组织起来的, 每个module都会有个module id.
* 默认module id为该文件的路径,而此路径将会转化成名字空间存放在webuploader中。如:
*
* * module `base`:webuploader.base
* * module `file`: webuploader.file
* * module `lib/dnd`: webuploader.lib.dnd
* * module `runtime/html5/dnd`: webuploader.runtime.html5.dnd
*
*
* 以下文档中对类的使用可能省略掉了`webuploader`前缀。
* @module webuploader
* @title webuploader api文档
*/
define('base',[
'dollar',
'promise'
], function( $, promise ) {
var noop = function() {},
call = function.call;
// http://jsperf.com/uncurrythis
// 反科里化
function uncurrythis( fn ) {
return function() {
return call.apply( fn, arguments );
};
}
function bindfn( fn, context ) {
return function() {
return fn.apply( context, arguments );
};
}
function createobject( proto ) {
var f;
if ( object.create ) {
return object.create( proto );
} else {
f = function() {};
f.prototype = proto;
return new f();
}
}
/**
* 基础类,提供一些简单常用的方法。
* @class base
*/
return {
/**
* @property {string} version 当前版本号。
*/
version: '0.1.5',
/**
* @property {jquery|zepto} $ 引用依赖的jquery或者zepto对象。
*/
$: $,
deferred: promise.deferred,
ispromise: promise.ispromise,
when: promise.when,
/**
* @description 简单的浏览器检查结果。
*
* * `webkit` webkit版本号,如果浏览器为非webkit内核,此属性为`undefined`。
* * `chrome` chrome浏览器版本号,如果浏览器为chrome,此属性为`undefined`。
* * `ie` ie浏览器版本号,如果浏览器为非ie,此属性为`undefined`。**暂不支持ie10 **
* * `firefox` firefox浏览器版本号,如果浏览器为非firefox,此属性为`undefined`。
* * `safari` safari浏览器版本号,如果浏览器为非safari,此属性为`undefined`。
* * `opera` opera浏览器版本号,如果浏览器为非opera,此属性为`undefined`。
*
* @property {object} [browser]
*/
browser: (function( ua ) {
var ret = {},
webkit = ua.match( /webkit\/([\d.] )/ ),
chrome = ua.match( /chrome\/([\d.] )/ ) ||
ua.match( /crios\/([\d.] )/ ),
ie = ua.match( /msie\s([\d\.] )/ ) ||
ua.match( /(?:trident)(?:.*rv:([\w.] ))?/i ),
firefox = ua.match( /firefox\/([\d.] )/ ),
safari = ua.match( /safari\/([\d.] )/ ),
opera = ua.match( /opr\/([\d.] )/ );
webkit && (ret.webkit = parsefloat( webkit[ 1 ] ));
chrome && (ret.chrome = parsefloat( chrome[ 1 ] ));
ie && (ret.ie = parsefloat( ie[ 1 ] ));
firefox && (ret.firefox = parsefloat( firefox[ 1 ] ));
safari && (ret.safari = parsefloat( safari[ 1 ] ));
opera && (ret.opera = parsefloat( opera[ 1 ] ));
return ret;
})( navigator.useragent ),
/**
* @description 操作系统检查结果。
*
* * `android` 如果在android浏览器环境下,此值为对应的android版本号,否则为`undefined`。
* * `ios` 如果在ios浏览器环境下,此值为对应的ios版本号,否则为`undefined`。
* @property {object} [os]
*/
os: (function( ua ) {
var ret = {},
// osx = !!ua.match( /\(macintosh\; intel / ),
android = ua.match( /(?:android);?[\s\/] ([\d.] )?/ ),
ios = ua.match( /(?:ipad|ipod|iphone).*os\s([\d_] )/ );
// osx && (ret.osx = true);
android && (ret.android = parsefloat( android[ 1 ] ));
ios && (ret.ios = parsefloat( ios[ 1 ].replace( /_/g, '.' ) ));
return ret;
})( navigator.useragent ),
/**
* 实现类与类之间的继承。
* @method inherits
* @grammar base.inherits( super ) => child
* @grammar base.inherits( super, protos ) => child
* @grammar base.inherits( super, protos, statics ) => child
* @param {class} super 父类
* @param {object | function} [protos] 子类或者对象。如果对象中包含constructor,子类将是用此属性值。
* @param {function} [protos.constructor] 子类构造器,不指定的话将创建个临时的直接执行父类构造器的方法。
* @param {object} [statics] 静态属性或方法。
* @return {class} 返回子类。
* @example
* function person() {
* console.log( 'super' );
* }
* person.prototype.hello = function() {
* console.log( 'hello' );
* };
*
* var manager = base.inherits( person, {
* world: function() {
* console.log( 'world' );
* }
* });
*
* // 因为没有指定构造器,父类的构造器将会执行。
* var instance = new manager(); // => super
*
* // 继承子父类的方法
* instance.hello(); // => hello
* instance.world(); // => world
*
* // 子类的__super__属性指向父类
* console.log( manager.__super__ === person ); // => true
*/
inherits: function( super, protos, staticprotos ) {
var child;
if ( typeof protos === 'function' ) {
child = protos;
protos = null;
} else if ( protos && protos.hasownproperty('constructor') ) {
child = protos.constructor;
} else {
child = function() {
return super.apply( this, arguments );
};
}
// 复制静态方法
$.extend( true, child, super, staticprotos || {} );
/* jshint camelcase: false */
// 让子类的__super__属性指向父类。
child.__super__ = super.prototype;
// 构建原型,添加原型方法或属性。
// 暂时用object.create实现。
child.prototype = createobject( super.prototype );
protos && $.extend( true, child.prototype, protos );
return child;
},
/**
* 一个不做任何事情的方法。可以用来赋值给默认的callback.
* @method noop
*/
noop: noop,
/**
* 返回一个新的方法,此方法将已指定的`context`来执行。
* @grammar base.bindfn( fn, context ) => function
* @method bindfn
* @example
* var dosomething = function() {
* console.log( this.name );
* },
* obj = {
* name: 'object name'
* },
* aliasfn = base.bind( dosomething, obj );
*
* aliasfn(); // => object name
*
*/
bindfn: bindfn,
/**
* 引用console.log如果存在的话,否则引用一个[空函数noop](#webuploader:base.noop)。
* @grammar base.log( args... ) => undefined
* @method log
*/
log: (function() {
if ( window.console ) {
return bindfn( console.log, console );
}
return noop;
})(),
nexttick: (function() {
return function( cb ) {
settimeout( cb, 1 );
};
// @bug 当浏览器不在当前窗口时就停了。
// var next = window.requestanimationframe ||
// window.webkitrequestanimationframe ||
// window.mozrequestanimationframe ||
// function( cb ) {
// window.settimeout( cb, 1000 / 60 );
// };
// // fix: uncaught typeerror: illegal invocation
// return bindfn( next, window );
})(),
/**
* 被[uncurrythis](http://www.2ality.com/2011/11/uncurrying-this.html)的数组slice方法。
* 将用来将非数组对象转化成数组对象。
* @grammar base.slice( target, start[, end] ) => array
* @method slice
* @example
* function dosomthing() {
* var args = base.slice( arguments, 1 );
* console.log( args );
* }
*
* dosomthing( 'ignored', 'arg2', 'arg3' ); // => array ["arg2", "arg3"]
*/
slice: uncurrythis( [].slice ),
/**
* 生成唯一的id
* @method guid
* @grammar base.guid() => string
* @grammar base.guid( prefx ) => string
*/
guid: (function() {
var counter = 0;
return function( prefix ) {
var guid = ( new date()).tostring( 32 ),
i = 0;
for ( ; i < 5; i ) {
guid = math.floor( math.random() * 65535 ).tostring( 32 );
}
return (prefix || 'wu_') guid (counter ).tostring( 32 );
};
})(),
/**
* 格式化文件大小, 输出成带单位的字符串
* @method formatsize
* @grammar base.formatsize( size ) => string
* @grammar base.formatsize( size, pointlength ) => string
* @grammar base.formatsize( size, pointlength, units ) => string
* @param {number} size 文件大小
* @param {number} [pointlength=2] 精确到的小数点数。
* @param {array} [units=[ 'b', 'k', 'm', 'g', 'tb' ]] 单位数组。从字节,到千字节,一直往上指定。如果单位数组里面只指定了到了k(千字节),同时文件大小大于m, 此方法的输出将还是显示成多少k.
* @example
* console.log( base.formatsize( 100 ) ); // => 100b
* console.log( base.formatsize( 1024 ) ); // => 1.00k
* console.log( base.formatsize( 1024, 0 ) ); // => 1k
* console.log( base.formatsize( 1024 * 1024 ) ); // => 1.00m
* console.log( base.formatsize( 1024 * 1024 * 1024 ) ); // => 1.00g
* console.log( base.formatsize( 1024 * 1024 * 1024, 0, ['b', 'kb', 'mb'] ) ); // => 1024mb
*/
formatsize: function( size, pointlength, units ) {
var unit;
units = units || [ 'b', 'k', 'm', 'g', 'tb' ];
while ( (unit = units.shift()) && size > 1024 ) {
size = size / 1024;
}
return (unit === 'b' ? size : size.tofixed( pointlength || 2 ))
unit;
}
};
});
/**
* 事件处理类,可以独立使用,也可以扩展给对象使用。
* @fileoverview mediator
*/
define('mediator',[
'base'
], function( base ) {
var $ = base.$,
slice = [].slice,
separator = /\s /,
protos;
// 根据条件过滤出事件handlers.
function findhandlers( arr, name, callback, context ) {
return $.grep( arr, function( handler ) {
return handler &&
(!name || handler.e === name) &&
(!callback || handler.cb === callback ||
handler.cb._cb === callback) &&
(!context || handler.ctx === context);
});
}
function eachevent( events, callback, iterator ) {
// 不支持对象,只支持多个event用空格隔开
$.each( (events || '').split( separator ), function( _, key ) {
iterator( key, callback );
});
}
function triggerhanders( events, args ) {
var stoped = false,
i = -1,
len = events.length,
handler;
while ( i < len ) {
handler = events[ i ];
if ( handler.cb.apply( handler.ctx2, args ) === false ) {
stoped = true;
break;
}
}
return !stoped;
}
protos = {
/**
* 绑定事件。
*
* `callback`方法在执行时,arguments将会来源于trigger的时候携带的参数。如
* ```javascript
* var obj = {};
*
* // 使得obj有事件行为
* mediator.installto( obj );
*
* obj.on( 'testa', function( arg1, arg2 ) {
* console.log( arg1, arg2 ); // => 'arg1', 'arg2'
* });
*
* obj.trigger( 'testa', 'arg1', 'arg2' );
* ```
*
* 如果`callback`中,某一个方法`return false`了,则后续的其他`callback`都不会被执行到。
* 切会影响到`trigger`方法的返回值,为`false`。
*
* `on`还可以用来添加一个特殊事件`all`, 这样所有的事件触发都会响应到。同时此类`callback`中的arguments有一个不同处,
* 就是第一个参数为`type`,记录当前是什么事件在触发。此类`callback`的优先级比脚低,会再正常`callback`执行完后触发。
* ```javascript
* obj.on( 'all', function( type, arg1, arg2 ) {
* console.log( type, arg1, arg2 ); // => 'testa', 'arg1', 'arg2'
* });
* ```
*
* @method on
* @grammar on( name, callback[, context] ) => self
* @param {string} name 事件名,支持多个事件用空格隔开
* @param {function} callback 事件处理器
* @param {object} [context] 事件处理器的上下文。
* @return {self} 返回自身,方便链式
* @chainable
* @class mediator
*/
on: function( name, callback, context ) {
var me = this,
set;
if ( !callback ) {
return this;
}
set = this._events || (this._events = []);
eachevent( name, callback, function( name, callback ) {
var handler = { e: name };
handler.cb = callback;
handler.ctx = context;
handler.ctx2 = context || me;
handler.id = set.length;
set.push( handler );
});
return this;
},
/**
* 绑定事件,且当handler执行完后,自动解除绑定。
* @method once
* @grammar once( name, callback[, context] ) => self
* @param {string} name 事件名
* @param {function} callback 事件处理器
* @param {object} [context] 事件处理器的上下文。
* @return {self} 返回自身,方便链式
* @chainable
*/
once: function( name, callback, context ) {
var me = this;
if ( !callback ) {
return me;
}
eachevent( name, callback, function( name, callback ) {
var once = function() {
me.off( name, once );
return callback.apply( context || me, arguments );
};
once._cb = callback;
me.on( name, once, context );
});
return me;
},
/**
* 解除事件绑定
* @method off
* @grammar off( [name[, callback[, context] ] ] ) => self
* @param {string} [name] 事件名
* @param {function} [callback] 事件处理器
* @param {object} [context] 事件处理器的上下文。
* @return {self} 返回自身,方便链式
* @chainable
*/
off: function( name, cb, ctx ) {
var events = this._events;
if ( !events ) {
return this;
}
if ( !name && !cb && !ctx ) {
this._events = [];
return this;
}
eachevent( name, cb, function( name, cb ) {
$.each( findhandlers( events, name, cb, ctx ), function() {
delete events[ this.id ];
});
});
return this;
},
/**
* 触发事件
* @method trigger
* @grammar trigger( name[, args...] ) => self
* @param {string} type 事件名
* @param {*} [...] 任意参数
* @return {boolean} 如果handler中return false了,则返回false, 否则返回true
*/
trigger: function( type ) {
var args, events, allevents;
if ( !this._events || !type ) {
return this;
}
args = slice.call( arguments, 1 );
events = findhandlers( this._events, type );
allevents = findhandlers( this._events, 'all' );
return triggerhanders( events, args ) &&
triggerhanders( allevents, arguments );
}
};
/**
* 中介者,它本身是个单例,但可以通过[installto](#webuploader:mediator:installto)方法,使任何对象具备事件行为。
* 主要目的是负责模块与模块之间的合作,降低耦合度。
*
* @class mediator
*/
return $.extend({
/**
* 可以通过这个接口,使任何对象具备事件功能。
* @method installto
* @param {object} obj 需要具备事件行为的对象。
* @return {object} 返回obj.
*/
installto: function( obj ) {
return $.extend( obj, protos );
}
}, protos );
});
/**
* @fileoverview uploader上传类
*/
define('uploader',[
'base',
'mediator'
], function( base, mediator ) {
var $ = base.$;
/**
* 上传入口类。
* @class uploader
* @constructor
* @grammar new uploader( opts ) => uploader
* @example
* var uploader = webuploader.uploader({
* swf: 'path_of_swf/uploader.swf',
*
* // 开起分片上传。
* chunked: true
* });
*/
function uploader( opts ) {
this.options = $.extend( true, {}, uploader.options, opts );
this._init( this.options );
}
// default options
// widgets中有相应扩展
uploader.options = {};
mediator.installto( uploader.prototype );
// 批量添加纯命令式方法。
$.each({
upload: 'start-upload',
stop: 'stop-upload',
getfile: 'get-file',
getfiles: 'get-files',
addfile: 'add-file',
addfiles: 'add-file',
sort: 'sort-files',
removefile: 'remove-file',
cancelfile: 'cancel-file',
skipfile: 'skip-file',
retry: 'retry',
isinprogress: 'is-in-progress',
makethumb: 'make-thumb',
md5file: 'md5-file',
getdimension: 'get-dimension',
addbutton: 'add-btn',
predictruntimetype: 'predict-runtime-type',
refresh: 'refresh',
disable: 'disable',
enable: 'enable',
reset: 'reset'
}, function( fn, command ) {
uploader.prototype[ fn ] = function() {
return this.request( command, arguments );
};
});
$.extend( uploader.prototype, {
state: 'pending',
_init: function( opts ) {
var me = this;
me.request( 'init', opts, function() {
me.state = 'ready';
me.trigger('ready');
});
},
/**
* 获取或者设置uploader配置项。
* @method option
* @grammar option( key ) => *
* @grammar option( key, val ) => self
* @example
*
* // 初始状态图片上传前不会压缩
* var uploader = new webuploader.uploader({
* compress: null;
* });
*
* // 修改后图片上传前,尝试将图片压缩到1600 * 1600
* uploader.option( 'compress', {
* width: 1600,
* height: 1600
* });
*/
option: function( key, val ) {
var opts = this.options;
// setter
if ( arguments.length > 1 ) {
if ( $.isplainobject( val ) &&
$.isplainobject( opts[ key ] ) ) {
$.extend( opts[ key ], val );
} else {
opts[ key ] = val;
}
} else { // getter
return key ? opts[ key ] : opts;
}
},
/**
* 获取文件统计信息。返回一个包含一下信息的对象。
* * `successnum` 上传成功的文件数
* * `progressnum` 上传中的文件数
* * `cancelnum` 被删除的文件数
* * `invalidnum` 无效的文件数
* * `uploadfailnum` 上传失败的文件数
* * `queuenum` 还在队列中的文件数
* * `interruptnum` 被暂停的文件数
* @method getstats
* @grammar getstats() => object
*/
getstats: function() {
// return this._mgr.getstats.apply( this._mgr, arguments );
var stats = this.request('get-stats');
return stats ? {
successnum: stats.numofsuccess,
progressnum: stats.numofprogress,
// who care?
// queuefailnum: 0,
cancelnum: stats.numofcancel,
invalidnum: stats.numofinvalid,
uploadfailnum: stats.numofuploadfailed,
queuenum: stats.numofqueue,
interruptnum: stats.numofinterrupt
} : {};
},
// 需要重写此方法来来支持opts.onevent和instance.onevent的处理器
trigger: function( type/*, args...*/ ) {
var args = [].slice.call( arguments, 1 ),
opts = this.options,
name = 'on' type.substring( 0, 1 ).touppercase()
type.substring( 1 );
if (
// 调用通过on方法注册的handler.
mediator.trigger.apply( this, arguments ) === false ||
// 调用opts.onevent
$.isfunction( opts[ name ] ) &&
opts[ name ].apply( this, args ) === false ||
// 调用this.onevent
$.isfunction( this[ name ] ) &&
this[ name ].apply( this, args ) === false ||
// 广播所有uploader的事件。
mediator.trigger.apply( mediator,
[ this, type ].concat( args ) ) === false ) {
return false;
}
return true;
},
/**
* 销毁 webuploader 实例
* @method destroy
* @grammar destroy() => undefined
*/
destroy: function() {
this.request( 'destroy', arguments );
this.off();
},
// widgets/widget.js将补充此方法的详细文档。
request: base.noop
});
/**
* 创建uploader实例,等同于new uploader( opts );
* @method create
* @class base
* @static
* @grammar base.create( opts ) => uploader
*/
base.create = uploader.create = function( opts ) {
return new uploader( opts );
};
// 暴露uploader,可以通过它来扩展业务逻辑。
base.uploader = uploader;
return uploader;
});
/**
* @fileoverview runtime管理器,负责runtime的选择, 连接
*/
define('runtime/runtime',[
'base',
'mediator'
], function( base, mediator ) {
var $ = base.$,
factories = {},
// 获取对象的第一个key
getfirstkey = function( obj ) {
for ( var key in obj ) {
if ( obj.hasownproperty( key ) ) {
return key;
}
}
return null;
};
// 接口类。
function runtime( options ) {
this.options = $.extend({
container: document.body
}, options );
this.uid = base.guid('rt_');
}
$.extend( runtime.prototype, {
getcontainer: function() {
var opts = this.options,
parent, container;
if ( this._container ) {
return this._container;
}
parent = $( opts.container || document.body );
container = $( document.createelement('div') );
container.attr( 'id', 'rt_' this.uid );
container.css({
position: 'absolute',
top: '0px',
left: '0px',
width: '1px',
height: '1px',
overflow: 'hidden'
});
parent.append( container );
parent.addclass('webuploader-container');
this._container = container;
this._parent = parent;
return container;
},
init: base.noop,
exec: base.noop,
destroy: function() {
this._container && this._container.remove();
this._parent && this._parent.removeclass('webuploader-container');
this.off();
}
});
runtime.orders = 'html5,flash';
/**
* 添加runtime实现。
* @param {string} type 类型
* @param {runtime} factory 具体runtime实现。
*/
runtime.addruntime = function( type, factory ) {
factories[ type ] = factory;
};
runtime.hasruntime = function( type ) {
return !!(type ? factories[ type ] : getfirstkey( factories ));
};
runtime.create = function( opts, orders ) {
var type, runtime;
orders = orders || runtime.orders;
$.each( orders.split( /\s*,\s*/g ), function() {
if ( factories[ this ] ) {
type = this;
return false;
}
});
type = type || getfirstkey( factories );
if ( !type ) {
throw new error('runtime error');
}
runtime = new factories[ type ]( opts );
return runtime;
};
mediator.installto( runtime.prototype );
return runtime;
});
/**
* @fileoverview runtime管理器,负责runtime的选择, 连接
*/
define('runtime/client',[
'base',
'mediator',
'runtime/runtime'
], function( base, mediator, runtime ) {
var cache;
cache = (function() {
var obj = {};
return {
add: function( runtime ) {
obj[ runtime.uid ] = runtime;
},
get: function( ruid, standalone ) {
var i;
if ( ruid ) {
return obj[ ruid ];
}
for ( i in obj ) {
// 有些类型不能重用,比如filepicker.
if ( standalone && obj[ i ].__standalone ) {
continue;
}
return obj[ i ];
}
return null;
},
remove: function( runtime ) {
delete obj[ runtime.uid ];
}
};
})();
function runtimeclient( component, standalone ) {
var deferred = base.deferred(),
runtime;
this.uid = base.guid('client_');
// 允许runtime没有初始化之前,注册一些方法在初始化后执行。
this.runtimeready = function( cb ) {
return deferred.done( cb );
};
this.connectruntime = function( opts, cb ) {
// already connected.
if ( runtime ) {
throw new error('already connected!');
}
deferred.done( cb );
if ( typeof opts === 'string' && cache.get( opts ) ) {
runtime = cache.get( opts );
}
// 像filepicker只能独立存在,不能公用。
runtime = runtime || cache.get( null, standalone );
// 需要创建
if ( !runtime ) {
runtime = runtime.create( opts, opts.runtimeorder );
runtime.__promise = deferred.promise();
runtime.once( 'ready', deferred.resolve );
runtime.init();
cache.add( runtime );
runtime.__client = 1;
} else {
// 来自cache
base.$.extend( runtime.options, opts );
runtime.__promise.then( deferred.resolve );
runtime.__client ;
}
standalone && (runtime.__standalone = standalone);
return runtime;
};
this.getruntime = function() {
return runtime;
};
this.disconnectruntime = function() {
if ( !runtime ) {
return;
}
runtime.__client--;
if ( runtime.__client <= 0 ) {
cache.remove( runtime );
delete runtime.__promise;
runtime.destroy();
}
runtime = null;
};
this.exec = function() {
if ( !runtime ) {
return;
}
var args = base.slice( arguments );
component && args.unshift( component );
return runtime.exec.apply( this, args );
};
this.getruid = function() {
return runtime && runtime.uid;
};
this.destroy = (function( destroy ) {
return function() {
destroy && destroy.apply( this, arguments );
this.trigger('destroy');
this.off();
this.exec('destroy');
this.disconnectruntime();
};
})( this.destroy );
}
mediator.installto( runtimeclient.prototype );
return runtimeclient;
});
/**
* @fileoverview blob
*/
define('lib/blob',[
'base',
'runtime/client'
], function( base, runtimeclient ) {
function blob( ruid, source ) {
var me = this;
me.source = source;
me.ruid = ruid;
this.size = source.size || 0;
// 如果没有指定 mimetype, 但是知道文件后缀。
if ( !source.type && this.ext &&
~'jpg,jpeg,png,gif,bmp'.indexof( this.ext ) ) {
this.type = 'image/' (this.ext === 'jpg' ? 'jpeg' : this.ext);
} else {
this.type = source.type || 'application/octet-stream';
}
runtimeclient.call( me, 'blob' );
this.uid = source.uid || this.uid;
if ( ruid ) {
me.connectruntime( ruid );
}
}
base.inherits( runtimeclient, {
constructor: blob,
slice: function( start, end ) {
return this.exec( 'slice', start, end );
},
getsource: function() {
return this.source;
}
});
return blob;
});
/**
* 为了统一化flash的file和html5的file而存在。
* 以至于要调用flash里面的file,也可以像调用html5版本的file一下。
* @fileoverview file
*/
define('lib/file',[
'base',
'lib/blob'
], function( base, blob ) {
var uid = 1,
rext = /\.([^.] )$/;
function file( ruid, file ) {
var ext;
this.name = file.name || ('untitled' uid );
ext = rext.exec( file.name ) ? regexp.$1.tolowercase() : '';
// todo 支持其他类型文件的转换。
// 如果有 mimetype, 但是文件名里面没有找出后缀规律
if ( !ext && file.type ) {
ext = /\/(jpg|jpeg|png|gif|bmp)$/i.exec( file.type ) ?
regexp.$1.tolowercase() : '';
this.name = '.' ext;
}
this.ext = ext;
this.lastmodifieddate = file.lastmodifieddate ||
(new date()).tolocalestring();
blob.apply( this, arguments );
}
return base.inherits( blob, file );
});
/**
* @fileoverview 错误信息
*/
define('lib/filepicker',[
'base',
'runtime/client',
'lib/file'
], function( base, runtimeclent, file ) {
var $ = base.$;
function filepicker( opts ) {
opts = this.options = $.extend({}, filepicker.options, opts );
opts.container = $( opts.id );
if ( !opts.container.length ) {
throw new error('按钮指定错误');
}
opts.innerhtml = opts.innerhtml || opts.label ||
opts.container.html() || '';
opts.button = $( opts.button || document.createelement('div') );
opts.button.html( opts.innerhtml );
opts.container.html( opts.button );
runtimeclent.call( this, 'filepicker', true );
}
filepicker.options = {
button: null,
container: null,
label: null,
innerhtml: null,
multiple: true,
accept: null,
name: 'file'
};
base.inherits( runtimeclent, {
constructor: filepicker,
init: function() {
var me = this,
opts = me.options,
button = opts.button;
button.addclass('webuploader-pick');
me.on( 'all', function( type ) {
var files;
switch ( type ) {
case 'mouseenter':
button.addclass('webuploader-pick-hover');
break;
case 'mouseleave':
button.removeclass('webuploader-pick-hover');
break;
case 'change':
files = me.exec('getfiles');
me.trigger( 'select', $.map( files, function( file ) {
file = new file( me.getruid(), file );
// 记录来源。
file._refer = opts.container;
return file;
}), opts.container );
break;
}
});
me.connectruntime( opts, function() {
me.refresh();
me.exec( 'init', opts );
me.trigger('ready');
});
this._resizehandler = base.bindfn( this.refresh, this );
$( window ).on( 'resize', this._resizehandler );
},
refresh: function() {
var shimcontainer = this.getruntime().getcontainer(),
button = this.options.button,
width = button.outerwidth ?
button.outerwidth() : button.width(),
height = button.outerheight ?
button.outerheight() : button.height(),
pos = button.offset();
width && height && shimcontainer.css({
bottom: 'auto',
right: 'auto',
width: width 'px',
height: height 'px'
}).offset( pos );
},
enable: function() {
var btn = this.options.button;
btn.removeclass('webuploader-pick-disable');
this.refresh();
},
disable: function() {
var btn = this.options.button;
this.getruntime().getcontainer().css({
top: '-99999px'
});
btn.addclass('webuploader-pick-disable');
},
destroy: function() {
var btn = this.options.button;
$( window ).off( 'resize', this._resizehandler );
btn.removeclass('webuploader-pick-disable webuploader-pick-hover '
'webuploader-pick');
}
});
return filepicker;
});
/**
* @fileoverview 组件基类。
*/
define('widgets/widget',[
'base',
'uploader'
], function( base, uploader ) {
var $ = base.$,
_init = uploader.prototype._init,
_destroy = uploader.prototype.destroy,
ignore = {},
widgetclass = [];
function isarraylike( obj ) {
if ( !obj ) {
return false;
}
var length = obj.length,
type = $.type( obj );
if ( obj.nodetype === 1 && length ) {
return true;
}
return type === 'array' || type !== 'function' && type !== 'string' &&
(length === 0 || typeof length === 'number' && length > 0 &&
(length - 1) in obj);
}
function widget( uploader ) {
this.owner = uploader;
this.options = uploader.options;
}
$.extend( widget.prototype, {
init: base.noop,
// 类backbone的事件监听声明,监听uploader实例上的事件
// widget直接无法监听事件,事件只能通过uploader来传递
invoke: function( apiname, args ) {
/*
{
'make-thumb': 'makethumb'
}
*/
var map = this.responsemap;
// 如果无api响应声明则忽略
if ( !map || !(apiname in map) || !(map[ apiname ] in this) ||
!$.isfunction( this[ map[ apiname ] ] ) ) {
return ignore;
}
return this[ map[ apiname ] ].apply( this, args );
},
/**
* 发送命令。当传入`callback`或者`handler`中返回`promise`时。返回一个当所有`handler`中的promise都完成后完成的新`promise`。
* @method request
* @grammar request( command, args ) => * | promise
* @grammar request( command, args, callback ) => promise
* @for uploader
*/
request: function() {
return this.owner.request.apply( this.owner, arguments );
}
});
// 扩展uploader.
$.extend( uploader.prototype, {
/**
* @property {string | array} [disablewidgets=undefined]
* @namespace options
* @for uploader
* @description 默认所有 uploader.register 了的 widget 都会被加载,如果禁用某一部分,请通过此 option 指定黑名单。
*/
// 覆写_init用来初始化widgets
_init: function() {
var me = this,
widgets = me._widgets = [],
deactives = me.options.disablewidgets || '';
$.each( widgetclass, function( _, klass ) {
(!deactives || !~deactives.indexof( klass._name )) &&
widgets.push( new klass( me ) );
});
return _init.apply( me, arguments );
},
request: function( apiname, args, callback ) {
var i = 0,
widgets = this._widgets,
len = widgets && widgets.length,
rlts = [],
dfds = [],
widget, rlt, promise, key;
args = isarraylike( args ) ? args : [ args ];
for ( ; i < len; i ) {
widget = widgets[ i ];
rlt = widget.invoke( apiname, args );
if ( rlt !== ignore ) {
// deferred对象
if ( base.ispromise( rlt ) ) {
dfds.push( rlt );
} else {
rlts.push( rlt );
}
}
}
// 如果有callback,则用异步方式。
if ( callback || dfds.length ) {
promise = base.when.apply( base, dfds );
key = promise.pipe ? 'pipe' : 'then';
// 很重要不能删除。删除了会死循环。
// 保证执行顺序。让callback总是在下一个 tick 中执行。
return promise[ key ](function() {
var deferred = base.deferred(),
args = arguments;
if ( args.length === 1 ) {
args = args[ 0 ];
}
settimeout(function() {
deferred.resolve( args );
}, 1 );
return deferred.promise();
})[ callback ? key : 'done' ]( callback || base.noop );
} else {
return rlts[ 0 ];
}
},
destroy: function() {
_destroy.apply( this, arguments );
this._widgets = null;
}
});
/**
* 添加组件
* @grammar uploader.register(proto);
* @grammar uploader.register(map, proto);
* @param {object} responsemap api 名称与函数实现的映射
* @param {object} proto 组件原型,构造函数通过 constructor 属性定义
* @method uploader.register
* @for uploader
* @example
* uploader.register({
* 'make-thumb': 'makethumb'
* }, {
* init: function( options ) {},
* makethumb: function() {}
* });
*
* uploader.register({
* 'make-thumb': function() {
*
* }
* });
*/
uploader.register = widget.register = function( responsemap, widgetproto ) {
var map = { init: 'init', destroy: 'destroy', name: 'anonymous' },
klass;
if ( arguments.length === 1 ) {
widgetproto = responsemap;
// 自动生成 map 表。
$.each(widgetproto, function(key) {
if ( key[0] === '_' || key === 'name' ) {
key === 'name' && (map.name = widgetproto.name);
return;
}
map[key.replace(/[a-z]/g, '-$&').tolowercase()] = key;
});
} else {
map = $.extend( map, responsemap );
}
widgetproto.responsemap = map;
klass = base.inherits( widget, widgetproto );
klass._name = map.name;
widgetclass.push( klass );
return klass;
};
/**
* 删除插件,只有在注册时指定了名字的才能被删除。
* @grammar uploader.unregister(name);
* @param {string} name 组件名字
* @method uploader.unregister
* @for uploader
* @example
*
* uploader.register({
* name: 'custom',
*
* 'make-thumb': function() {
*
* }
* });
*
* uploader.unregister('custom');
*/
uploader.unregister = widget.unregister = function( name ) {
if ( !name || name === 'anonymous' ) {
return;
}
// 删除指定的插件。
for ( var i = widgetclass.length; i--; ) {
if ( widgetclass[i]._name === name ) {
widgetclass.splice(i, 1)
}
}
};
return widget;
});
/**
* @fileoverview 文件选择相关
*/
define('widgets/filepicker',[
'base',
'uploader',
'lib/filepicker',
'widgets/widget'
], function( base, uploader, filepicker ) {
var $ = base.$;
$.extend( uploader.options, {
/**
* @property {selector | object} [pick=undefined]
* @namespace options
* @for uploader
* @description 指定选择文件的按钮容器,不指定则不创建按钮。
*
* * `id` {seletor|dom} 指定选择文件的按钮容器,不指定则不创建按钮。**注意** 这里虽然写的是 id, 但是不是只支持 id, 还支持 class, 或者 dom 节点。
* * `label` {string} 请采用 `innerhtml` 代替
* * `innerhtml` {string} 指定按钮文字。不指定时优先从指定的容器中看是否自带文字。
* * `multiple` {boolean} 是否开起同时选择多个文件能力。
*/
pick: null,
/**
* @property {arroy} [accept=null]
* @namespace options
* @for uploader
* @description 指定接受哪些类型的文件。 由于目前还有ext转mimetype表,所以这里需要分开指定。
*
* * `title` {string} 文字描述
* * `extensions` {string} 允许的文件后缀,不带点,多个用逗号分割。
* * `mimetypes` {string} 多个用逗号分割。
*
* 如:
*
* ```
* {
* title: 'images',
* extensions: 'gif,jpg,jpeg,bmp,png',
* mimetypes: 'image/*'
* }
* ```
*/
accept: null/*{
title: 'images',
extensions: 'gif,jpg,jpeg,bmp,png',
mimetypes: 'image/*'
}*/
});
return uploader.register({
name: 'picker',
init: function( opts ) {
this.pickers = [];
return opts.pick && this.addbtn( opts.pick );
},
refresh: function() {
$.each( this.pickers, function() {
this.refresh();
});
},
/**
* @method addbutton
* @for uploader
* @grammar addbutton( pick ) => promise
* @description
* 添加文件选择按钮,如果一个按钮不够,需要调用此方法来添加。参数跟[options.pick](#webuploader:uploader:options)一致。
* @example
* uploader.addbutton({
* id: '#btncontainer',
* innerhtml: '选择文件'
* });
*/
addbtn: function( pick ) {
var me = this,
opts = me.options,
accept = opts.accept,
promises = [];
if ( !pick ) {
return;
}
$.isplainobject( pick ) || (pick = {
id: pick
});
$( pick.id ).each(function() {
var options, picker, deferred;
deferred = base.deferred();
options = $.extend({}, pick, {
accept: $.isplainobject( accept ) ? [ accept ] : accept,
swf: opts.swf,
runtimeorder: opts.runtimeorder,
id: this
});
picker = new filepicker( options );
picker.once( 'ready', deferred.resolve );
picker.on( 'select', function( files ) {
me.owner.request( 'add-file', [ files ]);
});
picker.init();
me.pickers.push( picker );
promises.push( deferred.promise() );
});
return base.when.apply( base, promises );
},
disable: function() {
$.each( this.pickers, function() {
this.disable();
});
},
enable: function() {
$.each( this.pickers, function() {
this.enable();
});
},
destroy: function() {
$.each( this.pickers, function() {
this.destroy();
});
this.pickers = null;
}
});
});
/**
* @fileoverview image
*/
define('lib/image',[
'base',
'runtime/client',
'lib/blob'
], function( base, runtimeclient, blob ) {
var $ = base.$;
// 构造器。
function image( opts ) {
this.options = $.extend({}, image.options, opts );
runtimeclient.call( this, 'image' );
this.on( 'load', function() {
this._info = this.exec('info');
this._meta = this.exec('meta');
});
}
// 默认选项。
image.options = {
// 默认的图片处理质量
quality: 90,
// 是否裁剪
crop: false,
// 是否保留头部信息
preserveheaders: false,
// 是否允许放大。
allowmagnify: false
};
// 继承runtimeclient.
base.inherits( runtimeclient, {
constructor: image,
info: function( val ) {
// setter
if ( val ) {
this._info = val;
return this;
}
// getter
return this._info;
},
meta: function( val ) {
// setter
if ( val ) {
this._meta = val;
return this;
}
// getter
return this._meta;
},
loadfromblob: function( blob ) {
var me = this,
ruid = blob.getruid();
this.connectruntime( ruid, function() {
me.exec( 'init', me.options );
me.exec( 'loadfromblob', blob );
});
},
resize: function() {
var args = base.slice( arguments );
return this.exec.apply( this, [ 'resize' ].concat( args ) );
},
crop: function() {
var args = base.slice( arguments );
return this.exec.apply( this, [ 'crop' ].concat( args ) );
},
getasdataurl: function( type ) {
return this.exec( 'getasdataurl', type );
},
getasblob: function( type ) {
var blob = this.exec( 'getasblob', type );
return new blob( this.getruid(), blob );
}
});
return image;
});
/**
* @fileoverview 图片操作, 负责预览图片和上传前压缩图片
*/
define('widgets/image',[
'base',
'uploader',
'lib/image',
'widgets/widget'
], function( base, uploader, image ) {
var $ = base.$,
throttle;
// 根据要处理的文件大小来节流,一次不能处理太多,会卡。
throttle = (function( max ) {
var occupied = 0,
waiting = [],
tick = function() {
var item;
while ( waiting.length && occupied < max ) {
item = waiting.shift();
occupied = item[ 0 ];
item[ 1 ]();
}
};
return function( emiter, size, cb ) {
waiting.push([ size, cb ]);
emiter.once( 'destroy', function() {
occupied -= size;
settimeout( tick, 1 );
});
settimeout( tick, 1 );
};
})( 5 * 1024 * 1024 );
$.extend( uploader.options, {
/**
* @property {object} [thumb]
* @namespace options
* @for uploader
* @description 配置生成缩略图的选项。
*
* 默认为:
*
* ```javascript
* {
* width: 110,
* height: 110,
*
* // 图片质量,只有type为`image/jpeg`的时候才有效。
* quality: 70,
*
* // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
* allowmagnify: true,
*
* // 是否允许裁剪。
* crop: true,
*
* // 为空的话则保留原有图片格式。
* // 否则强制转换成指定的类型。
* type: 'image/jpeg'
* }
* ```
*/
thumb: {
width: 110,
height: 110,
quality: 70,
allowmagnify: true,
crop: true,
preserveheaders: false,
// 为空的话则保留原有图片格式。
// 否则强制转换成指定的类型。
// ie 8下面 base64 大小不能超过 32k 否则预览失败,而非 jpeg 编码的图片很可
// 能会超过 32k, 所以这里设置成预览的时候都是 image/jpeg
type: 'image/jpeg'
},
/**
* @property {object} [compress]
* @namespace options
* @for uploader
* @description 配置压缩的图片的选项。如果此选项为`false`, 则图片在上传前不进行压缩。
*
* 默认为:
*
* ```javascript
* {
* width: 1600,
* height: 1600,
*
* // 图片质量,只有type为`image/jpeg`的时候才有效。
* quality: 90,
*
* // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false.
* allowmagnify: false,
*
* // 是否允许裁剪。
* crop: false,
*
* // 是否保留头部meta信息。
* preserveheaders: true,
*
* // 如果发现压缩后文件大小比原来还大,则使用原来图片
* // 此属性可能会影响图片自动纠正功能
* nocompressiflarger: false,
*
* // 单位字节,如果图片大小小于此值,不会采用压缩。
* compresssize: 0
* }
* ```
*/
compress: {
width: 1600,
height: 1600,
quality: 90,
allowmagnify: false,
crop: false,
preserveheaders: true
}
});
return uploader.register({
name: 'image',
/**
* 生成缩略图,此过程为异步,所以需要传入`callback`。
* 通常情况在图片加入队里后调用此方法来生成预览图以增强交互效果。
*
* 当 width 或者 height 的值介于 0 - 1 时,被当成百分比使用。
*
* `callback`中可以接收到两个参数。
* * 第一个为error,如果生成缩略图有错误,此error将为真。
* * 第二个为ret, 缩略图的data url值。
*
* **注意**
* date url在ie6/7中不支持,所以不用调用此方法了,直接显示一张暂不支持预览图片好了。
* 也可以借助服务端,将 base64 数据传给服务端,生成一个临时文件供预览。
*
* @method makethumb
* @grammar makethumb( file, callback ) => undefined
* @grammar makethumb( file, callback, width, height ) => undefined
* @for uploader
* @example
*
* uploader.on( 'filequeued', function( file ) {
* var $li = ...;
*
* uploader.makethumb( file, function( error, ret ) {
* if ( error ) {
* $li.text('预览错误');
* } else {
* $li.append('');
* }
* });
*
* });
*/
makethumb: function( file, cb, width, height ) {
var opts, image;
file = this.request( 'get-file', file );
// 只预览图片格式。
if ( !file.type.match( /^image/ ) ) {
cb( true );
return;
}
opts = $.extend({}, this.options.thumb );
// 如果传入的是object.
if ( $.isplainobject( width ) ) {
opts = $.extend( opts, width );
width = null;
}
width = width || opts.width;
height = height || opts.height;
image = new image( opts );
image.once( 'load', function() {
file._info = file._info || image.info();
file._meta = file._meta || image.meta();
// 如果 width 的值介于 0 - 1
// 说明设置的是百分比。
if ( width <= 1 && width > 0 ) {
width = file._info.width * width;
}
// 同样的规则应用于 height
if ( height <= 1 && height > 0 ) {
height = file._info.height * height;
}
image.resize( width, height );
});
// 当 resize 完后
image.once( 'complete', function() {
cb( false, image.getasdata );
image.destroy();
});
image.once( 'error', function( reason ) {
cb( reason || true );
image.destroy();
});
throttle( image, file.source.size, function() {
file._info && image.info( file._info );
file._meta && image.meta( file._meta );
image.loadfromblob( file.source );
});
},
beforesendfile: function( file ) {
var opts = this.options.compress || this.options.resize,
compresssize = opts && opts.compresssize || 0,
nocompressiflarger = opts && opts.nocompressiflarger || false,
image, deferred;
file = this.request( 'get-file', file );
// 只压缩 jpeg 图片格式。
// gif 可能会丢失针
// bmp png 基本上尺寸都不大,且压缩比比较小。
if ( !opts || !~'image/jpeg,image/jpg'.indexof( file.type ) ||
file.size < compresssize ||
file._compressed ) {
return;
}
opts = $.extend({}, opts );
deferred = base.deferred();
image = new image( opts );
deferred.always(function() {
image.destroy();
image = null;
});
image.once( 'error', deferred.reject );
image.once( 'load', function() {
var width = opts.width,
height = opts.height;
file._info = file._info || image.info();
file._meta = file._meta || image.meta();
// 如果 width 的值介于 0 - 1
// 说明设置的是百分比。
if ( width <= 1 && width > 0 ) {
width = file._info.width * width;
}
// 同样的规则应用于 height
if ( height <= 1 && height > 0 ) {
height = file._info.height * height;
}
image.resize( width, height );
});
image.once( 'complete', function() {
var blob, size;
// 移动端 uc / qq 浏览器的无图模式下
// ctx.getimagedata 处理大图的时候会报 exception
// index_size_err: dom exception 1
try {
blob = image.getasblob( opts.type );
size = file.size;
// 如果压缩后,比原来还大则不用压缩后的。
if ( !nocompressiflarger || blob.size < size ) {
// file.source.destroy && file.source.destroy();
file.source = blob;
file.size = blob.size;
file.trigger( 'resize', blob.size, size );
}
// 标记,避免重复压缩。
file._compressed = true;
deferred.resolve();
} catch ( e ) {
// 出错了直接继续,让其上传原始图片
deferred.resolve();
}
});
file._info && image.info( file._info );
file._meta && image.meta( file._meta );
image.loadfromblob( file.source );
return deferred.promise();
}
});
});
/**
* @fileoverview 文件属性封装
*/
define('file',[
'base',
'mediator'
], function( base, mediator ) {
var $ = base.$,
idprefix = 'wu_file_',
idsuffix = 0,
rext = /\.([^.] )$/,
statusmap = {};
function gid() {
return idprefix idsuffix ;
}
/**
* 文件类
* @class file
* @constructor 构造函数
* @grammar new file( source ) => file
* @param {lib.file} source [lib.file](#lib.file)实例, 此source对象是带有runtime信息的。
*/
function wufile( source ) {
/**
* 文件名,包括扩展名(后缀)
* @property name
* @type {string}
*/
this.name = source.name || 'untitled';
/**
* 文件体积(字节)
* @property size
* @type {uint}
* @default 0
*/
this.size = source.size || 0;
/**
* 文件mimetype类型,与文件类型的对应关系请参考[http://t.cn/z8znfny](http://t.cn/z8znfny)
* @property type
* @type {string}
* @default 'application/octet-stream'
*/
this.type = source.type || 'application/octet-stream';
/**
* 文件最后修改日期
* @property lastmodifieddate
* @type {int}
* @default 当前时间戳
*/
this.lastmodifieddate = source.lastmodifieddate || (new date() * 1);
/**
* 文件id,每个对象具有唯一id,与文件名无关
* @property id
* @type {string}
*/
this.id = gid();
/**
* 文件扩展名,通过文件名获取,例如test.png的扩展名为png
* @property ext
* @type {string}
*/
this.ext = rext.exec( this.name ) ? regexp.$1 : '';
/**
* 状态文字说明。在不同的status语境下有不同的用途。
* @property statustext
* @type {string}
*/
this.statustext = '';
// 存储文件状态,防止通过属性直接修改
statusmap[ this.id ] = wufile.status.inited;
this.source = source;
this.loaded = 0;
this.on( 'error', function( msg ) {
this.setstatus( wufile.status.error, msg );
});
}
$.extend( wufile.prototype, {
/**
* 设置状态,状态变化时会触发`change`事件。
* @method setstatus
* @grammar setstatus( status[, statustext] );
* @param {file.status|string} status [文件状态值](#webuploader:file:file.status)
* @param {string} [statustext=''] 状态说明,常在error时使用,用http, abort,server等来标记是由于什么原因导致文件错误。
*/
setstatus: function( status, text ) {
var prevstatus = statusmap[ this.id ];
typeof text !== 'undefined' && (this.statustext = text);
if ( status !== prevstatus ) {
statusmap[ this.id ] = status;
/**
* 文件状态变化
* @event statuschange
*/
this.trigger( 'statuschange', status, prevstatus );
}
},
/**
* 获取文件状态
* @return {file.status}
* @example
文件状态具体包括以下几种类型:
{
// 初始化
inited: 0,
// 已入队列
queued: 1,
// 正在上传
progress: 2,
// 上传出错
error: 3,
// 上传成功
complete: 4,
// 上传取消
cancelled: 5
}
*/
getstatus: function() {
return statusmap[ this.id ];
},
/**
* 获取文件原始信息。
* @return {*}
*/
getsource: function() {
return this.source;
},
destroy: function() {
this.off();
delete statusmap[ this.id ];
}
});
mediator.installto( wufile.prototype );
/**
* 文件状态值,具体包括以下几种类型:
* * `inited` 初始状态
* * `queued` 已经进入队列, 等待上传
* * `progress` 上传中
* * `complete` 上传完成。
* * `error` 上传出错,可重试
* * `interrupt` 上传中断,可续传。
* * `invalid` 文件不合格,不能重试上传。会自动从队列中移除。
* * `cancelled` 文件被移除。
* @property {object} status
* @namespace file
* @class file
* @static
*/
wufile.status = {
inited: 'inited', // 初始状态
queued: 'queued', // 已经进入队列, 等待上传
progress: 'progress', // 上传中
error: 'error', // 上传出错,可重试
complete: 'complete', // 上传完成。
cancelled: 'cancelled', // 上传取消。
interrupt: 'interrupt', // 上传中断,可续传。
invalid: 'invalid' // 文件不合格,不能重试上传。
};
return wufile;
});
/**
* @fileoverview 文件队列
*/
define('queue',[
'base',
'mediator',
'file'
], function( base, mediator, wufile ) {
var $ = base.$,
status = wufile.status;
/**
* 文件队列, 用来存储各个状态中的文件。
* @class queue
* @extends mediator
*/
function queue() {
/**
* 统计文件数。
* * `numofqueue` 队列中的文件数。
* * `numofsuccess` 上传成功的文件数
* * `numofcancel` 被取消的文件数
* * `numofprogress` 正在上传中的文件数
* * `numofuploadfailed` 上传错误的文件数。
* * `numofinvalid` 无效的文件数。
* * `numofdeleted` 被移除的文件数。
* @property {object} stats
*/
this.stats = {
numofqueue: 0,
numofsuccess: 0,
numofcancel: 0,
numofprogress: 0,
numofuploadfailed: 0,
numofinvalid: 0,
numofdeleted: 0,
numofinterrupt: 0
};
// 上传队列,仅包括等待上传的文件
this._queue = [];
// 存储所有文件
this._map = {};
}
$.extend( queue.prototype, {
/**
* 将新文件加入对队列尾部
*
* @method append
* @param {file} file 文件对象
*/
append: function( file ) {
this._queue.push( file );
this._fileadded( file );
return this;
},
/**
* 将新文件加入对队列头部
*
* @method prepend
* @param {file} file 文件对象
*/
prepend: function( file ) {
this._queue.unshift( file );
this._fileadded( file );
return this;
},
/**
* 获取文件对象
*
* @method getfile
* @param {string} fileid 文件id
* @return {file}
*/
getfile: function( fileid ) {
if ( typeof fileid !== 'string' ) {
return fileid;
}
return this._map[ fileid ];
},
/**
* 从队列中取出一个指定状态的文件。
* @grammar fetch( status ) => file
* @method fetch
* @param {string} status [文件状态值](#webuploader:file:file.status)
* @return {file} [file](#webuploader:file)
*/
fetch: function( status ) {
var len = this._queue.length,
i, file;
status = status || status.queued;
for ( i = 0; i < len; i ) {
file = this._queue[ i ];
if ( status === file.getstatus() ) {
return file;
}
}
return null;
},
/**
* 对队列进行排序,能够控制文件上传顺序。
* @grammar sort( fn ) => undefined
* @method sort
* @param {function} fn 排序方法
*/
sort: function( fn ) {
if ( typeof fn === 'function' ) {
this._queue.sort( fn );
}
},
/**
* 获取指定类型的文件列表, 列表中每一个成员为[file](#webuploader:file)对象。
* @grammar getfiles( [status1[, status2 ...]] ) => array
* @method getfiles
* @param {string} [status] [文件状态值](#webuploader:file:file.status)
*/
getfiles: function() {
var sts = [].slice.call( arguments, 0 ),
ret = [],
i = 0,
len = this._queue.length,
file;
for ( ; i < len; i ) {
file = this._queue[ i ];
if ( sts.length && !~$.inarray( file.getstatus(), sts ) ) {
continue;
}
ret.push( file );
}
return ret;
},
/**
* 在队列中删除文件。
* @grammar removefile( file ) => array
* @method removefile
* @param {file} 文件对象。
*/
removefile: function( file ) {
var me = this,
existing = this._map[ file.id ];
if ( existing ) {
delete this._map[ file.id ];
file.destroy();
this.stats.numofdeleted ;
}
},
_fileadded: function( file ) {
var me = this,
existing = this._map[ file.id ];
if ( !existing ) {
this._map[ file.id ] = file;
file.on( 'statuschange', function( cur, pre ) {
me._onfilestatuschange( cur, pre );
});
}
},
_onfilestatuschange: function( curstatus, prestatus ) {
var stats = this.stats;
switch ( prestatus ) {
case status.progress:
stats.numofprogress--;
break;
case status.queued:
stats.numofqueue --;
break;
case status.error:
stats.numofuploadfailed--;
break;
case status.invalid:
stats.numofinvalid--;
break;
case status.interrupt:
stats.numofinterrupt--;
break;
}
switch ( curstatus ) {
case status.queued:
stats.numofqueue ;
break;
case status.progress:
stats.numofprogress ;
break;
case status.error:
stats.numofuploadfailed ;
break;
case status.complete:
stats.numofsuccess ;
break;
case status.cancelled:
stats.numofcancel ;
break;
case status.invalid:
stats.numofinvalid ;
break;
case status.interrupt:
stats.numofinterrupt ;
break;
}
}
});
mediator.installto( queue.prototype );
return queue;
});
/**
* @fileoverview 队列
*/
define('widgets/queue',[
'base',
'uploader',
'queue',
'file',
'lib/file',
'runtime/client',
'widgets/widget'
], function( base, uploader, queue, wufile, file, runtimeclient ) {
var $ = base.$,
rext = /\.\w $/,
status = wufile.status;
return uploader.register({
name: 'queue',
init: function( opts ) {
var me = this,
deferred, len, i, item, arr, accept, runtime;
if ( $.isplainobject( opts.accept ) ) {
opts.accept = [ opts.accept ];
}
// accept中的中生成匹配正则。
if ( opts.accept ) {
arr = [];
for ( i = 0, len = opts.accept.length; i < len; i ) {
item = opts.accept[ i ].extensions;
item && arr.push( item );
}
if ( arr.length ) {
accept = '\\.' arr.join(',')
.replace( /,/g, '$|\\.' )
.replace( /\*/g, '.*' ) '$';
}
me.accept = new regexp( accept, 'i' );
}
me.queue = new queue();
me.stats = me.queue.stats;
// 如果当前不是html5运行时,那就算了。
// 不执行后续操作
if ( this.request('predict-runtime-type') !== 'html5' ) {
return;
}
// 创建一个 html5 运行时的 placeholder
// 以至于外部添加原生 file 对象的时候能正确包裹一下供 webuploader 使用。
deferred = base.deferred();
this.placeholder = runtime = new runtimeclient('placeholder');
runtime.connectruntime({
runtimeorder: 'html5'
}, function() {
me._ruid = runtime.getruid();
deferred.resolve();
});
return deferred.promise();
},
// 为了支持外部直接添加一个原生file对象。
_wrapfile: function( file ) {
if ( !(file instanceof wufile) ) {
if ( !(file instanceof file) ) {
if ( !this._ruid ) {
throw new error('can\'t add external files.');
}
file = new file( this._ruid, file );
}
file = new wufile( file );
}
return file;
},
// 判断文件是否可以被加入队列
acceptfile: function( file ) {
var invalid = !file || !file.size || this.accept &&
// 如果名字中有后缀,才做后缀白名单处理。
rext.exec( file.name ) && !this.accept.test( file.name );
return !invalid;
},
/**
* @event beforefilequeued
* @param {file} file file对象
* @description 当文件被加入队列之前触发,此事件的handler返回值为`false`,则此文件不会被添加进入队列。
* @for uploader
*/
/**
* @event filequeued
* @param {file} file file对象
* @description 当文件被加入队列以后触发。
* @for uploader
*/
_addfile: function( file ) {
var me = this;
file = me._wrapfile( file );
// 不过类型判断允许不允许,先派送 `beforefilequeued`
if ( !me.owner.trigger( 'beforefilequeued', file ) ) {
return;
}
// 类型不匹配,则派送错误事件,并返回。
if ( !me.acceptfile( file ) ) {
me.owner.trigger( 'error', 'q_type_denied', file );
return;
}
me.queue.append( file );
me.owner.trigger( 'filequeued', file );
return file;
},
getfile: function( fileid ) {
return this.queue.getfile( fileid );
},
/**
* @event filesqueued
* @param {file} files 数组,内容为原始file(lib/file)对象。
* @description 当一批文件添加进队列以后触发。
* @for uploader
*/
/**
* @property {boolean} [auto=false]
* @namespace options
* @for uploader
* @description 设置为 true 后,不需要手动调用上传,有文件选择即开始上传。
*
*/
/**
* @method addfiles
* @grammar addfiles( file ) => undefined
* @grammar addfiles( [file1, file2 ...] ) => undefined
* @param {array of file or file} [files] files 对象 数组
* @description 添加文件到队列
* @for uploader
*/
addfile: function( files ) {
var me = this;
if ( !files.length ) {
files = [ files ];
}
files = $.map( files, function( file ) {
return me._addfile( file );
});
me.owner.trigger( 'filesqueued', files );
if ( me.options.auto ) {
settimeout(function() {
me.request('start-upload');
}, 20 );
}
},
getstats: function() {
return this.stats;
},
/**
* @event filedequeued
* @param {file} file file对象
* @description 当文件被移除队列后触发。
* @for uploader
*/
/**
* @method removefile
* @grammar removefile( file ) => undefined
* @grammar removefile( id ) => undefined
* @grammar removefile( file, true ) => undefined
* @grammar removefile( id, true ) => undefined
* @param {file|id} file file对象或这file对象的id
* @description 移除某一文件, 默认只会标记文件状态为已取消,如果第二个参数为 `true` 则会从 queue 中移除。
* @for uploader
* @example
*
* $li.on('click', '.remove-this', function() {
* uploader.removefile( file );
* })
*/
removefile: function( file, remove ) {
var me = this;
file = file.id ? file : me.queue.getfile( file );
this.request( 'cancel-file', file );
if ( remove ) {
this.queue.removefile( file );
}
},
/**
* @method getfiles
* @grammar getfiles() => array
* @grammar getfiles( status1, status2, status... ) => array
* @description 返回指定状态的文件集合,不传参数将返回所有状态的文件。
* @for uploader
* @example
* console.log( uploader.getfiles() ); // => all files
* console.log( uploader.getfiles('error') ) // => all error files.
*/
getfiles: function() {
return this.queue.getfiles.apply( this.queue, arguments );
},
fetchfile: function() {
return this.queue.fetch.apply( this.queue, arguments );
},
/**
* @method retry
* @grammar retry() => undefined
* @grammar retry( file ) => undefined
* @description 重试上传,重试指定文件,或者从出错的文件开始重新上传。
* @for uploader
* @example
* function retry() {
* uploader.retry();
* }
*/
retry: function( file, noforcestart ) {
var me = this,
files, i, len;
if ( file ) {
file = file.id ? file : me.queue.getfile( file );
file.setstatus( status.queued );
noforcestart || me.request('start-upload');
return;
}
files = me.queue.getfiles( status.error );
i = 0;
len = files.length;
for ( ; i < len; i ) {
file = files[ i ];
file.setstatus( status.queued );
}
me.request('start-upload');
},
/**
* @method sort
* @grammar sort( fn ) => undefined
* @description 排序队列中的文件,在上传之前调整可以控制上传顺序。
* @for uploader
*/
sortfiles: function() {
return this.queue.sort.apply( this.queue, arguments );
},
/**
* @event reset
* @description 当 uploader 被重置的时候触发。
* @for uploader
*/
/**
* @method reset
* @grammar reset() => undefined
* @description 重置uploader。目前只重置了队列。
* @for uploader
* @example
* uploader.reset();
*/
reset: function() {
this.owner.trigger('reset');
this.queue = new queue();
this.stats = this.queue.stats;
},
destroy: function() {
this.reset();
this.placeholder && this.placeholder.destroy();
}
});
});
/**
* @fileoverview 添加获取runtime相关信息的方法。
*/
define('widgets/runtime',[
'uploader',
'runtime/runtime',
'widgets/widget'
], function( uploader, runtime ) {
uploader.support = function() {
return runtime.hasruntime.apply( runtime, arguments );
};
/**
* @property {object} [runtimeorder=html5,flash]
* @namespace options
* @for uploader
* @description 指定运行时启动顺序。默认会想尝试 html5 是否支持,如果支持则使用 html5, 否则则使用 flash.
*
* 可以将此值设置成 `flash`,来强制使用 flash 运行时。
*/
return uploader.register({
name: 'runtime',
init: function() {
if ( !this.predictruntimetype() ) {
throw error('runtime error');
}
},
/**
* 预测uploader将采用哪个`runtime`
* @grammar predictruntimetype() => string
* @method predictruntimetype
* @for uploader
*/
predictruntimetype: function() {
var orders = this.options.runtimeorder || runtime.orders,
type = this.type,
i, len;
if ( !type ) {
orders = orders.split( /\s*,\s*/g );
for ( i = 0, len = orders.length; i < len; i ) {
if ( runtime.hasruntime( orders[ i ] ) ) {
this.type = type = orders[ i ];
break;
}
}
}
return type;
}
});
});
/**
* @fileoverview transport
*/
define('lib/transport',[
'base',
'runtime/client',
'mediator'
], function( base, runtimeclient, mediator ) {
var $ = base.$;
function transport( opts ) {
var me = this;
opts = me.options = $.extend( true, {}, transport.options, opts || {} );
runtimeclient.call( this, 'transport' );
this._blob = null;
this._formdata = opts.formdata || {};
this._headers = opts.headers || {};
this.on( 'progress', this._timeout );
this.on( 'load error', function() {
me.trigger( 'progress', 1 );
cleartimeout( me._timer );
});
}
transport.options = {
server: '',
method: 'post',
// 跨域时,是否允许携带cookie, 只有html5 runtime才有效
withcredentials: false,
fileval: 'file',
timeout: 2 * 60 * 1000, // 2分钟
formdata: {},
headers: {},
sendasbinary: false
};
$.extend( transport.prototype, {
// 添加blob, 只能添加一次,最后一次有效。
appendblob: function( key, blob, filename ) {
var me = this,
opts = me.options;
if ( me.getruid() ) {
me.disconnectruntime();
}
// 连接到blob归属的同一个runtime.
me.connectruntime( blob.ruid, function() {
me.exec('init');
});
me._blob = blob;
opts.fileval = key || opts.fileval;
opts.filename = filename || opts.filename;
},
// 添加其他字段
append: function( key, value ) {
if ( typeof key === 'object' ) {
$.extend( this._formdata, key );
} else {
this._formdata[ key ] = value;
}
},
setrequestheader: function( key, value ) {
if ( typeof key === 'object' ) {
$.extend( this._headers, key );
} else {
this._headers[ key ] = value;
}
},
send: function( method ) {
this.exec( 'send', method );
this._timeout();
},
abort: function() {
cleartimeout( this._timer );
return this.exec('abort');
},
destroy: function() {
this.trigger('destroy');
this.off();
this.exec('destroy');
this.disconnectruntime();
},
getresponse: function() {
return this.exec('getresponse');
},
getresponseasjson: function() {
return this.exec('getresponseasjson');
},
getstatus: function() {
return this.exec('getstatus');
},
_timeout: function() {
var me = this,
duration = me.options.timeout;
if ( !duration ) {
return;
}
cleartimeout( me._timer );
me._timer = settimeout(function() {
me.abort();
me.trigger( 'error', 'timeout' );
}, duration );
}
});
// 让transport具备事件功能。
mediator.installto( transport.prototype );
return transport;
});
/**
* @fileoverview 负责文件上传相关。
*/
define('widgets/upload',[
'base',
'uploader',
'file',
'lib/transport',
'widgets/widget'
], function( base, uploader, wufile, transport ) {
var $ = base.$,
ispromise = base.ispromise,
status = wufile.status;
// 添加默认配置项
$.extend( uploader.options, {
/**
* @property {boolean} [preparenextfile=false]
* @namespace options
* @for uploader
* @description 是否允许在文件传输时提前把下一个文件准备好。
* 对于一个文件的准备工作比较耗时,比如图片压缩,md5序列化。
* 如果能提前在当前文件传输期处理,可以节省总体耗时。
*/
preparenextfile: false,
/**
* @property {boolean} [chunked=false]
* @namespace options
* @for uploader
* @description 是否要分片处理大文件上传。
*/
chunked: false,
/**
* @property {boolean} [chunksize=5242880]
* @namespace options
* @for uploader
* @description 如果要分片,分多大一片? 默认大小为5m.
*/
chunksize: 5 * 1024 * 1024,
/**
* @property {boolean} [chunkretry=2]
* @namespace options
* @for uploader
* @description 如果某个分片由于网络问题出错,允许自动重传多少次?
*/
chunkretry: 2,
/**
* @property {boolean} [threads=3]
* @namespace options
* @for uploader
* @description 上传并发数。允许同时最大上传进程数。
*/
threads: 3,
/**
* @property {object} [formdata={}]
* @namespace options
* @for uploader
* @description 文件上传请求的参数表,每次发送都会发送此对象中的参数。
*/
formdata: {}
/**
* @property {object} [fileval='file']
* @namespace options
* @for uploader
* @description 设置文件上传域的name。
*/
/**
* @property {object} [method='post']
* @namespace options
* @for uploader
* @description 文件上传方式,`post`或者`get`。
*/
/**
* @property {object} [sendasbinary=false]
* @namespace options
* @for uploader
* @description 是否已二进制的流的方式发送文件,这样整个上传内容`php://input`都为文件内容,
* 其他参数在$_get数组中。
*/
});
// 负责将文件切片。
function cutefile( file, chunksize ) {
var pending = [],
blob = file.source,
total = blob.size,
chunks = chunksize ? math.ceil( total / chunksize ) : 1,
start = 0,
index = 0,
len, api;
api = {
file: file,
has: function() {
return !!pending.length;
},
shift: function() {
return pending.shift();
},
unshift: function( block ) {
pending.unshift( block );
}
};
while ( index < chunks ) {
len = math.min( chunksize, total - start );
pending.push({
file: file,
start: start,
end: chunksize ? (start len) : total,
total: total,
chunks: chunks,
chunk: index ,
cuted: api
});
start = len;
}
file.blocks = pending.concat();
file.remaning = pending.length;
return api;
}
uploader.register({
name: 'upload',
init: function() {
var owner = this.owner,
me = this;
this.runing = false;
this.progress = false;
owner
.on( 'startupload', function() {
me.progress = true;
})
.on( 'uploadfinished', function() {
me.progress = false;
});
// 记录当前正在传的数据,跟threads相关
this.pool = [];
// 缓存分好片的文件。
this.stack = [];
// 缓存即将上传的文件。
this.pending = [];
// 跟踪还有多少分片在上传中但是没有完成上传。
this.remaning = 0;
this.__tick = base.bindfn( this._tick, this );
owner.on( 'uploadcomplete', function( file ) {
// 把其他块取消了。
file.blocks && $.each( file.blocks, function( _, v ) {
v.transport && (v.transport.abort(), v.transport.destroy());
delete v.transport;
});
delete file.blocks;
delete file.remaning;
});
},
reset: function() {
this.request( 'stop-upload', true );
this.runing = false;
this.pool = [];
this.stack = [];
this.pending = [];
this.remaning = 0;
this._trigged = false;
this._promise = null;
},
/**
* @event startupload
* @description 当开始上传流程时触发。
* @for uploader
*/
/**
* 开始上传。此方法可以从初始状态调用开始上传流程,也可以从暂停状态调用,继续上传流程。
*
* 可以指定开始某一个文件。
* @grammar upload() => undefined
* @grammar upload( file | fileid) => undefined
* @method upload
* @for uploader
*/
startupload: function(file) {
var me = this;
// 移出invalid的文件
$.each( me.request( 'get-files', status.invalid ), function() {
me.request( 'remove-file', this );
});
// 如果指定了开始某个文件,则只开始指定文件。
if ( file ) {
file = file.id ? file : me.request( 'get-file', file );
if (file.getstatus() === status.interrupt) {
$.each( me.pool, function( _, v ) {
// 之前暂停过。
if (v.file !== file) {
return;
}
v.transport && v.transport.send();
});
file.setstatus( status.queued );
} else if (file.getstatus() === status.progress) {
return;
} else {
file.setstatus( status.queued );
}
} else {
$.each( me.request( 'get-files', [ status.inited ] ), function() {
this.setstatus( status.queued );
});
}
if ( me.runing ) {
return;
}
me.runing = true;
var files = [];
// 如果有暂停的,则续传
$.each( me.pool, function( _, v ) {
var file = v.file;
if ( file.getstatus() === status.interrupt ) {
files.push(file);
me._trigged = false;
v.transport && v.transport.send();
}
});
var file;
while ( (file = files.shift()) ) {
file.setstatus( status.progress );
}
file || $.each( me.request( 'get-files',
status.interrupt ), function() {
this.setstatus( status.progress );
});
me._trigged = false;
base.nexttick( me.__tick );
me.owner.trigger('startupload');
},
/**
* @event stopupload
* @description 当开始上传流程暂停时触发。
* @for uploader
*/
/**
* 暂停上传。第一个参数为是否中断上传当前正在上传的文件。
*
* 如果第一个参数是文件,则只暂停指定文件。
* @grammar stop() => undefined
* @grammar stop( true ) => undefined
* @grammar stop( file ) => undefined
* @method stop
* @for uploader
*/
stopupload: function( file, interrupt ) {
var me = this;
if (file === true) {
interrupt = file;
file = null;
}
if ( me.runing === false ) {
return;
}
// 如果只是暂停某个文件。
if ( file ) {
file = file.id ? file : me.request( 'get-file', file );
if ( file.getstatus() !== status.progress &&
file.getstatus() !== status.queued ) {
return;
}
file.setstatus( status.interrupt );
$.each( me.pool, function( _, v ) {
// 只 abort 指定的文件。
if (v.file !== file) {
return;
}
v.transport && v.transport.abort();
me._putback(v);
me._popblock(v);
});
return base.nexttick( me.__tick );
}
me.runing = false;
if (this._promise && this._promise.file) {
this._promise.file.setstatus( status.interrupt );
}
interrupt && $.each( me.pool, function( _, v ) {
v.transport && v.transport.abort();
v.file.setstatus( status.interrupt );
});
me.owner.trigger('stopupload');
},
/**
* @method cancelfile
* @grammar cancelfile( file ) => undefined
* @grammar cancelfile( id ) => undefined
* @param {file|id} file file对象或这file对象的id
* @description 标记文件状态为已取消, 同时将中断文件传输。
* @for uploader
* @example
*
* $li.on('click', '.remove-this', function() {
* uploader.cancelfile( file );
* })
*/
cancelfile: function( file ) {
file = file.id ? file : this.request( 'get-file', file );
// 如果正在上传。
file.blocks && $.each( file.blocks, function( _, v ) {
var _tr = v.transport;
if ( _tr ) {
_tr.abort();
_tr.destroy();
delete v.transport;
}
});
file.setstatus( status.cancelled );
this.owner.trigger( 'filedequeued', file );
},
/**
* 判断`uplaode`r是否正在上传中。
* @grammar isinprogress() => boolean
* @method isinprogress
* @for uploader
*/
isinprogress: function() {
return !!this.progress;
},
_getstats: function() {
return this.request('get-stats');
},
/**
* 掉过一个文件上传,直接标记指定文件为已上传状态。
* @grammar skipfile( file ) => undefined
* @method skipfile
* @for uploader
*/
skipfile: function( file, status ) {
file = file.id ? file : this.request( 'get-file', file );
file.setstatus( status || status.complete );
file.skipped = true;
// 如果正在上传。
file.blocks && $.each( file.blocks, function( _, v ) {
var _tr = v.transport;
if ( _tr ) {
_tr.abort();
_tr.destroy();
delete v.transport;
}
});
this.owner.trigger( 'uploadskip', file );
},
/**
* @event uploadfinished
* @description 当所有文件上传结束时触发。
* @for uploader
*/
_tick: function() {
var me = this,
opts = me.options,
fn, val;
// 上一个promise还没有结束,则等待完成后再执行。
if ( me._promise ) {
return me._promise.always( me.__tick );
}
// 还有位置,且还有文件要处理的话。
if ( me.pool.length < opts.threads && (val = me._nextblock()) ) {
me._trigged = false;
fn = function( val ) {
me._promise = null;
// 有可能是reject过来的,所以要检测val的类型。
val && val.file && me._startsend( val );
base.nexttick( me.__tick );
};
me._promise = ispromise( val ) ? val.always( fn ) : fn( val );
// 没有要上传的了,且没有正在传输的了。
} else if ( !me.remaning && !me._getstats().numofqueue &&
!me._getstats().numofinterrupt ) {
me.runing = false;
me._trigged || base.nexttick(function() {
me.owner.trigger('uploadfinished');
});
me._trigged = true;
}
},
_putback: function(block) {
var idx;
block.cuted.unshift(block);
idx = this.stack.indexof(block.cuted);
if (!~idx) {
this.stack.unshift(block.cuted);
}
},
_getstack: function() {
var i = 0,
act;
while ( (act = this.stack[ i ]) ) {
if ( act.has() && act.file.getstatus() === status.progress ) {
return act;
} else if (!act.has() ||
act.file.getstatus() !== status.progress &&
act.file.getstatus() !== status.interrupt ) {
// 把已经处理完了的,或者,状态为非 progress(上传中)、
// interupt(暂停中) 的移除。
this.stack.splice( --i, 1 );
}
}
return null;
},
_nextblock: function() {
var me = this,
opts = me.options,
act, next, done, preparing;
// 如果当前文件还有没有需要传输的,则直接返回剩下的。
if ( (act = this._getstack()) ) {
// 是否提前准备下一个文件
if ( opts.preparenextfile && !me.pending.length ) {
me._preparenextfile();
}
return act.shift();
// 否则,如果正在运行,则准备下一个文件,并等待完成后返回下个分片。
} else if ( me.runing ) {
// 如果缓存中有,则直接在缓存中取,没有则去queue中取。
if ( !me.pending.length && me._getstats().numofqueue ) {
me._preparenextfile();
}
next = me.pending.shift();
done = function( file ) {
if ( !file ) {
return null;
}
act = cutefile( file, opts.chunked ? opts.chunksize : 0 );
me.stack.push(act);
return act.shift();
};
// 文件可能还在prepare中,也有可能已经完全准备好了。
if ( ispromise( next) ) {
preparing = next.file;
next = next[ next.pipe ? 'pipe' : 'then' ]( done );
next.file = preparing;
return next;
}
return done( next );
}
},
/**
* @event uploadstart
* @param {file} file file对象
* @description 某个文件开始上传前触发,一个文件只会触发一次。
* @for uploader
*/
_preparenextfile: function() {
var me = this,
file = me.request('fetch-file'),
pending = me.pending,
promise;
if ( file ) {
promise = me.request( 'before-send-file', file, function() {
// 有可能文件被skip掉了。文件被skip掉后,状态坑定不是queued.
if ( file.getstatus() === status.progress ||
file.getstatus() === status.interrupt ) {
return file;
}
return me._finishfile( file );
});
me.owner.trigger( 'uploadstart', file );
file.setstatus( status.progress );
promise.file = file;
// 如果还在pending中,则替换成文件本身。
promise.done(function() {
var idx = $.inarray( promise, pending );
~idx && pending.splice( idx, 1, file );
});
// befeore-send-file的钩子就有错误发生。
promise.fail(function( reason ) {
file.setstatus( status.error, reason );
me.owner.trigger( 'uploaderror', file, reason );
me.owner.trigger( 'uploadcomplete', file );
});
pending.push( promise );
}
},
// 让出位置了,可以让其他分片开始上传
_popblock: function( block ) {
var idx = $.inarray( block, this.pool );
this.pool.splice( idx, 1 );
block.file.remaning--;
this.remaning--;
},
// 开始上传,可以被掉过。如果promise被reject了,则表示跳过此分片。
_startsend: function( block ) {
var me = this,
file = block.file,
promise;
// 有可能在 before-send-file 的 promise 期间改变了文件状态。
// 如:暂停,取消
// 我们不能中断 promise, 但是可以在 promise 完后,不做上传操作。
if ( file.getstatus() !== status.progress ) {
// 如果是中断,则还需要放回去。
if (file.getstatus() === status.interrupt) {
me._putback(block);
}
return;
}
me.pool.push( block );
me.remaning ;
// 如果没有分片,则直接使用原始的。
// 不会丢失content-type信息。
block.blob = block.chunks === 1 ? file.source :
file.source.slice( block.start, block.end );
// hook, 每个分片发送之前可能要做些异步的事情。
promise = me.request( 'before-send', block, function() {
// 有可能文件已经上传出错了,所以不需要再传输了。
if ( file.getstatus() === status.progress ) {
me._dosend( block );
} else {
me._popblock( block );
base.nexttick( me.__tick );
}
});
// 如果为fail了,则跳过此分片。
promise.fail(function() {
if ( file.remaning === 1 ) {
me._finishfile( file ).always(function() {
block.percentage = 1;
me._popblock( block );
me.owner.trigger( 'uploadcomplete', file );
base.nexttick( me.__tick );
});
} else {
block.percentage = 1;
me.updatefileprogress( file );
me._popblock( block );
base.nexttick( me.__tick );
}
});
},
/**
* @event uploadbeforesend
* @param {object} object
* @param {object} data 默认的上传参数,可以扩展此对象来控制上传参数。
* @param {object} headers 可以扩展此对象来控制上传头部。
* @description 当某个文件的分块在发送前触发,主要用来询问是否要添加附带参数,大文件在开起分片上传的前提下此事件可能会触发多次。
* @for uploader
*/
/**
* @event uploadaccept
* @param {object} object
* @param {object} ret 服务端的返回数据,json格式,如果服务端不是json格式,从ret._raw中取数据,自行解析。
* @description 当某个文件上传到服务端响应后,会派送此事件来询问服务端响应是否有效。如果此事件handler返回值为`false`, 则此文件将派送`server`类型的`uploaderror`事件。
* @for uploader
*/
/**
* @event uploadprogress
* @param {file} file file对象
* @param {number} percentage 上传进度
* @description 上传过程中触发,携带上传进度。
* @for uploader
*/
/**
* @event uploaderror
* @param {file} file file对象
* @param {string} reason 出错的code
* @description 当文件上传出错时触发。
* @for uploader
*/
/**
* @event uploadsuccess
* @param {file} file file对象
* @param {object} response 服务端返回的数据
* @description 当文件上传成功时触发。
* @for uploader
*/
/**
* @event uploadcomplete
* @param {file} [file] file对象
* @description 不管成功或者失败,文件上传完成时触发。
* @for uploader
*/
// 做上传操作。
_dosend: function( block ) {
var me = this,
owner = me.owner,
opts = me.options,
file = block.file,
tr = new transport( opts ),
data = $.extend({}, opts.formdata ),
headers = $.extend({}, opts.headers ),
requestaccept, ret;
block.transport = tr;
tr.on( 'destroy', function() {
delete block.transport;
me._popblock( block );
base.nexttick( me.__tick );
});
// 广播上传进度。以文件为单位。
tr.on( 'progress', function( percentage ) {
block.percentage = percentage;
me.updatefileprogress( file );
});
// 用来询问,是否返回的结果是有错误的。
requestaccept = function( reject ) {
var fn;
ret = tr.getresponseasjson() || {};
ret._raw = tr.getresponse();
fn = function( value ) {
reject = value;
};
// 服务端响应了,不代表成功了,询问是否响应正确。
if ( !owner.trigger( 'uploadaccept', block, ret, fn ) ) {
reject = reject || 'server';
}
return reject;
};
// 尝试重试,然后广播文件上传出错。
tr.on( 'error', function( type, flag ) {
block.retried = block.retried || 0;
// 自动重试
if ( block.chunks > 1 && ~'http,abort'.indexof( type ) &&
block.retried < opts.chunkretry ) {
block.retried ;
tr.send();
} else {
// http status 500 ~ 600
if ( !flag && type === 'server' ) {
type = requestaccept( type );
}
file.setstatus( status.error, type );
owner.trigger( 'uploaderror', file, type );
owner.trigger( 'uploadcomplete', file );
}
});
// 上传成功
tr.on( 'load', function() {
var reason;
// 如果非预期,转向上传出错。
if ( (reason = requestaccept()) ) {
tr.trigger( 'error', reason, true );
return;
}
// 全部上传完成。
if ( file.remaning === 1 ) {
me._finishfile( file, ret );
} else {
tr.destroy();
}
});
// 配置默认的上传字段。
data = $.extend( data, {
id: file.id,
name: file.name,
type: file.type,
lastmodifieddate: file.lastmodifieddate,
size: file.size
});
block.chunks > 1 && $.extend( data, {
chunks: block.chunks,
chunk: block.chunk
});
// 在发送之间可以添加字段什么的。。。
// 如果默认的字段不够使用,可以通过监听此事件来扩展
owner.trigger( 'uploadbeforesend', block, data, headers );
// 开始发送。
tr.appendblob( opts.fileval, block.blob, file.name );
tr.append( data );
tr.setrequestheader( headers );
tr.send();
},
// 完成上传。
_finishfile: function( file, ret, hds ) {
var owner = this.owner;
return owner
.request( 'after-send-file', arguments, function() {
file.setstatus( status.complete );
owner.trigger( 'uploadsuccess', file, ret, hds );
})
.fail(function( reason ) {
// 如果外部已经标记为invalid什么的,不再改状态。
if ( file.getstatus() === status.progress ) {
file.setstatus( status.error, reason );
}
owner.trigger( 'uploaderror', file, reason );
})
.always(function() {
owner.trigger( 'uploadcomplete', file );
});
},
updatefileprogress: function(file) {
var totalpercent = 0,
uploaded = 0;
if (!file.blocks) {
return;
}
$.each( file.blocks, function( _, v ) {
uploaded = (v.percentage || 0) * (v.end - v.start);
});
totalpercent = uploaded / file.size;
this.owner.trigger( 'uploadprogress', file, totalpercent || 0 );
}
});
});
/**
* @fileoverview 各种验证,包括文件总大小是否超出、单文件是否超出和文件是否重复。
*/
define('widgets/validator',[
'base',
'uploader',
'file',
'widgets/widget'
], function( base, uploader, wufile ) {
var $ = base.$,
validators = {},
api;
/**
* @event error
* @param {string} type 错误类型。
* @description 当validate不通过时,会以派送错误事件的形式通知调用者。通过`upload.on('error', handler)`可以捕获到此类错误,目前有以下错误会在特定的情况下派送错来。
*
* * `q_exceed_num_limit` 在设置了`filenumlimit`且尝试给`uploader`添加的文件数量超出这个值时派送。
* * `q_exceed_size_limit` 在设置了`q_exceed_size_limit`且尝试给`uploader`添加的文件总大小超出这个值时派送。
* * `q_type_denied` 当文件类型不满足时触发。。
* @for uploader
*/
// 暴露给外面的api
api = {
// 添加验证器
addvalidator: function( type, cb ) {
validators[ type ] = cb;
},
// 移除验证器
removevalidator: function( type ) {
delete validators[ type ];
}
};
// 在uploader初始化的时候启动validators的初始化
uploader.register({
name: 'validator',
init: function() {
var me = this;
base.nexttick(function() {
$.each( validators, function() {
this.call( me.owner );
});
});
}
});
/**
* @property {int} [filenumlimit=undefined]
* @namespace options
* @for uploader
* @description 验证文件总数量, 超出则不允许加入队列。
*/
api.addvalidator( 'filenumlimit', function() {
var uploader = this,
opts = uploader.options,
count = 0,
max = parseint( opts.filenumlimit, 10 ),
flag = true;
if ( !max ) {
return;
}
uploader.on( 'beforefilequeued', function( file ) {
if ( count >= max && flag ) {
flag = false;
this.trigger( 'error', 'q_exceed_num_limit', max, file );
settimeout(function() {
flag = true;
}, 1 );
}
return count >= max ? false : true;
});
uploader.on( 'filequeued', function() {
count ;
});
uploader.on( 'filedequeued', function() {
count--;
});
uploader.on( 'reset', function() {
count = 0;
});
});
/**
* @property {int} [filesizelimit=undefined]
* @namespace options
* @for uploader
* @description 验证文件总大小是否超出限制, 超出则不允许加入队列。
*/
api.addvalidator( 'filesizelimit', function() {
var uploader = this,
opts = uploader.options,
count = 0,
max = parseint( opts.filesizelimit, 10 ),
flag = true;
if ( !max ) {
return;
}
uploader.on( 'beforefilequeued', function( file ) {
var invalid = count file.size > max;
if ( invalid && flag ) {
flag = false;
this.trigger( 'error', 'q_exceed_size_limit', max, file );
settimeout(function() {
flag = true;
}, 1 );
}
return invalid ? false : true;
});
uploader.on( 'filequeued', function( file ) {
count = file.size;
});
uploader.on( 'filedequeued', function( file ) {
count -= file.size;
});
uploader.on( 'reset', function() {
count = 0;
});
});
/**
* @property {int} [filesinglesizelimit=undefined]
* @namespace options
* @for uploader
* @description 验证单个文件大小是否超出限制, 超出则不允许加入队列。
*/
api.addvalidator( 'filesinglesizelimit', function() {
var uploader = this,
opts = uploader.options,
max = opts.filesinglesizelimit;
if ( !max ) {
return;
}
uploader.on( 'beforefilequeued', function( file ) {
if ( file.size > max ) {
file.setstatus( wufile.status.invalid, 'exceed_size' );
this.trigger( 'error', 'f_exceed_size', max, file );
return false;
}
});
});
/**
* @property {boolean} [duplicate=undefined]
* @namespace options
* @for uploader
* @description 去重, 根据文件名字、文件大小和最后修改时间来生成hash key.
*/
api.addvalidator( 'duplicate', function() {
var uploader = this,
opts = uploader.options,
mapping = {};
if ( opts.duplicate ) {
return;
}
function hashstring( str ) {
var hash = 0,
i = 0,
len = str.length,
_char;
for ( ; i < len; i ) {
_char = str.charcodeat( i );
hash = _char (hash << 6) (hash << 16) - hash;
}
return hash;
}
uploader.on( 'beforefilequeued', function( file ) {
var hash = file.__hash || (file.__hash = hashstring( file.name
file.size file.lastmodifieddate ));
// 已经重复了
if ( mapping[ hash ] ) {
this.trigger( 'error', 'f_duplicate', file );
return false;
}
});
uploader.on( 'filequeued', function( file ) {
var hash = file.__hash;
hash && (mapping[ hash ] = true);
});
uploader.on( 'filedequeued', function( file ) {
var hash = file.__hash;
hash && (delete mapping[ hash ]);
});
uploader.on( 'reset', function() {
mapping = {};
});
});
return api;
});
/**
* @fileoverview runtime管理器,负责runtime的选择, 连接
*/
define('runtime/compbase',[],function() {
function compbase( owner, runtime ) {
this.owner = owner;
this.options = owner.options;
this.getruntime = function() {
return runtime;
};
this.getruid = function() {
return runtime.uid;
};
this.trigger = function() {
return owner.trigger.apply( owner, arguments );
};
}
return compbase;
});
/**
* @fileoverview flashruntime
*/
define('runtime/flash/runtime',[
'base',
'runtime/runtime',
'runtime/compbase'
], function( base, runtime, compbase ) {
var $ = base.$,
type = 'flash',
components = {};
function getflashversion() {
var version;
try {
version = navigator.plugins[ 'shockwave flash' ];
version = version.description;
} catch ( ex ) {
try {
version = new activexobject('shockwaveflash.shockwaveflash')
.getvariable('$version');
} catch ( ex2 ) {
version = '0.0';
}
}
version = version.match( /\d /g );
return parsefloat( version[ 0 ] '.' version[ 1 ], 10 );
}
function flashruntime() {
var pool = {},
clients = {},
destroy = this.destroy,
me = this,
jsreciver = base.guid('webuploader_');
runtime.apply( me, arguments );
me.type = type;
// 这个方法的调用者,实际上是runtimeclient
me.exec = function( comp, fn/*, args...*/ ) {
var client = this,
uid = client.uid,
args = base.slice( arguments, 2 ),
instance;
clients[ uid ] = client;
if ( components[ comp ] ) {
if ( !pool[ uid ] ) {
pool[ uid ] = new components[ comp ]( client, me );
}
instance = pool[ uid ];
if ( instance[ fn ] ) {
return instance[ fn ].apply( instance, args );
}
}
return me.flashexec.apply( client, arguments );
};
function handler( evt, obj ) {
var type = evt.type || evt,
parts, uid;
parts = type.split('::');
uid = parts[ 0 ];
type = parts[ 1 ];
// console.log.apply( console, arguments );
if ( type === 'ready' && uid === me.uid ) {
me.trigger('ready');
} else if ( clients[ uid ] ) {
clients[ uid ].trigger( type.tolowercase(), evt, obj );
}
// base.log( evt, obj );
}
// flash的接受器。
window[ jsreciver ] = function() {
var args = arguments;
// 为了能捕获得到。
settimeout(function() {
handler.apply( null, args );
}, 1 );
};
this.jsreciver = jsreciver;
this.destroy = function() {
// @todo 删除池子中的所有实例
return destroy && destroy.apply( this, arguments );
};
this.flashexec = function( comp, fn ) {
var flash = me.getflash(),
args = base.slice( arguments, 2 );
return flash.exec( this.uid, comp, fn, args );
};
// @todo
}
base.inherits( runtime, {
constructor: flashruntime,
init: function() {
var container = this.getcontainer(),
opts = this.options,
html;
// if not the minimal height, shims are not initialized
// in older browsers (e.g ff3.6, ie6,7,8, safari 4.0,5.0, etc)
container.css({
position: 'absolute',
top: '-8px',
left: '-8px',
width: '9px',
height: '9px',
overflow: 'hidden'
});
// insert flash object
html = '';
container.html( html );
},
getflash: function() {
if ( this._flash ) {
return this._flash;
}
this._flash = $( '#' this.uid ).get( 0 );
return this._flash;
}
});
flashruntime.register = function( name, component ) {
component = components[ name ] = base.inherits( compbase, $.extend({
// @todo fix this later
flashexec: function() {
var owner = this.owner,
runtime = this.getruntime();
return runtime.flashexec.apply( owner, arguments );
}
}, component ) );
return component;
};
if ( getflashversion() >= 11.4 ) {
runtime.addruntime( type, flashruntime );
}
return flashruntime;
});
/**
* @fileoverview filepicker
*/
define('runtime/flash/filepicker',[
'base',
'runtime/flash/runtime'
], function( base, flashruntime ) {
var $ = base.$;
return flashruntime.register( 'filepicker', {
init: function( opts ) {
var copy = $.extend({}, opts ),
len, i;
// 修复flash再没有设置title的情况下无法弹出flash文件选择框的bug.
len = copy.accept && copy.accept.length;
for ( i = 0; i < len; i ) {
if ( !copy.accept[ i ].title ) {
copy.accept[ i ].title = 'files';
}
}
delete copy.button;
delete copy.id;
delete copy.container;
this.flashexec( 'filepicker', 'init', copy );
},
destroy: function() {
this.flashexec( 'filepicker', 'destroy' );
}
});
});
/**
* @fileoverview 图片压缩
*/
define('runtime/flash/image',[
'runtime/flash/runtime'
], function( flashruntime ) {
return flashruntime.register( 'image', {
// init: function( options ) {
// var owner = this.owner;
// this.flashexec( 'image', 'init', options );
// owner.on( 'load', function() {
// debugger;
// });
// },
loadfromblob: function( blob ) {
var owner = this.owner;
owner.info() && this.flashexec( 'image', 'info', owner.info() );
owner.meta() && this.flashexec( 'image', 'meta', owner.meta() );
this.flashexec( 'image', 'loadfromblob', blob.uid );
}
});
});
/**
* @fileoverview blob html实现
*/
define('runtime/flash/blob',[
'runtime/flash/runtime',
'lib/blob'
], function( flashruntime, blob ) {
return flashruntime.register( 'blob', {
slice: function( start, end ) {
var blob = this.flashexec( 'blob', 'slice', start, end );
return new blob( blob.uid, blob );
}
});
});
/**
* @fileoverview transport flash实现
*/
define('runtime/flash/transport',[
'base',
'runtime/flash/runtime',
'runtime/client'
], function( base, flashruntime, runtimeclient ) {
var $ = base.$;
return flashruntime.register( 'transport', {
init: function() {
this._status = 0;
this._response = null;
this._responsejson = null;
},
send: function() {
var owner = this.owner,
opts = this.options,
xhr = this._initajax(),
blob = owner._blob,
server = opts.server,
binary;
xhr.connectruntime( blob.ruid );
if ( opts.sendasbinary ) {
server = (/\?/.test( server ) ? '&' : '?')
$.param( owner._formdata );
binary = blob.uid;
} else {
$.each( owner._formdata, function( k, v ) {
xhr.exec( 'append', k, v );
});
xhr.exec( 'appendblob', opts.fileval, blob.uid,
opts.filename || owner._formdata.name || '' );
}
this._setrequestheader( xhr, opts.headers );
xhr.exec( 'send', {
method: opts.method,
url: server,
forceurlstream: opts.forceurlstream,
mimetype: 'application/octet-stream'
}, binary );
},
getstatus: function() {
return this._status;
},
getresponse: function() {
return this._response || '';
},
getresponseasjson: function() {
return this._responsejson;
},
abort: function() {
var xhr = this._xhr;
if ( xhr ) {
xhr.exec('abort');
xhr.destroy();
this._xhr = xhr = null;
}
},
destroy: function() {
this.abort();
},
_initajax: function() {
var me = this,
xhr = new runtimeclient('xmlhttprequest');
xhr.on( 'uploadprogress progress', function( e ) {
var percent = e.loaded / e.total;
percent = math.min( 1, math.max( 0, percent ) );
return me.trigger( 'progress', percent );
});
xhr.on( 'load', function() {
var status = xhr.exec('getstatus'),
readbody = false,
err = '',
p;
xhr.off();
me._xhr = null;
if ( status >= 200 && status < 300 ) {
readbody = true;
} else if ( status >= 500 && status < 600 ) {
readbody = true;
err = 'server';
} else {
err = 'http';
}
if ( readbody ) {
me._response = xhr.exec('getresponse');
me._response = decodeuricomponent( me._response );
// flash 处理可能存在 bug, 没辙只能靠 js 了
// try {
// me._responsejson = xhr.exec('getresponseasjson');
// } catch ( error ) {
p = window.json && window.json.parse || function( s ) {
try {
return new function('return ' s).call();
} catch ( err ) {
return {};
}
};
me._responsejson = me._response ? p(me._response) : {};
// }
}
xhr.destroy();
xhr = null;
return err ? me.trigger( 'error', err ) : me.trigger('load');
});
xhr.on( 'error', function() {
xhr.off();
me._xhr = null;
me.trigger( 'error', 'http' );
});
me._xhr = xhr;
return xhr;
},
_setrequestheader: function( xhr, headers ) {
$.each( headers, function( key, val ) {
xhr.exec( 'setrequestheader', key, val );
});
}
});
});
/**
* @fileoverview 只有flash实现的文件版本。
*/
define('preset/flashonly',[
'base',
// widgets
'widgets/filepicker',
'widgets/image',
'widgets/queue',
'widgets/runtime',
'widgets/upload',
'widgets/validator',
// runtimes
// flash
'runtime/flash/filepicker',
'runtime/flash/image',
'runtime/flash/blob',
'runtime/flash/transport'
], function( base ) {
return base;
});
define('webuploader',[
'preset/flashonly'
], function( preset ) {
return preset;
});
return require('webuploader');
});