").append(b.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},b.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){b.fn[t]=function(e){return this.on(t,e)}}),b.each(["get","post"],function(e,n){b[n]=function(e,r,i,o){return b.isFunction(r)&&(o=o||i,i=r,r=t),b.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),b.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Nn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Mn(Mn(e,b.ajaxSettings),t):Mn(b.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,u,l,c,p=b.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?b(f):b.event,h=b.Deferred(),g=b.Callbacks("once memory"),m=p.statusCode||{},y={},v={},x=0,T="canceled",N={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else N.always(e[N.status]);return this},abort:function(e){var t=e||T;return l&&l.abort(t),k(0,t),this}};if(h.promise(N).complete=g.add,N.success=N.done,N.error=N.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=b.trim(p.dataType||"*").toLowerCase().match(w)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?80:443))==(mn[3]||("http:"===mn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=b.param(p.data,p.traditional)),qn(An,p,n,N),2===x)return N;u=p.global,u&&0===b.active++&&b.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Cn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(b.lastModified[o]&&N.setRequestHeader("If-Modified-Since",b.lastModified[o]),b.etag[o]&&N.setRequestHeader("If-None-Match",b.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&N.setRequestHeader("Content-Type",p.contentType),N.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)N.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,N,p)===!1||2===x))return N.abort();T="abort";for(i in{success:1,error:1,complete:1})N[i](p[i]);if(l=qn(jn,p,n,N)){N.readyState=1,u&&d.trigger("ajaxSend",[N,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){N.abort("timeout")},p.timeout));try{x=1,l.send(y,k)}catch(C){if(!(2>x))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,C=n;2!==x&&(x=2,s&&clearTimeout(s),l=t,a=i||"",N.readyState=e>0?4:0,r&&(w=_n(p,N,r)),e>=200&&300>e||304===e?(p.ifModified&&(T=N.getResponseHeader("Last-Modified"),T&&(b.lastModified[o]=T),T=N.getResponseHeader("etag"),T&&(b.etag[o]=T)),204===e?(c=!0,C="nocontent"):304===e?(c=!0,C="notmodified"):(c=Fn(p,w),C=c.state,y=c.data,v=c.error,c=!v)):(v=C,(e||!C)&&(C="error",0>e&&(e=0))),N.status=e,N.statusText=(n||C)+"",c?h.resolveWith(f,[y,C,N]):h.rejectWith(f,[N,C,v]),N.statusCode(m),m=t,u&&d.trigger(c?"ajaxSuccess":"ajaxError",[N,p,c?y:v]),g.fireWith(f,[N,C]),u&&(d.trigger("ajaxComplete",[N,p]),--b.active||b.event.trigger("ajaxStop")))}return N},getScript:function(e,n){return b.get(e,t,n,"script")},getJSON:function(e,t,n){return b.get(e,t,n,"json")}});function _n(e,n,r){var i,o,a,s,u=e.contents,l=e.dataTypes,c=e.responseFields;for(s in c)s in r&&(n[c[s]]=r[s]);while("*"===l[0])l.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in u)if(u[s]&&u[s].test(o)){l.unshift(s);break}if(l[0]in r)a=l[0];else{for(s in r){if(!l[0]||e.converters[s+" "+l[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function Fn(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(i in e.converters)a[i.toLowerCase()]=e.converters[i];for(;r=u[++s];)if("*"!==r){if("*"!==l&&l!==r){if(i=a[l+" "+r]||a["* "+r],!i)for(n in a)if(o=n.split(" "),o[1]===r&&(i=a[l+" "+o[0]]||a["* "+o[0]])){i===!0?i=a[n]:a[n]!==!0&&(r=o[0],u.splice(s--,0,r));break}if(i!==!0)if(i&&e["throws"])t=i(t);else try{t=i(t)}catch(c){return{state:"parsererror",error:i?c:"No conversion from "+l+" to "+r}}}l=r}return{state:"success",data:t}}b.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return b.globalEval(e),e}}}),b.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),b.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=o.head||b("head")[0]||o.documentElement;return{send:function(t,i){n=o.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var On=[],Bn=/(=)\?(?=&|$)|\?\?/;b.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=On.pop()||b.expando+"_"+vn++;return this[e]=!0,e}}),b.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=b.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||b.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,On.push(o)),s&&b.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}b.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=b.ajaxSettings.xhr(),b.support.cors=!!Rn&&"withCredentials"in Rn,Rn=b.support.ajax=!!Rn,Rn&&b.ajaxTransport(function(n){if(!n.crossDomain||b.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,p;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=b.noop,$n&&delete Pn[a]),i)4!==u.readyState&&u.abort();else{p={},s=u.status,l=u.getAllResponseHeaders(),"string"==typeof u.responseText&&(p.text=u.responseText);try{c=u.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,l)},n.async?4===u.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},b(e).unload($n)),Pn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+x+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=Yn.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(b.cssNumber[e]?"":"px"),"px"!==r&&s){s=b.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,b.style(i.elem,e,s+r);while(u!==(u=i.cur()/a)&&1!==u&&--l)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=b.now()}function Zn(e,t){b.each(t,function(t,n){var r=(Qn[t]||[]).concat(Qn["*"]),i=0,o=r.length;for(;o>i;i++)if(r[i].call(e,t,n))return})}function er(e,t,n){var r,i,o=0,a=Gn.length,s=b.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;for(;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:b.extend({},t),opts:b.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=b.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(tr(c,l.opts.specialEasing);a>o;o++)if(r=Gn[o].call(l,e,c,l.opts))return r;return Zn(l,c),b.isFunction(l.opts.start)&&l.opts.start.call(e,l),b.fx.timer(b.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function tr(e,t){var n,r,i,o,a;for(i in e)if(r=b.camelCase(i),o=t[r],n=e[i],b.isArray(n)&&(o=n[1],n=e[i]=n[0]),i!==r&&(e[r]=n,delete e[i]),a=b.cssHooks[r],a&&"expand"in a){n=a.expand(n),delete e[r];for(i in n)i in e||(e[i]=n[i],t[i]=o)}else t[r]=o}b.Animation=b.extend(er,{tweener:function(e,t){b.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,u,l,c,p,f=this,d=e.style,h={},g=[],m=e.nodeType&&nn(e);n.queue||(c=b._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,p=c.empty.fire,c.empty.fire=function(){c.unqueued||p()}),c.unqueued++,f.always(function(){f.always(function(){c.unqueued--,b.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===b.css(e,"display")&&"none"===b.css(e,"float")&&(b.support.inlineBlockNeedsLayout&&"inline"!==un(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",b.support.shrinkWrapBlocks||f.always(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(i in t)if(a=t[i],Vn.exec(a)){if(delete t[i],u=u||"toggle"===a,a===(m?"hide":"show"))continue;g.push(i)}if(o=g.length){s=b._data(e,"fxshow")||b._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?b(e).show():f.done(function(){b(e).hide()}),f.done(function(){var t;b._removeData(e,"fxshow");for(t in h)b.style(e,t,h[t])});for(i=0;o>i;i++)r=g[i],l=f.createTween(r,m?s[r]:0),h[r]=s[r]||b.style(e,r),r in s||(s[r]=l.start,m&&(l.end=l.start,l.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}b.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(b.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?b.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=b.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){b.fx.step[e.prop]?b.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[b.cssProps[e.prop]]||b.cssHooks[e.prop])?b.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},b.each(["toggle","show","hide"],function(e,t){var n=b.fn[t];b.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),b.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=b.isEmptyObject(e),o=b.speed(t,n,r),a=function(){var t=er(this,b.extend({},e),o);a.finish=function(){t.stop(!0)},(i||b._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=b.timers,a=b._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&b.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=b._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=b.timers,a=r?r.length:0;for(n.finish=!0,b.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}b.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){b.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),b.speed=function(e,t,n){var r=e&&"object"==typeof e?b.extend({},e):{complete:n||!n&&t||b.isFunction(e)&&e,duration:e,easing:n&&t||t&&!b.isFunction(t)&&t};return r.duration=b.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in b.fx.speeds?b.fx.speeds[r.duration]:b.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){b.isFunction(r.old)&&r.old.call(this),r.queue&&b.dequeue(this,r.queue)},r},b.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},b.timers=[],b.fx=rr.prototype.init,b.fx.tick=function(){var e,n=b.timers,r=0;for(Xn=b.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||b.fx.stop(),Xn=t},b.fx.timer=function(e){e()&&b.timers.push(e)&&b.fx.start()},b.fx.interval=13,b.fx.start=function(){Un||(Un=setInterval(b.fx.tick,b.fx.interval))},b.fx.stop=function(){clearInterval(Un),Un=null},b.fx.speeds={slow:600,fast:200,_default:400},b.fx.step={},b.expr&&b.expr.filters&&(b.expr.filters.animated=function(e){return b.grep(b.timers,function(t){return e===t.elem}).length}),b.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){b.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,b.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},b.offset={setOffset:function(e,t,n){var r=b.css(e,"position");"static"===r&&(e.style.position="relative");var i=b(e),o=i.offset(),a=b.css(e,"top"),s=b.css(e,"left"),u=("absolute"===r||"fixed"===r)&&b.inArray("auto",[a,s])>-1,l={},c={},p,f;u?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),b.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(l.top=t.top-o.top+p),null!=t.left&&(l.left=t.left-o.left+f),"using"in t?t.using.call(e,l):i.css(l)}},b.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===b.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),b.nodeName(e[0],"html")||(n=e.offset()),n.top+=b.css(e[0],"borderTopWidth",!0),n.left+=b.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-b.css(r,"marginTop",!0),left:t.left-n.left-b.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.documentElement;while(e&&!b.nodeName(e,"html")&&"static"===b.css(e,"position"))e=e.offsetParent;return e||o.documentElement})}}),b.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);b.fn[e]=function(i){return b.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?b(a).scrollLeft():o,r?o:b(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return b.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}b.each({Height:"height",Width:"width"},function(e,n){b.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){b.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return b.access(this,function(n,r,i){var o;return b.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?b.css(n,r,s):b.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=b,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return b})})(window);
================================================
FILE: _draft/music/md5.js
================================================
(function( window ) {
function md5cycle(x, k) {
var a = x[0],
b = x[1],
c = x[2],
d = x[3];
a = ff(a, b, c, d, k[0], 7, -680876936);
d = ff(d, a, b, c, k[1], 12, -389564586);
c = ff(c, d, a, b, k[2], 17, 606105819);
b = ff(b, c, d, a, k[3], 22, -1044525330);
a = ff(a, b, c, d, k[4], 7, -176418897);
d = ff(d, a, b, c, k[5], 12, 1200080426);
c = ff(c, d, a, b, k[6], 17, -1473231341);
b = ff(b, c, d, a, k[7], 22, -45705983);
a = ff(a, b, c, d, k[8], 7, 1770035416);
d = ff(d, a, b, c, k[9], 12, -1958414417);
c = ff(c, d, a, b, k[10], 17, -42063);
b = ff(b, c, d, a, k[11], 22, -1990404162);
a = ff(a, b, c, d, k[12], 7, 1804603682);
d = ff(d, a, b, c, k[13], 12, -40341101);
c = ff(c, d, a, b, k[14], 17, -1502002290);
b = ff(b, c, d, a, k[15], 22, 1236535329);
a = gg(a, b, c, d, k[1], 5, -165796510);
d = gg(d, a, b, c, k[6], 9, -1069501632);
c = gg(c, d, a, b, k[11], 14, 643717713);
b = gg(b, c, d, a, k[0], 20, -373897302);
a = gg(a, b, c, d, k[5], 5, -701558691);
d = gg(d, a, b, c, k[10], 9, 38016083);
c = gg(c, d, a, b, k[15], 14, -660478335);
b = gg(b, c, d, a, k[4], 20, -405537848);
a = gg(a, b, c, d, k[9], 5, 568446438);
d = gg(d, a, b, c, k[14], 9, -1019803690);
c = gg(c, d, a, b, k[3], 14, -187363961);
b = gg(b, c, d, a, k[8], 20, 1163531501);
a = gg(a, b, c, d, k[13], 5, -1444681467);
d = gg(d, a, b, c, k[2], 9, -51403784);
c = gg(c, d, a, b, k[7], 14, 1735328473);
b = gg(b, c, d, a, k[12], 20, -1926607734);
a = hh(a, b, c, d, k[5], 4, -378558);
d = hh(d, a, b, c, k[8], 11, -2022574463);
c = hh(c, d, a, b, k[11], 16, 1839030562);
b = hh(b, c, d, a, k[14], 23, -35309556);
a = hh(a, b, c, d, k[1], 4, -1530992060);
d = hh(d, a, b, c, k[4], 11, 1272893353);
c = hh(c, d, a, b, k[7], 16, -155497632);
b = hh(b, c, d, a, k[10], 23, -1094730640);
a = hh(a, b, c, d, k[13], 4, 681279174);
d = hh(d, a, b, c, k[0], 11, -358537222);
c = hh(c, d, a, b, k[3], 16, -722521979);
b = hh(b, c, d, a, k[6], 23, 76029189);
a = hh(a, b, c, d, k[9], 4, -640364487);
d = hh(d, a, b, c, k[12], 11, -421815835);
c = hh(c, d, a, b, k[15], 16, 530742520);
b = hh(b, c, d, a, k[2], 23, -995338651);
a = ii(a, b, c, d, k[0], 6, -198630844);
d = ii(d, a, b, c, k[7], 10, 1126891415);
c = ii(c, d, a, b, k[14], 15, -1416354905);
b = ii(b, c, d, a, k[5], 21, -57434055);
a = ii(a, b, c, d, k[12], 6, 1700485571);
d = ii(d, a, b, c, k[3], 10, -1894986606);
c = ii(c, d, a, b, k[10], 15, -1051523);
b = ii(b, c, d, a, k[1], 21, -2054922799);
a = ii(a, b, c, d, k[8], 6, 1873313359);
d = ii(d, a, b, c, k[15], 10, -30611744);
c = ii(c, d, a, b, k[6], 15, -1560198380);
b = ii(b, c, d, a, k[13], 21, 1309151649);
a = ii(a, b, c, d, k[4], 6, -145523070);
d = ii(d, a, b, c, k[11], 10, -1120210379);
c = ii(c, d, a, b, k[2], 15, 718787259);
b = ii(b, c, d, a, k[9], 21, -343485551);
x[0] = add32(a, x[0]);
x[1] = add32(b, x[1]);
x[2] = add32(c, x[2]);
x[3] = add32(d, x[3]);
}
function cmn(q, a, b, x, s, t) {
a = add32(add32(a, q), add32(x, t));
return add32((a << s) | (a >>> (32 - s)), b);
}
function ff(a, b, c, d, x, s, t) {
return cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function gg(a, b, c, d, x, s, t) {
return cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function hh(a, b, c, d, x, s, t) {
return cmn(b ^ c ^ d, a, b, x, s, t);
}
function ii(a, b, c, d, x, s, t) {
return cmn(c ^ (b | (~d)), a, b, x, s, t);
}
function md51(s) {
txt = '';
var n = s.length,
state = [1732584193, -271733879, -1732584194, 271733878],
i;
for (i = 64; i <= s.length; i += 64) {
md5cycle(state, md5blk(s.substring(i - 64, i)));
}
s = s.substring(i - 64);
var tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (i = 0; i < s.length; i++)
tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i = 0; i < 16; i++) tail[i] = 0;
}
tail[14] = n * 8;
md5cycle(state, tail);
return state;
}
/* there needs to be support for Unicode here,
* unless we pretend that we can redefine the MD-5
* algorithm for multi-byte characters (perhaps
* by adding every four 16-bit characters and
* shortening the sum to 32 bits). Otherwise
* I suggest performing MD-5 as if every character
* was two bytes--e.g., 0040 0025 = @%--but then
* how will an ordinary MD-5 sum be matched?
* There is no way to standardize text to something
* like UTF-8 before transformation; speed cost is
* utterly prohibitive. The JavaScript standard
* itself needs to look at this: it should start
* providing access to strings as preformed UTF-8
* 8-bit unsigned value arrays.
*/
function md5blk(s) { /* I figured global was faster. */
var md5blks = [],
i; /* Andy King said do it this way. */
for (i = 0; i < 64; i += 4) {
md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
}
return md5blks;
}
var hex_chr = '0123456789abcdef'.split('');
function rhex(n) {
var s = '',
j = 0;
for (; j < 4; j++)
s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
return s;
}
function hex(x) {
for (var i = 0; i < x.length; i++)
x[i] = rhex(x[i]);
return x.join('');
}
function md5(s) {
return hex(md51(s));
}
/* this function is much faster,
so if possible we use it. Some IEs
are the only ones I know of that
need the idiotic second function,
generated by an if clause. */
var add32 = function(a, b) {
return (a + b) & 0xFFFFFFFF;
}
if (md5('hello') != '5d41402abc4b2a76b9719d911017c592') {
add32 = function(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF),
msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
}
window.md5 = md5;
})( this );
================================================
FILE: _draft/music/server/fileupload.php
================================================
')
.appendTo($wrap.find('.queueList')),
// 状态栏,包括进度和控制按钮
$statusBar = $wrap.find('.statusBar'),
// 文件总体选择信息。
$info = $statusBar.find('.info'),
// 上传按钮
$upload = $wrap.find('.uploadBtn'),
// 没选择文件之前的内容。
$placeHolder = $wrap.find('.placeholder'),
$progress = $statusBar.find('.progress').hide(),
// 添加的文件数量
fileCount = 0,
// 添加的文件总大小
fileSize = 0,
// 可能有pedding, ready, uploading, confirm, done.
state = 'pedding',
// 所有文件的进度信息,key为file id
percentages = {},
// WebUploader实例
uploader;
// 实例化
uploader = WebUploader.create({
pick: '#filePicker',
dnd: '#dndArea',
chunked: true,
accept: '',
server: './server/fileupload.php',
// server: 'http://www.2betop.net/fileupload.php',
});
// 添加“添加文件”的按钮,
uploader.addButton({
id: '#filePicker2',
label: '继续添加'
});
// 当有文件添加进来时执行,负责view的创建
function addFile(file) {
var $li = $('
' +
'' + file.name + '
' +
'
' +
'
' +
' '),
$btns = $('
' +
'删除 ' + '
').appendTo($li),
$prgress = $li.find('p.progress span'),
$wrap = $li.find('p.imgWrap'),
$info = $('
'),
showError = function(code) {
switch (code) {
case 'interrupt':
text = '上传暂停';
break;
default:
text = '上传失败,请重试';
break;
}
$info.text(text).appendTo($li);
};
if (file.getStatus() === 'invalid') {
showError(file.statusText);
} else {
$wrap.text('不能预览');
percentages[file.id] = [file.size, 0];
file.rotation = 0;
}
file.on('statuschange', function(cur, prev) {
if (prev === 'progress') {
$prgress.hide().width(0);
} else if (prev === 'queued') {
$li.off('mouseenter mouseleave');
$btns.remove();
}
// 成功
if (cur === 'error' || cur === 'invalid') {
showError(file.statusText);
percentages[file.id][1] = 1;
} else if (cur === 'interrupt') {
showError('interrupt');
} else if (cur === 'queued') {
percentages[file.id][1] = 0;
} else if (cur === 'progress') {
$info.remove();
$prgress.css({
display: 'block',
width: '10%'
});
} else if (cur === 'complete') {
$li.append('
');
}
$li.removeClass('state-' + prev).addClass('state-' + cur);
});
$li.on('mouseenter', function() {
$btns.stop().animate({
height: 30
});
});
$li.on('mouseleave', function() {
$btns.stop().animate({
height: 0
});
});
$btns.on('click', 'span', function() {
uploader.removeFile(file);
});
$li.appendTo($queue);
}
// 负责view的销毁
function removeFile(file) {
var $li = $('#' + file.id);
delete percentages[file.id];
updateTotalProgress();
$li.off().find('.file-panel').off().end().remove();
}
function updateTotalProgress() {
var loaded = 0,
total = 0,
spans = $progress.children(),
percent;
$.each(percentages, function(k, v) {
total += v[0];
loaded += v[0] * v[1];
});
percent = total ? loaded / total : 0;
spans.eq(0).text(Math.round(percent * 100) + '%');
spans.eq(1).css('width', Math.round(percent * 100) + '%');
updateStatus();
}
function updateStatus() {
var text = '',
stats;
if (state === 'ready') {
text = '选中' + fileCount + '张图片,共' +
WebUploader.formatSize(fileSize) + '。';
} else if (state === 'confirm') {
stats = uploader.getStats();
if (stats.uploadFailNum) {
text = '已成功上传' + stats.successNum + '张照片至XX相册,' +
stats.uploadFailNum + '张照片上传失败,
重新上传 失败图片或
忽略 '
}
} else {
stats = uploader.getStats();
text = '共' + fileCount + '张(' +
WebUploader.formatSize(fileSize) +
'),已上传' + stats.successNum + '张';
if (stats.uploadFailNum) {
text += ',失败' + stats.uploadFailNum + '张';
}
}
$info.html(text);
}
function setState(val) {
var file, stats;
if (val === state) {
return;
}
$upload.removeClass('state-' + state);
$upload.addClass('state-' + val);
state = val;
switch (state) {
case 'pedding':
$placeHolder.removeClass('element-invisible');
$queue.hide();
$statusBar.addClass('element-invisible');
uploader.refresh();
break;
case 'ready':
$placeHolder.addClass('element-invisible');
$('#filePicker2').removeClass('element-invisible');
$queue.show();
$statusBar.removeClass('element-invisible');
uploader.refresh();
break;
case 'uploading':
$('#filePicker2').addClass('element-invisible');
$progress.show();
$upload.text('暂停上传');
break;
case 'paused':
$progress.show();
$upload.text('继续上传');
break;
case 'confirm':
$progress.hide();
$upload.text('开始上传').addClass('disabled');
stats = uploader.getStats();
if (stats.successNum && !stats.uploadFailNum) {
setState('finish');
return;
}
break;
case 'finish':
stats = uploader.getStats();
if (stats.successNum) {
alert('上传成功');
} else {
// 没有成功的图片,重设
state = 'done';
location.reload();
}
break;
}
updateStatus();
}
uploader.onUploadProgress = function(file, percentage) {
var $li = $('#' + file.id),
$percent = $li.find('.progress span');
$percent.css('width', percentage * 100 + '%');
percentages[file.id][1] = percentage;
updateTotalProgress();
};
uploader.onFileQueued = function(file) {
fileCount++;
fileSize += file.size;
if (fileCount === 1) {
$placeHolder.addClass('element-invisible');
$statusBar.show();
}
addFile(file);
setState('ready');
updateTotalProgress();
};
uploader.onFileDequeued = function(file) {
fileCount--;
fileSize -= file.size;
if (!fileCount) {
setState('pedding');
}
removeFile(file);
updateTotalProgress();
};
uploader.on('all', function(type) {
var stats;
switch (type) {
case 'uploadFinished':
setState('confirm');
break;
case 'startUpload':
setState('uploading');
break;
case 'stopUpload':
setState('paused');
break;
}
});
uploader.onError = function(code) {
alert('Eroor: ' + code);
};
$upload.on('click', function() {
if ($(this).hasClass('disabled')) {
return false;
}
if (state === 'ready') {
uploader.upload();
} else if (state === 'paused') {
uploader.upload();
} else if (state === 'uploading') {
uploader.stop();
}
});
$info.on('click', '.retry', function() {
uploader.retry();
});
$info.on('click', '.ignore', function() {
alert('todo');
});
$upload.addClass('state-' + state);
updateTotalProgress();
});
})(jQuery);
(function($) {
// 扩展md5逻辑
var Uploader = WebUploader.Uploader;
var fr;
function readContent(file, cb) {
var chunkSize = 2 * 1024 * 1024,
chunks = Math.ceil(file.size / chunkSize),
chunk = 0,
ret = '',
blobSlice = file.mozSlice || file.webkitSlice || file.slice,
loadNext;
fr = fr || new FileReader;
loadNext = function() {
var start, end;
start = chunk * chunkSize;
end = start + chunkSize >= file.size ? file.size : start + chunkSize;
fr.onload = function(e) {
ret += fr.result;
fr.result = null;
};
fr.onloadend = function() {
fr.onload = fr.onloadend = null;
if (++chunk < chunks) {
setTimeout(loadNext, 1);
} else {
fr.readAsBinaryString(new Blob(['a'], {
type: 'text/plain'
}));
cb(ret);
ret = loadNext = blobSlice = file = null;
}
};
fr.readAsBinaryString(blobSlice.call(file, start, end));
};
loadNext();
}
function Md5File(file, callback) {
console.time('get md5: ' + file.name);
readContent(file, function(ret) {
ret = md5(ret);
console.timeEnd('get md5: ' + file.name);
setTimeout(function() {
callback(ret);
}, 1);
});
}
Uploader.register({
'before-send-file': 'preupload'
}, {
preupload: function(file) {
var me = this,
owner = this.owner,
server = me.options.server,
deferred = WebUploader.Deferred(),
blob = file.source.getSource();
Md5File(blob, function(ret) {
$.ajax(server, {
dataType: 'json',
data: {
md5: ret
},
success: function( response ) {
if ( response.exist ) {
owner.skipFile( file );
var log = $('#'+file.id).find('p.imgWrap')
log.text('文件重复,已跳过');
}
deferred.resolve( true );
}
});
});
return deferred.promise();
}
});
})(jQuery);
================================================
FILE: _draft/music/webuploader.js
================================================
/* WebUploader 0.1.0 */
(function( window, undefined ) {
/**
* @fileOverview 让内部各个部件的代码可以用[amd](https://github.com/amdjs/amdjs-api/wiki/AMD)模块定义方式组织起来。
*
* AMD API 内部的简单不完全实现,请忽略。只有当WebUploader被合并成一个文件的时候才会引入。
*/
var internalAmd = (function( global, undefined ) {
var modules = {},
// 简单不完全实现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;
}
if ( typeof id !== 'string' || !factory ) {
throw new Error('Define Error');
}
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 ] || global[ id ];
if ( !module ) {
throw new Error( '`' + id + '` is undefined' );
}
return module;
};
return {
define: define,
require: require,
// 暴露所有的模块。
modules: modules
};
})( window ),
/* jshint unused: false */
require = internalAmd.require,
define = internalAmd.define;
/**
* @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', [
'jQuery'
], function( $ ) {
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.0',
/**
* @property {jQuery|Zepto} $ 引用依赖的jQuery或者Zepto对象。
*/
$: $,
/**
* 创建一个[Deferred](http://api.jquery.com/category/deferred-object/)对象。
* 详细的Deferred用法说明,请参照jQuery的API文档。
*
* Deferred对象在钩子回掉函数中经常要用到,用来处理需要等待的异步操作。
*
*
* @method Deferred
* @grammar Base.Deferred() => Deferred
* @example
* // 在文件开始发送前做些异步操作。
* // WebUploader会等待此异步操作完成后,开始发送文件。
* Uploader.register({
* 'before-send-file': 'doSomthingAsync'
* }, {
*
* doSomthingAsync: function() {
* var deferred = Base.Deferred();
*
* // 模拟一次异步操作。
* setTimeout(deferred.resolve, 2000);
*
* return deferred.promise();
* }
* });
*/
Deferred: $.Deferred,
/**
* 判断传入的参数是否为一个promise对象。
* @method isPromise
* @grammar Base.isPromise( anything ) => Boolean
* @param {*} anything 检测对象。
* @return {Boolean}
* @example
* console.log( Base.isPromise() ); // => false
* console.log( Base.isPromise({ key: '123' }) ); // => false
* console.log( Base.isPromise( Base.Deferred().promise() ) ); // => true
*
* // Deferred也是一个Promise
* console.log( Base.isPromise( Base.Deferred() ) ); // => true
*/
isPromise: function( anything ) {
return anything && typeof anything.then === 'function';
},
/**
* 返回一个promise,此promise在所有传入的promise都完成了后完成。
* 详细请查看[这里](http://api.jquery.com/jQuery.when/)。
*
* @method when
* @grammar Base.when( promise1[, promise2[, promise3...]] ) => Promise
*/
when: $.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.]+)/ ),
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 ),
/**
* 实现类与类之间的继承。
* @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如果存在的话,否则引用一个[空函数loop](#WebUploader:Base.log)。
* @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',
removeFile: 'remove-file',
skipFile: 'skip-file',
retry: 'retry',
isInProgress: 'is-in-progress',
makeThumb: 'make-thumb',
getDimension: 'get-dimension',
addButton: 'add-btn',
getRuntimeType: 'get-runtime-type',
refresh: 'refresh',
disable: 'disable',
enable: 'enable'
}, 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({
* resize: null;
* });
*
* // 修改后图片上传前,尝试将图片压缩到1600 * 1600
* uploader.options( 'resize', {
* 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` 上传成功的文件数
* * `uploadFailNum` 上传失败的文件数
* * `cancelNum` 被删除的文件数
* * `invalidNum` 无效的文件数
* * `queueNum` 还在队列中的文件数
* @method getStats
* @grammar getStats() => Object
*/
getStats: function() {
// return this._mgr.getStats.apply( this._mgr, arguments );
var stats = this.request('get-stats');
return {
successNum: stats.numOfSuccess,
// who care?
// queueFailNum: 0,
cancelNum: stats.numOfCancel,
invalidNum: stats.numOfInvalid,
uploadFailNum: stats.numOfUploadFailed,
queueNum: stats.numOfQueue
};
},
// 需要重写此方法来来支持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 ( Mediator.trigger.apply( this, arguments ) === false ) {
return false;
}
if ( $.isFunction( opts[ name ] ) &&
opts[ name ].apply( this, args ) === false ) {
return false;
}
if ( $.isFunction( this[ name ] ) &&
this[ name ].apply( this, args ) === false ) {
return false;
}
return true;
},
// widgets/widget.js将补充此方法的详细文档。
request: Base.noop,
reset: function() {
// @todo
}
});
/**
* 创建Uploader实例,等同于new Uploader( opts );
* @method create
* @class Base
* @static
* @grammar Base.create( opts ) => Uploader
*/
Base.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;
return container;
},
init: Base.noop,
exec: Base.noop,
destroy: function() {
if ( this._container ) {
this._container.parentNode.removeChild( this.__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 = (function() {
var obj = {};
return {
add: function( runtime ) {
obj[ runtime.uid ] = runtime;
},
get: function( ruid ) {
var i;
if ( ruid ) {
return obj[ ruid ];
}
for ( i in obj ) {
return obj[ i ];
}
return null;
},
remove: function( runtime ) {
delete obj[ runtime.uid ];
},
has: function() {
return !!this.get.apply( this, arguments );
}
};
})();
function RuntimeClient( component, standalone ) {
var deferred = Base.Deferred(),
runtime;
this.uid = Base.guid('client_');
this.runtimeReady = function( cb ) {
return deferred.done( cb );
};
this.connectRuntime = function( opts, cb ) {
if ( runtime ) {
return;
}
deferred.done( cb );
if ( typeof opts === 'string' && cache.get( opts ) ) {
runtime = cache.get( opts );
// 像filePicker只能独立存在,不能公用。
} else if ( !standalone && cache.has() ) {
runtime = cache.get();
}
if ( !runtime ) {
runtime = Runtime.create( opts, opts.runtimeOrder );
cache.add( runtime );
runtime.promise = deferred.promise();
runtime.once( 'ready', deferred.resolve );
runtime.init();
runtime.client = 1;
return runtime;
}
runtime.promise.then( deferred.resolve );
runtime.client++;
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;
RuntimeClient.call( me, 'Blob' );
this.uid = source.uid || this.uid;
this.type = source.type || '';
this.size = source.size || 0;
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;
});
/**
* @fileOverview File
*/
define( 'lib/file', [
'base',
'lib/blob'
], function( Base, Blob ) {
var uid = 0,
rExt = /\.([^.]+)$/;
function File( ruid, file ) {
var ext;
Blob.apply( this, arguments );
this.name = file.name || ('untitled' + uid++);
ext = rExt.exec( file.name ) ? RegExp.$1.toLowerCase() : '';
if ( !this.type && ~'jpg,jpeg,png,gif,bmp'.indexOf( ext ) ) {
this.type = 'image/' + ext;
}
this.ext = ext;
this.lastModifiedDate = file.lastModifiedDate ||
(new Date()).toLocaleString();
}
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.label = opts.label || opts.container.text() || '选择文件';
opts.button = $( opts.button || document.createElement('div') );
opts.button.text( opts.label );
opts.container.html( opts.button );
RuntimeClent.call( this, 'FilePicker', true );
}
FilePicker.options = {
button: null,
container: null,
label: null,
multiple: true,
accept: null
};
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 ) {
return new File( me.getRuid(), file );
}) );
break;
}
});
me.connectRuntime( opts, function() {
me.refresh();
me.exec( 'init', opts );
});
$( window ).on( 'resize', function() {
me.refresh();
});
},
refresh: function() {
var shimContainer = this.getRuntime().getContainer(),
button = this.options.button,
width = button.outerWidth(),
height = button.outerHeight(),
pos = button.offset();
width && shimContainer.css({
width: width + 'px',
height: height + 'px'
}).offset( pos );
},
destroy: function() {
if ( this.runtime ) {
this.exec('destroy');
this.disconnectRuntime();
}
}
});
return FilePicker;
});
/**
* @fileOverview 组件基类。
*/
define( 'widgets/widget', [
'base',
'uploader'
], function( Base, Uploader ) {
var $ = Base.$,
_init = Uploader.prototype._init,
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, {
// 覆写_init用来初始化widgets
_init: function() {
var me = this,
widgets = me._widgets = [];
$.each( widgetClass, function( _, klass ) {
widgets.push( new klass( me ) );
});
return _init.apply( me, arguments );
},
request: function( apiName, args, callback ) {
var i = 0,
widgets = this._widgets,
len = widgets.length,
rlts = [],
dfds = [],
widget, rlt;
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 ) {
return Base.when.apply( Base, dfds )
// 很重要不能删除。删除了会死循环。
// 保证执行顺序。让callback总是在下一个tick中执行。
.then(function() {
var deferred = Base.Deferred(),
args = arguments;
setTimeout(function() {
deferred.resolve.apply( deferred, args );
}, 1 );
return deferred.promise();
})
.then( callback || Base.noop );
} else {
return rlts[ 0 ];
}
}
});
/**
* 添加组件
* @param {object} widgetProto 组件原型,构造函数通过constructor属性定义
* @param {object} responseMap API名称与函数实现的映射
* @example
* Uploader.register( {
* init: function( options ) {},
* makeThumb: function() {}
* }, {
* 'make-thumb': 'makeThumb'
* } );
*/
Uploader.register = Widget.register = function( responseMap, widgetProto ) {
var map = { init: 'init' },
klass;
if ( arguments.length === 1 ) {
widgetProto = responseMap;
widgetProto.responseMap = map;
} else {
widgetProto.responseMap = $.extend( map, responseMap );
}
klass = Base.inherits( Widget, widgetProto );
widgetClass.push( klass );
return klass;
};
return Widget;
});
/**
* @fileOverview 文件选择相关
*/
define( 'widgets/filepicker', [
'base',
'uploader',
'lib/filepicker',
'widgets/widget'
], function( Base, Uploader, FilePicker ) {
Base.$.extend( Uploader.options, {
/**
* @property {Selector | Object} [pick=undefined]
* @namespace options
* @for Uploader
* @description 指定选择文件的按钮容器,不指定则不创建按钮。
*
* * `id` {Seletor} 指定选择文件的按钮容器,不指定则不创建按钮。
* * `label` {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({
'add-btn': 'addButton',
'refresh': 'refresh'
}, {
init: function( opts ) {
this.pickers = [];
return opts.pick && this.addButton( 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',
* label: '选择文件'
* });
*/
addButton: function( pick ) {
var me = this,
opts = me.options,
accept = opts.accept,
options, picker, deferred;
if ( !pick ) {
return;
}
deferred = Base.Deferred();
if ( typeof pick === 'string' ) {
pick = {
id: pick
};
}
options = $.extend({}, pick, {
accept: $.isPlainObject( accept ) ? [ accept ] : accept,
swf: opts.swf,
runtimeOrder: opts.runtimeOrder
});
picker = new FilePicker( options );
picker.once( 'ready', deferred.resolve );
picker.on( 'select', function( files ) {
me.owner.request( 'add-file', [ files ]);
});
picker.init();
this.pickers.push( picker );
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 'image/png'
*/
this.type = source.type || 'image/png';
/**
* 文件最后修改日期
* @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;
},
destory: function() {
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( 'lib/dnd', [
'base',
'mediator',
'runtime/client'
], function( Base, Mediator, RuntimeClent ) {
var $ = Base.$;
function DragAndDrop( opts ) {
opts = this.options = $.extend({}, DragAndDrop.options, opts );
opts.container = $( opts.container );
if ( !opts.container.length ) {
return;
}
RuntimeClent.call( this, 'DragAndDrop' );
}
DragAndDrop.options = {
accept: null,
disableGlobalDnd: true
};
Base.inherits( RuntimeClent, {
constructor: DragAndDrop,
init: function() {
var me = this;
me.connectRuntime( me.options, function() {
me.exec('init');
});
},
destroy: function() {
this.disconnectRuntime();
}
});
Mediator.installTo( DragAndDrop.prototype );
return DragAndDrop;
});
/**
* @fileOverview 错误信息
*/
define( 'lib/filepaste', [
'base',
'mediator',
'runtime/client'
], function( Base, Mediator, RuntimeClent ) {
var $ = Base.$;
function FilePaste( opts ) {
opts = this.options = $.extend({}, opts );
opts.container = $( opts.container || document.body );
RuntimeClent.call( this, 'FilePaste' );
}
Base.inherits( RuntimeClent, {
constructor: FilePaste,
init: function() {
var me = this;
me.connectRuntime( me.options, function() {
me.exec('init');
});
},
destroy: function() {
this.exec('destroy');
this.disconnectRuntime();
this.off();
}
});
Mediator.installTo( FilePaste.prototype );
return FilePaste;
});
/**
* @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: true,
// 是否允许放大。
allowMagnify: true
};
// 继承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 ) );
},
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 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,
fileVar: '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.fileVar = key || opts.fileVar;
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( '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` 无效的文件数。
* @property {Object} stats
*/
this.stats = {
numOfQueue: 0,
numOfSuccess: 0,
numOfCancel: 0,
numOfProgress: 0,
numOfUploadFailed: 0,
numOfInvalid: 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;
},
/**
* 获取指定类型的文件列表, 列表中每一个成员为[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;
},
_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 );
});
}
file.setStatus( STATUS.QUEUED );
},
_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;
}
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;
}
}
});
Mediator.installTo( Queue.prototype );
return Queue;
});
/**
* @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 = {},
destory = this.destory,
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 hander( 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() {
hander.apply( null, args );
}, 1 );
};
this.jsreciver = jsreciver;
this.destory = function() {
// @todo 删除池子中的所有实例
return destory && destory.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.3 ) {
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 );
delete copy.button;
delete copy.container;
this.flashExec( 'FilePicker', 'init', copy );
},
destroy: function() {
// todo
}
});
});
/**
* @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 Transport flash实现
*/
define( 'runtime/flash/transport', [
'base',
'runtime/flash/runtime',
'runtime/client'
], function( Base, FlashRuntime, RuntimeClient ) {
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.fileVar, blob.uid,
opts.filename || owner._formData.name || '' );
}
this._setRequestHeader( xhr, opts.headers );
xhr.exec( 'send', {
method: opts.method,
url: server
}, 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 ) {
return me.trigger( 'progress', e.loaded / e.total );
});
xhr.on( 'load', function() {
var status = xhr.exec('getStatus');
xhr.off();
me._xhr = null;
if ( status === 200 ) {
me._response = xhr.exec('getResponse');
me._responseJson = xhr.exec('getResponseAsJson');
return me.trigger('load');
}
me._status = status;
xhr.destroy();
xhr = null;
return me.trigger( 'error', 'http' );
});
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 Html5Runtime
*/
define( 'runtime/html5/runtime', [
'base',
'runtime/runtime',
'runtime/compbase'
], function( Base, Runtime, CompBase ) {
var type = 'html5',
components = {};
function Html5Runtime() {
var pool = {},
me = this,
destory = this.destory;
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;
if ( components[ comp ] ) {
instance = pool[ uid ] = pool[ uid ] ||
new components[ comp ]( client, me );
if ( instance[ fn ] ) {
return instance[ fn ].apply( instance, args );
}
}
};
me.destory = function() {
// @todo 删除池子中的所有实例
return destory && destory.apply( this, arguments );
};
}
Base.inherits( Runtime, {
constructor: Html5Runtime,
// 不需要连接其他程序,直接执行callback
init: function() {
var me = this;
setTimeout(function() {
me.trigger('ready');
}, 1 );
}
});
Html5Runtime.register = function( name, component ) {
var klass = components[ name ] = Base.inherits( CompBase, component );
return klass;
};
// 注册html5运行时。
if ( window.Blob && window.FileReader && window.DataView ) {
Runtime.addRuntime( type, Html5Runtime );
}
return Html5Runtime;
});
/**
* @fileOverview Blob Html实现
*/
define( 'runtime/html5/blob', [
'runtime/html5/runtime',
'lib/blob'
], function( Html5Runtime, Blob ) {
return Html5Runtime.register( 'Blob', {
slice: function( start, end ) {
var blob = this.owner.source,
slice = blob.slice || blob.webkitSlice || blob.mozSlice;
blob = slice.call( blob, start, end );
return new Blob( this.getRuid(), blob );
}
});
});
/**
* @fileOverview FilePaste
*/
define( 'runtime/html5/dnd', [
'base',
'runtime/html5/runtime',
'lib/file'
], function( Base, Html5Runtime, File ) {
var $ = Base.$;
return Html5Runtime.register( 'DragAndDrop', {
init: function() {
var elem = this.elem = this.options.container;
this.dragEnterHandler = Base.bindFn( this._dragEnterHandler, this );
this.dragOverHandler = Base.bindFn( this._dragOverHandler, this );
this.dragLeaveHandler = Base.bindFn( this._dragLeaveHandler, this );
this.dropHandler = Base.bindFn( this._dropHandler, this );
elem.on( 'dragenter', this.dragEnterHandler );
elem.on( 'dragover', this.dragOverHandler );
elem.on( 'dragleave', this.dragLeaveHandler );
elem.on( 'drop', this.dropHandler );
if ( this.options.disableGlobalDnd ) {
$( document ).on( 'dragover', this.dragOverHandler );
$( document ).on( 'drop', this.dropHandler );
}
},
_dragEnterHandler: function( e ) {
this.elem.addClass('webuploader-dnd-over');
e = e.originalEvent || e;
e.dataTransfer.dropEffect = 'copy';
return false;
},
_dragOverHandler: function( e ) {
// 只处理框内的。
if ( !$.contains( this.elem.parent().get( 0 ), e.target ) ) {
return false;
}
this._dragEnterHandler.call( this, e );
return false;
},
_dragLeaveHandler: function() {
this.elem.removeClass('webuploader-dnd-over');
return false;
},
_dropHandler: function( e ) {
var results = [],
promises = [],
me = this,
ruid = me.getRuid(),
items, files, dataTransfer, file, i, len, canAccessFolder;
// 只处理框内的。
if ( !$.contains( me.elem.parent().get( 0 ), e.target ) ) {
return false;
}
e = e.originalEvent || e;
dataTransfer = e.dataTransfer;
items = dataTransfer.items;
files = dataTransfer.files;
canAccessFolder = !!(items && items[ 0 ].webkitGetAsEntry);
for ( i = 0, len = files.length; i < len; i++ ) {
file = files[ i ];
if ( file.type ) {
results.push( file );
} else if ( !file.type && canAccessFolder ) {
promises.push( this._traverseDirectoryTree(
items[ i ].webkitGetAsEntry(), results ) );
}
}
Base.when.apply( Base, promises ).done(function() {
me.trigger( 'drop', $.map( results, function( file ) {
return new File( ruid, file );
}) );
});
this.elem.removeClass('webuploader-dnd-over');
return false;
},
_traverseDirectoryTree: function( entry, results ) {
var deferred = Base.Deferred(),
me = this;
if ( entry.isFile ) {
entry.file(function( file ) {
file.type && results.push( file );
deferred.resolve( true );
});
} else if ( entry.isDirectory ) {
entry.createReader().readEntries(function( entries ) {
var len = entries.length,
promises = [],
arr = [], // 为了保证顺序。
i;
for ( i = 0; i < len; i++ ) {
promises.push( me._traverseDirectoryTree(
entries[ i ], arr ) );
}
Base.when.apply( Base, promises ).then(function() {
results.push.apply( results, arr );
deferred.resolve( true );
}, deferred.reject );
});
}
return deferred.promise();
},
destroy: function() {
var elem = this.elem;
elem.off( 'dragenter', this.dragEnterHandler );
elem.off( 'dragover', this.dragEnterHandler );
elem.off( 'dragleave', this.dragLeaveHandler );
elem.off( 'drop', this.dropHandler );
if ( this.options.disableGlobalDnd ) {
$( document ).off( 'dragover', this.dragOverHandler );
$( document ).off( 'drop', this.dropHandler );
}
}
});
});
/**
* @fileOverview FilePaste
*/
define( 'runtime/html5/filepaste', [
'base',
'runtime/html5/runtime',
'lib/file'
], function( Base, Html5Runtime, File ) {
return Html5Runtime.register( 'FilePaste', {
init: function() {
var opts = this.options,
elem = this.elem = opts.container,
accept = '.*',
arr, i, len, item;
// accetp的mimeTypes中生成匹配正则。
if ( opts.accept ) {
arr = [];
for ( i = 0, len = opts.accept.length; i < len; i++ ) {
item = opts.accept[ i ].mimeTypes;
item && arr.push( item );
}
if ( arr.length ) {
accept = arr.join(',');
accept = accept.replace( /,/g, '|' ).replace( /\*/g, '.*' );
}
}
this.accept = accept = new RegExp( accept, 'i' );
this.hander = Base.bindFn( this._pasteHander, this );
elem.on( 'paste', this.hander );
},
_pasteHander: function( e ) {
var allowed = [],
ruid = this.getRuid(),
files, file, blob, i, len;
e = e.originalEvent || e;
e.preventDefault();
e.stopPropagation();
files = e.clipboardData.items;
for ( i = 0, len = files.length; i < len; i++ ) {
file = files[ i ];
if ( !file.type || !(blob = file.getAsFile()) ||
blob.size < 6 ) {
continue;
}
allowed.push( new File( ruid, blob ) );
}
allowed.length && this.trigger( 'paste', allowed );
},
destroy: function() {
this.elem.off( 'paste', this.hander );
}
});
});
/**
* @fileOverview FilePicker
*/
define( 'runtime/html5/filepicker', [
'base',
'runtime/html5/runtime'
], function( Base, Html5Runtime ) {
var $ = Base.$;
return Html5Runtime.register( 'FilePicker', {
init: function() {
var container = this.getRuntime().getContainer(),
me = this,
owner = me.owner,
opts = me.options,
lable = $( document.createElement('label') ),
input = $( document.createElement('input') ),
arr, i, len, mouseHandler;
input.attr( 'type', 'file' );
input.css({
position: 'absolute',
clip: 'rect(1px,1px,1px,1px)'
});
lable.on( 'click', function() {
input.trigger('click');
});
lable.css({
opacity: 0,
width: '100%',
height: '100%',
display: 'block',
cursor: 'pointer',
background: '#ffffff'
});
if ( opts.multiple ) {
input.attr( 'multiple', 'multiple' );
}
// @todo Firefox不支持单独指定后缀
if ( opts.accept && opts.accept.length > 0 ) {
arr = [];
for ( i = 0, len = opts.accept.length; i < len; i++ ) {
arr.push( opts.accept[ i ].mimeTypes );
}
input.attr( 'accept', arr.join(',') );
}
container.append( input );
container.append( lable );
mouseHandler = function( e ) {
owner.trigger( e.type );
};
input.on( 'change', function( e ) {
var fn = arguments.callee,
clone;
me.files = e.target.files;
// reset input
clone = this.cloneNode( true );
this.parentNode.replaceChild( clone, this );
input.off();
input = $( clone ).on( 'change', fn )
.on( 'mouseenter mouseleave', mouseHandler );
owner.trigger('change');
});
lable.on( 'mouseenter mouseleave', mouseHandler );
},
getFiles: function() {
return this.files;
},
destroy: function() {
// todo
}
});
});
/**
* Terms:
*
* Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
* @fileOverview Image控件
*/
define( 'runtime/html5/util', function() {
var urlAPI = window.createObjectURL && window ||
window.URL && URL.revokeObjectURL && URL ||
window.webkitURL;
return {
createObjectURL: urlAPI && urlAPI.createObjectURL,
revokeObjectURL: urlAPI && urlAPI.revokeObjectURL,
dataURL2Blob: function( dataURI ) {
var byteStr, intArray, ab, i, mimetype, parts;
parts = dataURI.split(',');
if ( ~parts[ 0 ].indexOf('base64') ) {
byteStr = atob( parts[ 1 ] );
} else {
byteStr = decodeURIComponent( parts[ 1 ] );
}
ab = new ArrayBuffer( byteStr.length );
intArray = new Uint8Array( ab );
for ( i = 0; i < byteStr.length; i++ ) {
intArray[ i ] = byteStr.charCodeAt( i );
}
mimetype = parts[ 0 ].split(':')[ 1 ].split(';')[ 0 ];
return new Blob([ ab ], {
type: mimetype
});
},
dataURL2ArrayBuffer: function( dataURI ) {
var byteStr, intArray, i, parts;
parts = dataURI.split(',');
if ( ~parts[ 0 ].indexOf('base64') ) {
byteStr = atob( parts[ 1 ] );
} else {
byteStr = decodeURIComponent( parts[ 1 ] );
}
intArray = new Uint8Array( byteStr.length );
for ( i = 0; i < byteStr.length; i++ ) {
intArray[ i ] = byteStr.charCodeAt( i );
}
return intArray.buffer;
},
arrayBufferToBlob: function( buffer, type ) {
return new Blob([ buffer ], type ? { type: type } : {} );
}
};
});
/**
* Terms:
*
* Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
* @fileOverview Image控件
*/
define( 'runtime/html5/imagemeta', function() {
var api;
api = {
parsers: {
0xffe1: []
},
maxMetaDataSize: 262144,
parse: function( blob, cb ) {
var me = this,
fr = new FileReader();
fr.onload = function() {
cb( false, me._parse( this.result ) );
fr = fr.onload = fr.onerror = null;
};
fr.onerror = function( e ) {
cb( e.message );
fr = fr.onload = fr.onerror = null;
};
blob = blob.slice( 0, me.maxMetaDataSize );
fr.readAsArrayBuffer( blob.getSource() );
},
_parse: function( buffer, noParse ) {
if ( buffer.byteLength < 6 ) {
return;
}
var dataview = new DataView( buffer ),
offset = 2,
maxOffset = dataview.byteLength - 4,
headLength = offset,
ret = {},
markerBytes, markerLength, parsers, i;
if ( dataview.getUint16( 0 ) === 0xffd8 ) {
while ( offset < maxOffset ) {
markerBytes = dataview.getUint16( offset );
if ( markerBytes >= 0xffe0 && markerBytes <= 0xffef ||
markerBytes === 0xfffe ) {
markerLength = dataview.getUint16( offset + 2 ) + 2;
if ( offset + markerLength > dataview.byteLength ) {
break;
}
parsers = api.parsers[ markerBytes ];
if ( !noParse && parsers ) {
for ( i = 0; i < parsers.length; i += 1 ) {
parsers[ i ].call( api, dataview, offset,
markerLength, ret );
}
}
offset += markerLength;
headLength = offset;
} else {
break;
}
}
if ( headLength > 6 ) {
if ( buffer.slice ) {
ret.imageHead = buffer.slice( 2, headLength );
} else {
// Workaround for IE10, which does not yet
// support ArrayBuffer.slice:
ret.imageHead = new Uint8Array( buffer )
.subarray( 2, headLength );
}
}
}
return ret;
},
updateImageHead: function( buffer, head ) {
var data = this._parse( buffer, true ),
buf1, buf2, bodyoffset;
bodyoffset = 2;
if ( data.imageHead ) {
bodyoffset = 2 + data.imageHead.byteLength;
}
if ( buffer.slice ) {
buf2 = buffer.slice( bodyoffset );
} else {
buf2 = new Uint8Array( buffer ).subarray( bodyoffset );
}
buf1 = new Uint8Array( head.byteLength + 2 + buf2.byteLength );
buf1[ 0 ] = 0xFF;
buf1[ 1 ] = 0xD8;
buf1.set( new Uint8Array( head ), 2 );
buf1.set( new Uint8Array( buf2 ), head.byteLength + 2 );
return buf1.buffer;
}
};
return api;
});
/**
* @fileOverview Image
*/
define( 'runtime/html5/image', [
'runtime/html5/runtime',
'runtime/html5/util',
'runtime/html5/imagemeta'
], function( Html5Runtime, Util, ImageMeta ) {
var BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D';
return Html5Runtime.register( 'Image', {
// flag: 标记是否被修改过。
modified: false,
init: function() {
var me = this,
img = new Image();
img.onload = function() {
me._info = {
type: me.type,
width: this.width,
height: this.height
};
// 读取meta信息。
if ( !me._metas && ~'image/jpegimage/jpg'.indexOf( me.type ) ) {
ImageMeta.parse( me._blob, function( error, ret ) {
me._metas = ret;
me.owner.trigger('load');
});
} else {
me.owner.trigger('load');
}
};
img.onerror = function() {
me.owner.trigger('error');
};
me._img = img;
},
loadFromBlob: function( blob ) {
var me = this,
img = me._img;
me._blob = blob;
me.type = blob.type;
img.src = Util.createObjectURL( blob.getSource() );
me.owner.once( 'load', function() {
Util.revokeObjectURL( img.src );
});
},
resize: function( width, height ) {
var canvas = this._canvas ||
(this._canvas = document.createElement('canvas'));
this._resize( this._img, canvas, width, height );
this._blob = null; // 没用了,可以删掉了。
this.modified = true;
this.owner.trigger('complete');
},
getAsBlob: function( type ) {
var blob = this._blob,
opts = this.options,
canvas;
type = type || this.type;
// blob需要重新生成。
if ( this.modified || this.type !== type ) {
canvas = this._canvas;
if ( type === 'image/jpeg' ) {
blob = canvas.toDataURL( 'image/jpeg', opts.quality / 100 );
if ( opts.preserveHeaders && this._metas &&
this._metas.imageHead ) {
blob = Util.dataURL2ArrayBuffer( blob );
blob = ImageMeta.updateImageHead( blob,
this._metas.imageHead );
blob = Util.arrayBufferToBlob( blob, type );
return blob;
}
} else {
blob = canvas.toDataURL( type );
}
blob = Util.dataURL2Blob( blob );
}
return blob;
},
getAsDataUrl: function( type ) {
var opts = this.options;
type = type || this.type;
if ( type === 'image/jpeg' ) {
return this._canvas.toDataURL( type, opts.quality / 100 );
} else {
return this._canvas.toDataURL( type );
}
},
getOrientation: function() {
return this._metas && this._metas.exif &&
this._metas.exif.get('Orientation') || 1;
},
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;
},
destroy: function() {
var canvas = this._canvas;
this._img.onload = null;
if ( canvas ) {
canvas.getContext('2d')
.clearRect( 0, 0, canvas.width, canvas.height );
canvas.width = canvas.height = 0;
this._canvas = null;
}
// 释放内存。非常重要,否则释放不了image的内存。
this._img.src = BLANK;
this._img = this._blob = null;
},
_resize: function( img, cvs, width, height ) {
var opts = this.options,
naturalWidth = img.width,
naturalHeight = img.height,
orientation = this.getOrientation(),
scale, w, h, x, y;
// values that require 90 degree rotation
if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) {
// 交换width, height的值。
width ^= height;
height ^= width;
width ^= height;
}
scale = Math[ opts.crop ? 'max' : 'min' ]( width / naturalWidth,
height / naturalHeight );
// 不允许放大。
opts.allowMagnify || (scale = Math.min( 1, scale ));
w = naturalWidth * scale;
h = naturalHeight * scale;
if ( opts.crop ) {
cvs.width = width;
cvs.height = height;
} else {
cvs.width = w;
cvs.height = h;
}
x = (cvs.width - w) / 2;
y = (cvs.height - h) / 2;
opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation );
this._renderImageToCanvas( cvs, img, x, y, w, h );
},
_rotate2Orientaion: function( canvas, orientation ) {
var width = canvas.width,
height = canvas.height,
ctx = canvas.getContext('2d');
switch ( orientation ) {
case 5:
case 6:
case 7:
case 8:
canvas.width = height;
canvas.height = width;
break;
}
switch ( orientation ) {
case 2: // horizontal flip
ctx.translate( width, 0 );
ctx.scale( -1, 1 );
break;
case 3: // 180 rotate left
ctx.translate( width, height );
ctx.rotate( Math.PI );
break;
case 4: // vertical flip
ctx.translate( 0, height );
ctx.scale( 1, -1 );
break;
case 5: // vertical flip + 90 rotate right
ctx.rotate( 0.5 * Math.PI );
ctx.scale( 1, -1 );
break;
case 6: // 90 rotate right
ctx.rotate( 0.5 * Math.PI );
ctx.translate( 0, -height );
break;
case 7: // horizontal flip + 90 rotate right
ctx.rotate( 0.5 * Math.PI );
ctx.translate( width, -height );
ctx.scale( -1, 1 );
break;
case 8: // 90 rotate left
ctx.rotate( -0.5 * Math.PI );
ctx.translate( -width, 0 );
break;
}
},
_renderImageToCanvas: function( canvas, img, x, y, w, h ) {
canvas.getContext('2d').drawImage( img, x, y, w, h );
}
/*_renderImageToCanvas: (function() {
var subsampled, vertSquashRatio;
// Detect subsampling in loaded image.
// In iOS, larger images than 2M pixels may be subsampled in rendering.
function detectSubsampling(img) {
var iw = img.naturalWidth,
ih = img.naturalHeight;
if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image
var canvas = document.createElement('canvas');
canvas.width = canvas.height = 1;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, -iw + 1, 0);
// subsampled image becomes half smaller in rendering size.
// check alpha channel value to confirm image is covering edge pixel or not.
// if alpha value is 0 image is not covering, hence subsampled.
return ctx.getImageData(0, 0, 1, 1).data[3] === 0;
} else {
return false;
}
}
// Detecting vertical squash in loaded image.
// Fixes a bug which squash image vertically while drawing into canvas for some images.
function detectVerticalSquash(img, iw, ih) {
var canvas = document.createElement('canvas');
canvas.width = 1;
canvas.height = ih;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
var data = ctx.getImageData(0, 0, 1, ih).data;
// search image edge pixel position in case it is squashed vertically.
var sy = 0;
var ey = ih;
var py = ih;
while (py > sy) {
var alpha = data[(py - 1) * 4 + 3];
if (alpha === 0) {
ey = py;
} else {
sy = py;
}
py = (ey + sy) >> 1;
}
var ratio = (py / ih);
return (ratio === 0) ? 1 : ratio;
}
return function( canvas, img, x, y, w, h ) {
var iw = img.naturalWidth, ih = img.naturalHeight;
var width = w, height = h;
var ctx = canvas.getContext('2d');
ctx.save();
subsampled = typeof subsampled === 'undefined' ? detectSubsampling( img ) : subsampled;
if ( subsampled ) {
iw /= 2;
ih /= 2;
}
var d = 1024; // size of tiling canvas
var tmpCanvas = document.createElement('canvas');
tmpCanvas.width = tmpCanvas.height = d;
var tmpCtx = tmpCanvas.getContext('2d');
vertSquashRatio = vertSquashRatio || detectVerticalSquash(img, iw, ih);
console.log( vertSquashRatio );
var dw = Math.ceil(d * width / iw);
var dh = Math.ceil(d * height / ih / vertSquashRatio);
var sy = 0;
var dy = 0;
while (sy < ih) {
var sx = 0;
var dx = 0;
while (sx < iw) {
tmpCtx.clearRect(0, 0, d, d);
tmpCtx.drawImage(img, x - sx, y - sy );
ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh);
sx += d;
dx += dw;
}
sy += d;
dy += dh;
}
ctx.restore();
tmpCanvas = tmpCtx = null;
};
})()*/
});
});
/**
* 代码来自于:https://github.com/blueimp/JavaScript-Load-Image
* 暂时项目中只用了orientation.
*
* 去除了 Exif Sub IFD Pointer, GPS Info IFD Pointer, Exif Thumbnail.
* @fileOverview EXIF解析
*/
// Sample
// ====================================
// Make : Apple
// Model : iPhone 4S
// Orientation : 1
// XResolution : 72 [72/1]
// YResolution : 72 [72/1]
// ResolutionUnit : 2
// Software : QuickTime 7.7.1
// DateTime : 2013:09:01 22:53:55
// ExifIFDPointer : 190
// ExposureTime : 0.058823529411764705 [1/17]
// FNumber : 2.4 [12/5]
// ExposureProgram : Normal program
// ISOSpeedRatings : 800
// ExifVersion : 0220
// DateTimeOriginal : 2013:09:01 22:52:51
// DateTimeDigitized : 2013:09:01 22:52:51
// ComponentsConfiguration : YCbCr
// ShutterSpeedValue : 4.058893515764426
// ApertureValue : 2.5260688216892597 [4845/1918]
// BrightnessValue : -0.3126686601998395
// MeteringMode : Pattern
// Flash : Flash did not fire, compulsory flash mode
// FocalLength : 4.28 [107/25]
// SubjectArea : [4 values]
// FlashpixVersion : 0100
// ColorSpace : 1
// PixelXDimension : 2448
// PixelYDimension : 3264
// SensingMethod : One-chip color area sensor
// ExposureMode : 0
// WhiteBalance : Auto white balance
// FocalLengthIn35mmFilm : 35
// SceneCaptureType : Standard
define( 'runtime/html5/imagemeta/exif', [
'base',
'runtime/html5/imagemeta'
], function( Base, ImageMeta ) {
var EXIF = {};
EXIF.ExifMap = function() {
return this;
};
EXIF.ExifMap.prototype.map = {
'Orientation': 0x0112
};
EXIF.ExifMap.prototype.get = function( id ) {
return this[ id ] || this[ this.map[ id ] ];
};
EXIF.exifTagTypes = {
// byte, 8-bit unsigned int:
1: {
getValue: function( dataView, dataOffset ) {
return dataView.getUint8( dataOffset );
},
size: 1
},
// ascii, 8-bit byte:
2: {
getValue: function( dataView, dataOffset ) {
return String.fromCharCode( dataView.getUint8( dataOffset ) );
},
size: 1,
ascii: true
},
// short, 16 bit int:
3: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getUint16( dataOffset, littleEndian );
},
size: 2
},
// long, 32 bit int:
4: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getUint32( dataOffset, littleEndian );
},
size: 4
},
// rational = two long values,
// first is numerator, second is denominator:
5: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getUint32( dataOffset, littleEndian ) /
dataView.getUint32( dataOffset + 4, littleEndian );
},
size: 8
},
// slong, 32 bit signed int:
9: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getInt32( dataOffset, littleEndian );
},
size: 4
},
// srational, two slongs, first is numerator, second is denominator:
10: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getInt32( dataOffset, littleEndian ) /
dataView.getInt32( dataOffset + 4, littleEndian );
},
size: 8
}
};
// undefined, 8-bit byte, value depending on field:
EXIF.exifTagTypes[ 7 ] = EXIF.exifTagTypes[ 1 ];
EXIF.getExifValue = function( dataView, tiffOffset, offset, type, length,
littleEndian ) {
var tagType = EXIF.exifTagTypes[ type ],
tagSize, dataOffset, values, i, str, c;
if ( !tagType ) {
Base.log('Invalid Exif data: Invalid tag type.');
return;
}
tagSize = tagType.size * length;
// Determine if the value is contained in the dataOffset bytes,
// or if the value at the dataOffset is a pointer to the actual data:
dataOffset = tagSize > 4 ? tiffOffset + dataView.getUint32( offset + 8,
littleEndian ) : (offset + 8);
if ( dataOffset + tagSize > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid data offset.');
return;
}
if ( length === 1 ) {
return tagType.getValue( dataView, dataOffset, littleEndian );
}
values = [];
for ( i = 0; i < length; i += 1 ) {
values[ i ] = tagType.getValue( dataView,
dataOffset + i * tagType.size, littleEndian );
}
if ( tagType.ascii ) {
str = '';
// Concatenate the chars:
for ( i = 0; i < values.length; i += 1 ) {
c = values[ i ];
// Ignore the terminating NULL byte(s):
if ( c === '\u0000' ) {
break;
}
str += c;
}
return str;
}
return values;
};
EXIF.parseExifTag = function( dataView, tiffOffset, offset, littleEndian,
data ) {
var tag = dataView.getUint16( offset, littleEndian );
data.exif[ tag ] = EXIF.getExifValue( dataView, tiffOffset, offset,
dataView.getUint16( offset + 2, littleEndian ), // tag type
dataView.getUint32( offset + 4, littleEndian ), // tag length
littleEndian );
};
EXIF.parseExifTags = function( dataView, tiffOffset, dirOffset,
littleEndian, data ) {
var tagsNumber, dirEndOffset, i;
if ( dirOffset + 6 > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid directory offset.');
return;
}
tagsNumber = dataView.getUint16( dirOffset, littleEndian );
dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
if ( dirEndOffset + 4 > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid directory size.');
return;
}
for ( i = 0; i < tagsNumber; i += 1 ) {
this.parseExifTag( dataView, tiffOffset,
dirOffset + 2 + 12 * i, // tag offset
littleEndian, data );
}
// Return the offset to the next directory:
return dataView.getUint32( dirEndOffset, littleEndian );
};
// EXIF.getExifThumbnail = function(dataView, offset, length) {
// var hexData,
// i,
// b;
// if (!length || offset + length > dataView.byteLength) {
// Base.log('Invalid Exif data: Invalid thumbnail data.');
// return;
// }
// hexData = [];
// for (i = 0; i < length; i += 1) {
// b = dataView.getUint8(offset + i);
// hexData.push((b < 16 ? '0' : '') + b.toString(16));
// }
// return 'data:image/jpeg,%' + hexData.join('%');
// };
EXIF.parseExifData = function( dataView, offset, length, data ) {
var tiffOffset = offset + 10,
littleEndian, dirOffset;
// Check for the ASCII code for "Exif" (0x45786966):
if ( dataView.getUint32( offset + 4 ) !== 0x45786966 ) {
// No Exif data, might be XMP data instead
return;
}
if ( tiffOffset + 8 > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid segment size.');
return;
}
// Check for the two null bytes:
if ( dataView.getUint16( offset + 8 ) !== 0x0000 ) {
Base.log('Invalid Exif data: Missing byte alignment offset.');
return;
}
// Check the byte alignment:
switch ( dataView.getUint16( tiffOffset ) ) {
case 0x4949:
littleEndian = true;
break;
case 0x4D4D:
littleEndian = false;
break;
default:
Base.log('Invalid Exif data: Invalid byte alignment marker.');
return;
}
// Check for the TIFF tag marker (0x002A):
if ( dataView.getUint16( tiffOffset + 2, littleEndian ) !== 0x002A ) {
Base.log('Invalid Exif data: Missing TIFF marker.');
return;
}
// Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
dirOffset = dataView.getUint32( tiffOffset + 4, littleEndian );
// Create the exif object to store the tags:
data.exif = new EXIF.ExifMap();
// Parse the tags of the main image directory and retrieve the
// offset to the next directory, usually the thumbnail directory:
dirOffset = EXIF.parseExifTags( dataView, tiffOffset,
tiffOffset + dirOffset, littleEndian, data );
// 尝试读取缩略图
// if ( dirOffset ) {
// thumbnailData = {exif: {}};
// dirOffset = EXIF.parseExifTags(
// dataView,
// tiffOffset,
// tiffOffset + dirOffset,
// littleEndian,
// thumbnailData
// );
// // Check for JPEG Thumbnail offset:
// if (thumbnailData.exif[0x0201]) {
// data.exif.Thumbnail = EXIF.getExifThumbnail(
// dataView,
// tiffOffset + thumbnailData.exif[0x0201],
// thumbnailData.exif[0x0202] // Thumbnail data length
// );
// }
// }
};
ImageMeta.parsers[ 0xffe1 ].push( EXIF.parseExifData );
return EXIF;
});
/**
* @fileOverview Transport
* @todo 支持chunked传输,优势:
* 可以将大文件分成小块,挨个传输,可以提高大文件成功率,当失败的时候,也只需要重传那小部分,
* 而不需要重头再传一次。另外断点续传也需要用chunked方式。
*/
define( 'runtime/html5/transport', [
'base',
'runtime/html5/runtime'
], function( Base, Html5Runtime ) {
var noop = Base.noop,
$ = Base.$;
return Html5Runtime.register( 'Transport', {
init: function() {
this._status = 0;
this._response = null;
},
send: function() {
var owner = this.owner,
opts = this.options,
xhr = this._initAjax(),
blob = owner._blob,
server = opts.server,
formData, binary;
if ( opts.sendAsBinary ) {
server += (/\?/.test( server ) ? '&' : '?') +
$.param( owner._formData );
binary = blob.getSource();
} else {
formData = new FormData();
$.each( owner._formData, function( k, v ) {
formData.append( k, v );
});
formData.append( opts.fileVar, blob.getSource(),
opts.filename || owner._formData.name || '' );
}
if ( opts.withCredentials && 'withCredentials' in xhr ) {
xhr.open( opts.method, server, true );
xhr.withCredentials = true;
} else {
xhr.open( opts.method, server );
}
this._setRequestHeader( xhr, opts.headers );
binary && xhr.overrideMimeType('application/octet-stream');
xhr.send( binary || formData );
},
getResponse: function() {
return this._response;
},
getResponseAsJson: function() {
return this._parseJson( this._response );
},
getStatus: function() {
return this._status;
},
abort: function() {
var xhr = this._xhr;
if ( xhr ) {
xhr.upload.onprogress = noop;
xhr.onreadystatechange = noop;
xhr.abort();
this._xhr = xhr = null;
}
},
destroy: function() {
this.abort();
},
_initAjax: function() {
var me = this,
xhr = new XMLHttpRequest(),
opts = this.options;
if ( opts.withCredentials && !('withCredentials' in xhr) &&
typeof XDomainRequest !== 'undefined' ) {
xhr = new XDomainRequest();
}
xhr.upload.onprogress = function( e ) {
var percentage = 0;
if ( e.lengthComputable ) {
percentage = e.loaded / e.total;
}
return me.trigger( 'progress', percentage );
};
xhr.onreadystatechange = function() {
if ( xhr.readyState !== 4 ) {
return;
}
xhr.upload.onprogress = noop;
xhr.onreadystatechange = noop;
me._xhr = null;
// 只考虑200的情况
if ( xhr.status === 200 ) {
me._response = xhr.responseText;
return me.trigger('load');
}
me._status = xhr.status;
xhr = null;
return me.trigger( 'error', me._status ? 'http' : 'abort' );
};
me._xhr = xhr;
return xhr;
},
_setRequestHeader: function( xhr, headers ) {
$.each( headers, function( key, val ) {
xhr.setRequestHeader( key, val );
});
},
_parseJson: function( str ) {
var json;
try {
json = JSON.parse( str );
} catch ( ex ) {
json = {};
}
return json;
}
});
});
/**
* @fileOverview DragAndDrop Widget。
*/
define( 'widgets/filednd', [
'base',
'uploader',
'lib/dnd',
'widgets/widget'
], function( Base, Uploader, Dnd ) {
Uploader.options.dnd = '';
/**
* @property {Selector} [dnd=undefined] 指定Drag And Drop拖拽的容器,如果不指定,则不启动。
* @namespace options
* @for Uploader
*/
return Uploader.register({
init: function( opts ) {
if ( !opts.dnd ||
this.request('predict-runtime-type') !== 'html5' ) {
return;
}
var me = this,
deferred = Base.Deferred(),
options = $.extend({}, {
container: opts.dnd,
accept: opts.accept
}),
dnd;
dnd = new Dnd( options );
dnd.once( 'ready', deferred.resolve );
dnd.on( 'drop', function( files ) {
me.request( 'add-file', [ files ]);
});
dnd.init();
return deferred.promise();
}
});
});
/**
* @fileOverview 组件基类。
*/
define( 'widgets/filepaste', [
'base',
'uploader',
'lib/filepaste',
'widgets/widget'
], function( Base, Uploader, FilePaste ) {
/**
* @property {Selector} [paste=undefined] 指定监听paste事件的容器,如果不指定,不启用此功能。此功能为通过粘贴来添加截屏的图片。建议设置为`document.body`.
* @namespace options
* @for Uploader
*/
return Uploader.register({
init: function( opts ) {
if ( !opts.paste ||
this.request('predict-runtime-type') !== 'html5' ) {
return;
}
var me = this,
deferred = Base.Deferred(),
options = $.extend({}, {
container: opts.paste,
accept: opts.accept
}),
paste;
paste = new FilePaste( options );
paste.once( 'ready', deferred.resolve );
paste.on( 'paste', function( files ) {
me.owner.request( 'add-file', [ files ]);
});
paste.init();
return deferred.promise();
}
});
});
/**
* @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,
*
* // 是否保留头部meta信息。
* preserveHeaders: false,
*
* // 为空的话则保留原有图片格式。
* // 否则强制转换成指定的类型。
* type: 'image/jpeg'
* }
* ```
*/
thumb: {
width: 110,
height: 110,
quality: 70,
allowMagnify: true,
crop: true,
preserveHeaders: false,
// 为空的话则保留原有图片格式。
// 否则强制转换成指定的类型。
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
* }
* ```
*/
compress: {
width: 1600,
height: 1600,
quality: 90,
allowMagnify: false,
crop: false,
preserveHeaders: true
}
});
return Uploader.register({
'make-thumb': 'makeThumb',
'before-send-file': 'compressImage'
}, {
/**
* 生成缩略图,此过程为异步,所以需要传入`callback`。
* 通常情况在图片加入队里后调用此方法来生成预览图以增强交互效果。
*
* `callback`中可以接收到两个参数。
* * 第一个为error,如果生成缩略图有错误,此error将为真。
* * 第二个为ret, 缩略图的Data URL值。
*
* **注意**
* Date URL在IE6/7中不支持,所以不用调用此方法了,直接显示一张暂不支持预览图片好了。
*
*
* @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();
image.resize( width, height );
});
image.once( 'complete', function() {
cb( false, image.getAsDataUrl( opts.type ) );
image.destroy();
});
image.once( 'error', function() {
cb( 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 );
});
},
compressImage: function( file ) {
var opts = this.options.compress || this.options.resize,
compressSize = opts && opts.compressSize || 300 * 1024,
image, deferred;
file = this.request( 'get-file', file );
// 只预览图片格式。
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() {
file._info = file._info || image.info();
file._meta = file._meta || image.meta();
image.resize( opts.width, opts.height );
});
image.once( 'complete', function() {
var blob, size;
blob = image.getAsBlob( opts.type );
size = file.size;
// 如果压缩后,比原来还大则不用压缩后的。
if ( 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( true );
});
file._info && image.info( file._info );
file._meta && image.meta( file._meta );
image.loadFromBlob( file.source );
return deferred.promise();
}
});
});
/**
* @fileOverview 队列
*/
define( 'widgets/queue', [
'base',
'uploader',
'queue',
'file',
'widgets/widget'
], function( Base, Uploader, Queue, WUFile ) {
var $ = Base.$,
rExt = /\.\w+$/,
Status = WUFile.Status;
return Uploader.register({
'add-file': 'addFiles',
'get-file': 'getFile',
'fetch-file': 'fetchFile',
'get-stats': 'getStats',
'get-files': 'getFiles',
'remove-file': 'removeFile',
'retry': 'retry'
}, {
init: function( opts ) {
var len, i, item, arr, accept;
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, '.*' ) + '$';
}
this.accept = new RegExp( accept, 'i' );
}
this.queue = new Queue();
this.stats = this.queue.stats;
},
/**
* @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;
if ( !file || file.size < 6 || me.accept &&
// 如果名字中有后缀,才做后缀白名单处理。
rExt.exec( file.name ) && !me.accept.test( file.name ) ) {
return;
}
if ( !(file instanceof WUFile) ) {
file = new WUFile( file );
}
if ( !me.owner.trigger( 'beforeFileQueued', 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
*/
addFiles: 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 ) {
me.request('start-upload');
}
},
getStats: function() {
return this.stats;
},
/**
* @event fileDequeued
* @param {File} file File对象
* @description 当文件被移除队列后触发。
* @for Uploader
*/
/**
* @method removeFile
* @grammar removeFile( file ) => undefined
* @grammar removeFile( id ) => undefined
* @param {File|id} file File对象或这File对象的id
* @description 移除某一文件。
* @for Uploader
* @example
*
* $li.on('click', '.remove-this', function() {
* uploader.removeFile( file );
* })
*/
removeFile: function( file ) {
var me = this;
file = file.id ? file : me.queue.getFile( file );
file.setStatus( Status.CANCELLED );
me.owner.trigger( 'fileDequeued', 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');
}
});
});
/**
* @fileOverview 添加获取Runtime相关信息的方法。
*/
define( 'widgets/runtime', [
'uploader',
'runtime/runtime',
'widgets/widget'
], function( Uploader, Runtime ) {
Uploader.support = function() {
return Runtime.hasRuntime.apply( Runtime, arguments );
};
return Uploader.register({
'predict-runtime-type': 'predictRuntmeType'
}, {
init: function() {
if ( !this.predictRuntmeType() ) {
throw Error('Runtime Error');
}
},
/**
* 预测Uploader将采用哪个`Runtime`
* @grammar predictRuntmeType() => String
* @method predictRuntmeType
* @for Uploader
*/
predictRuntmeType: 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 负责文件上传相关。
*/
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: null
});
// 负责将文件切片。
function CuteFile( file, chunkSize ) {
var pending = [],
blob = file.source,
total = blob.size,
chunks = chunkSize ? Math.ceil( total / chunkSize ) : 1,
start = 0,
index = 0,
len;
while ( index < chunks ) {
len = Math.min( chunkSize, total - start );
pending.push({
file: file,
start: start,
end: start + len,
total: total,
chunks: chunks,
chunk: index++
});
start += len;
}
file.blocks = pending.concat();
file.remaning = pending.length;
return {
file: file,
has: function() {
return !!pending.length;
},
fetch: function() {
return pending.shift();
}
};
}
Uploader.register({
'start-upload': 'start',
'stop-upload': 'stop',
'skip-file': 'skipFile',
'is-in-progress': 'isInProgress'
}, {
init: function() {
var owner = this.owner;
this.runing = false;
// 记录当前正在传的数据,跟threads相关
this.pool = [];
// 缓存即将上传的文件。
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;
});
},
/**
* @event startUpload
* @description 当开始上传流程时触发。
* @for Uploader
*/
/**
* 开始上传。此方法可以从初始状态调用开始上传流程,也可以从暂停状态调用,继续上传流程。
* @grammar upload() => undefined
* @method upload
* @for Uploader
*/
start: function() {
var me = this;
// 移出invalid的文件
$.each( me.request( 'get-files', Status.INVALID ), function() {
me.request( 'remove-file', this );
});
if ( me.runing ) {
return;
}
me.runing = true;
// 如果有暂停的,则续传
$.each( me.pool, function( _, v ) {
var file = v.file;
if ( file.getStatus() === Status.INTERRUPT ) {
file.setStatus( Status.PROGRESS );
me._trigged = false;
v.transport && v.transport.send();
}
});
me._trigged = false;
me.owner.trigger('startUpload');
Base.nextTick( me.__tick );
},
/**
* @event stopUpload
* @description 当开始上传流程暂停时触发。
* @for Uploader
*/
/**
* 暂停上传。第一个参数为是否中断上传当前正在上传的文件。
* @grammar stop() => undefined
* @grammar stop( true ) => undefined
* @method stop
* @for Uploader
*/
stop: function( interrupt ) {
var me = this;
if ( me.runing === false ) {
return;
}
me.runing = false;
interrupt && $.each( me.pool, function( _, v ) {
v.transport && v.transport.abort();
v.file.setStatus( Status.INTERRUPT );
});
me.owner.trigger('stopUpload');
},
/**
* 判断`Uplaode`r是否正在上传中。
* @grammar isInProgress() => Boolean
* @method isInProgress
* @for Uploader
*/
isInProgress: function() {
return !!this.runing;
},
getStats: function() {
return this.request('get-stats');
},
/**
* 掉过一个文件上传,直接标记指定文件为已上传状态。
* @grammar skipFile( file ) => undefined
* @method skipFile
* @for Uploader
*/
skipFile: function( file, status ) {
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.runing = false;
me._trigged || Base.nextTick(function() {
me.owner.trigger('uploadFinished');
});
me._trigged = true;
}
},
_nextBlock: function() {
var me = this,
act = me._act,
opts = me.options,
next, done;
// 如果当前文件还有没有需要传输的,则直接返回剩下的。
if ( act && act.has() &&
act.file.getStatus() === Status.PROGRESS ) {
// 是否提前准备下一个文件
if ( opts.prepareNextFile && !me.pending.length ) {
me._prepareNextFile();
}
return act.fetch();
// 否则,如果正在运行,则准备下一个文件,并等待完成后返回下个分片。
} 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._act = act;
return act.fetch();
};
// 文件可能还在prepare中,也有可能已经完全准备好了。
return isPromise( next ) ? next.then( done ) : 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.QUEUED ) {
me.owner.trigger( 'uploadStart', file );
file.setStatus( Status.PROGRESS );
return file;
}
return me._finishFile( 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;
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._popBlock( block );
Base.nextTick( me.__tick );
}
});
},
/**
* @event uploadBeforeSend
* @param {Object} object
* @param {Object} data 默认的上传参数,可以扩展此对象来控制上传参数。
* @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对象
* @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 );
block.transport = tr;
tr.on( 'destroy', function() {
delete block.transport;
me._popBlock( block );
Base.nextTick( me.__tick );
});
// 广播上传进度。以文件为单位。
tr.on( 'progress', function( percentage ) {
var totalPercent = 0,
uploaded = 0;
// 可能没有abort掉,progress还是执行进来了。
// if ( !file.blocks ) {
// return;
// }
totalPercent = block.percentage = percentage;
if ( block.chunks > 1 ) { // 计算文件的整体速度。
$.each( file.blocks, function( _, v ) {
uploaded += (v.percentage || 0) * (v.end - v.start);
});
totalPercent = uploaded / file.size;
}
owner.trigger( 'uploadProgress', file, totalPercent || 0 );
});
// 尝试重试,然后广播文件上传出错。
tr.on( 'error', function( type ) {
block.retried = block.retried || 0;
// 自动重试
if ( block.chunks > 1 && ~'http,abort'.indexOf( type ) &&
block.retried < opts.chunkRetry ) {
block.retried++;
tr.send();
} else {
file.setStatus( Status.ERROR, type );
owner.trigger( 'uploadError', file, type );
owner.trigger( 'uploadComplete', file );
}
});
// 上传成功
tr.on( 'load', function() {
var ret = tr.getResponseAsJson() || {},
reject, fn;
ret._raw = tr.getResponse();
fn = function( value ) {
reject = value;
};
// 服务端响应了,不代表成功了,询问是否响应正确。
if ( !owner.trigger( 'uploadAccept', block, ret, fn ) ) {
reject = reject || 'server';
}
// 如果非预期,转向上传出错。
if ( reject ) {
tr.trigger( 'error', reject );
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 );
});
}
});
});
/**
* @fileOverview 各种验证,包括文件总大小是否超出、单文件是否超出和文件是否重复。
*/
define( 'widgets/validator', [
'base',
'uploader',
'file',
'widgets/widget'
], function( Base, Uploader, WUFile ) {
var $ = Base.$,
validators = {},
api;
// 暴露给外面的api
api = {
// 添加验证器
addValidator: function( type, cb ) {
validators[ type ] = cb;
},
// 移除验证器
removeValidator: function( type ) {
delete validators[ type ];
}
};
// 在Uploader初始化的时候启动Validators的初始化
Uploader.register({
init: function() {
var me = this;
$.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 = opts.fileNumLimit >> 0,
flag = true;
if ( !max ) {
return;
}
uploader.on( 'beforeFileQueued', function() {
if ( count >= max && flag ) {
flag = false;
this.trigger( 'error', 'Q_EXCEED_NUM_LIMIT', max );
setTimeout(function() {
flag = true;
}, 1 );
}
return count >= max ? false : true;
});
uploader.on( 'fileQueued', function() {
count++;
});
uploader.on( 'fileDequeued', function() {
count--;
});
});
/**
* @property {int} [fileSizeLimit=undefined]
* @namespace options
* @for Uploader
* @description 验证文件总大小是否超出限制, 超出则不允许加入队列。
*/
api.addValidator( 'fileSizeLimit', function() {
var uploader = this,
opts = uploader.options,
count = 0,
max = opts.fileSizeLimit >> 0,
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 );
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;
});
});
/**
* @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( 'fileQueued', function( file ) {
if ( file.size > max ) {
file.setStatus( WUFile.Status.INVALID, 'exceed_size' );
}
});
});
/**
* @property {int} [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 = hashString( file.name + file.size +
file.lastModifiedDate );
// 已经重复了
if ( mapping[ hash ] ) {
return false;
}
});
uploader.on( 'fileQueued', function( file ) {
var hash = hashString( file.name + file.size +
file.lastModifiedDate );
mapping[ hash ] = true;
});
uploader.on( 'fileDequeued', function( file ) {
var hash = hashString( file.name + file.size +
file.lastModifiedDate );
delete mapping[ hash ];
});
});
return api;
});
/**
* @file 暴露变量给外部使用。
* 此文件也只有在把webupload合并成一个文件使用的时候才会引入。
*
* 将所有modules,将路径ids装换成对象。
*/
(function( modules ) {
var
// 让首写字母大写。
ucFirst = function( str ) {
return str && (str.charAt( 0 ).toUpperCase() + str.substr( 1 ));
},
// 暴露出去的key
exportName = 'WebUploader',
exports = modules.base,
key, host, parts, part, last, origin;
for ( key in modules ) {
host = exports;
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 ];
}
if ( typeof module === 'object' && typeof module.exports === 'object' ) {
module.exports = exports;
} else if ( window.define && window.define.amd ) {
window.define( function() { return exports; } );
} else {
origin = window[ exportName ];
window[ exportName ] = exports;
window[ exportName ].noConflict = function() {
window[ exportName ] = origin;
};
}
})( internalAmd.modules );
})( this );
================================================
FILE: bower.json
================================================
{
"name": "fex-webuploader",
"main": "dist/webuploader.js",
"homepage": "https://github.com/fex-team/webuploader",
"author": "fex-team",
"description": "WebUploader是一个简单的以Html5为主,Flash为辅的现代文件上传组件。在现代的浏览器里面能充分发挥html5的优势,同时又不摒弃主流IE浏览器,延用原来的Flash运行时。两套运行时,同样的调用方式,可供用户任意选用。WebUploader采用大文件分片并发上传,极大的提高了文件上传效率。",
"keywords": [
"fileuploader",
"chunk",
"uploader",
"html5",
"flash"
],
"dependencies": {
"jquery": ">= 1.9.0"
},
"license": "BSD",
"ignore": [
"**/.*",
"node_modules",
"/build",
"/css",
"/jekyll",
"/server",
"/test",
"/_draft",
"/examples",
"/flash",
"/pages"
]
}
================================================
FILE: build/docTpl/class.ejs
================================================
<% var item; if( (item = items[ 0 ]) && item.hasOwnProperty('constructor') ) { %>
class="deprecated"<% } %> ><%= item.name %>
<% if ( item.since ) { %><%- item.since %> <% } %>
<% if ( item[ 'deprecated' ] ) { %><%- markdown( item[ 'deprecated' ] ) %>
<% } %>
<% if( item.uses ) { %><%- renderUses( item.uses ) %><% }%>
<% if ( item.grammars ) { %>
<% _.forEach( item.grammars, function( grammar ) { %>
<%= grammar.signature %>
<% if ( grammar.return ) { %>⇒ <%= grammar.return %> <% } %>
<% if ( grammar.since ) { %><%= grammar.since %> <% } %>
<% });%>
<% } %>
<% if ( item.params ) { %>
参数:
<%- renderParams( item.params ) %>
<% } %>
<% if ( item.returns ) { %>
返回值:
<%- renderParams( item.returns ) %>
<% } %>
<%- markdown( item.description || description || '' ) %>
<% _.forEach( item.examples || [], function( example ) { %>
<%- formatExample( example ) %>
<% }) %>
<% } else { %>
<%= title || name %>
<% if ( description ) { %><%- markdown( description ) %><% } %>
<% } %>
<% if ( options.length ) { %> <%- renderTpl( 'options' ) %> <% } %>
<% if ( events.length ) { %> <%- renderTpl( 'events' ) %> <% } %>
<% if ( items.length ) { %> <%- renderTpl( 'items' ) %> <% } %>
<% if ( plugins.length ) { %> <%- renderTpl( 'plugins' ) %> <% } %>
================================================
FILE: build/docTpl/content.ejs
================================================
<% _.forEach( modules, function( module ) { %>
<%- renderTpl( 'module', module ) %>
<% }) %>
================================================
FILE: build/docTpl/css/doc.css
================================================
ul.signature {
margin: 1em 0;
padding: 0;
font: normal 12px/18px Monaco, Consolas, "Lucida Console", monospace;
}
ul.signature li {
list-style: none;
}
.method p {
margin: 0.5em 0;
}
.method h3 {
margin-bottom: .2em;
}
.method h3.deprecated {
text-decoration: line-through;
}
span.deleted {
text-decoration: line-through;
}
.method pre.cm-s-default {
display: block;
white-space: pre-wrap;
margin: 1em 0px;
}
.method .warning {
margin: 5px 0;
font: bold 12px Arial;
color: #700;
}
.method .version {
background: #CCF;
color: black;
padding: 1px 3px;
margin: 0 0 0 5px;
border-radius: 3px;
font: bold 11px Arial;
font-weight: normal;
}
div.notice {
padding: 4px 10px;
border-left: 2px solid #FF8;
background: #FFE;
color: black;
margin: 1em 0;
}
ul.params-list li > span.meta + p, ol.plugin-list li > code + p {
display: inline;
padding-left: 10px;
}
table.table .events-tb-desc {
min-width: 250px;
}
================================================
FILE: build/docTpl/events.ejs
================================================
事件说明
事件名
参数说明
描述
<% _.forEach( events, function( item ) { %>
<%= item.name %>
<% if ( item.params ) { %>
<%- renderParams( item.params ) %>
<% } %>
<%- markdown(item.description) %>
<% }) %>
================================================
FILE: build/docTpl/items.ejs
================================================
<% _.sortBy( items, function( value ){ return value.uses ? value.uses.length : 0; } ).forEach(function( item ) { %>
<% if( item.hasOwnProperty('constructor') ) { return; } %>
class="deprecated"<% } %> ><%= item.name %>
<% if ( item.since ) { %><%- item.since %> <% } %>
<% if ( item[ 'deprecated' ] ) { %><%- markdown( item[ 'deprecated' ] ) %>
<% } %>
<% if( item.uses ) { %><%- renderUses( item.uses ) %><% }%>
<% if ( item.grammars ) { %>
<% _.forEach( item.grammars, function( grammar ) { %>
<%= grammar.signature %>
<% if ( grammar.return ) { %>⇒ <%= grammar.return %> <% } %>
<% if ( grammar.since ) { %><%= grammar.since %> <% } %>
<% });%>
<% } %>
<% if ( item.params ) { %>
参数:
<%- renderParams( item.params ) %>
<% } %>
<% if ( item.returns ) { %>
返回值:
<%- renderParams( item.returns ) %>
<% } %>
<%- markdown( item.description || '' ) %>
<% _.forEach( item.examples || [], function( example ) { %>
<%- formatExample( example ) %>
<% }) %>
<% }) %>
================================================
FILE: build/docTpl/layout.ejs
================================================
---
layout: default
title: <%= title %>
navName: API
group: 'nav'
weight : 3
styles:
- /doc/css/doc.css
---
<%- renderTpl('content').replace(/
([\s\S]*?)<\/code><\/pre>/igm, function( m0, m1, m2 ) {
return '\n' +
'{% highlight ' + m1 + ' %}\n' +
m2.replace(/&/g, '&')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, '\'') +
'\n{% endhighlight %}\n';
}) %>
================================================
FILE: build/docTpl/module.ejs
================================================
<% if ( title ) { %>
<% } %>
<%- markdown( description ) %>
<%- renderTpl('sidebar') %>
<% if ( items ) { %>
<%- renderTpl( 'items' ) %>
<% } %>
<% _.forEach( classes, function( clazz ) { %>
<%- clazz.isPlugin ? '' : renderTpl( 'class', clazz ) %>
<% }) %>
================================================
FILE: build/docTpl/options.ejs
================================================
参数说明
<% _.sortBy( options, function( value ){ return value.uses ? value.uses.length : 0; } ).forEach(function( item ) { %>
<%= item.shortname || item.name %>
<% if ( item.type ) { %> {<%=: item.type | join:', ' %>} <% }%>
<% if ( item.optional ) { %> [可选] <% }%>
<% if ( item.defaultvalue ) { %> [默认值:<%= item.defaultvalue %>] <% }%>
<%- markdown(item.description) %>
<% if ( item.uses ) { %>
<%- renderUses( item.uses, '依赖: %s。' ) %>
<% } %>
<% }) %>
================================================
FILE: build/docTpl/plugins.ejs
================================================
插件介绍
<% _.forEach( plugins, function( item ) { %>
<%= item.shortname || item.name %><%- markdown(item.description) %>
<%- renderFileInfo( item.file ) %>
<% }) %>
================================================
FILE: build/docTpl/sidebar.ejs
================================================
<% _.forEach( navs, function( classes, modulename ) { %>
<% _.forEach( classes, function( items, classname ) { %>
<%= classname %>
<% _.forEach( items, function( item ) { %>
<% if( item.text === classname ) { return; } %>
<%= item.text %>
<% });%>
<% }); %>
<% }); %>
================================================
FILE: build/fis/intro.js
================================================
var jQuery = require('example:widget/ui/jquery/jquery.js');
module.exports = (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 ) );
};
return makeExport( jQuery );
})( window, function( window, define, require ) {
================================================
FILE: build/fis/outro.js
================================================
var _require = require;
return _require('webuploader');
});
================================================
FILE: build/intro.js
================================================
/**
* @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 ) {
================================================
FILE: build/outro.js
================================================
return require('webuploader');
});
================================================
FILE: build/tasks/build.js
================================================
/**
* @fileOverview 负责合并amd modules为一个单文件。
*/
'use strict';
var requirejs = require('requirejs'),
fs = require('fs'),
path = require('path');
// convert relative path to absolute path.
function convert( name, _path, contents ) {
var rDefine = /(define\s*\(\s*('|").*?\2\s*,\s*\[)([\s\S]*?)\]/ig,
rDeps = /('|")(.*?)\1/g,
root = _path.substr( 0, _path.length - name.length - 3 ),
dir = path.dirname( _path ),
m, m2, deps, dep, _path2;
contents = contents.replace( rDefine, function( m, m1, m2, m3 ) {
return m1 + m3.replace( rDeps, function( m, m1, m2 ) {
m2 = path.join( dir, m2 );
m2 = path.relative( root, m2 );
m2 = m2.replace(/\\/g, '/');
return m1 + m2 + m1;
}) + ']';
});
return contents;
}
module.exports = function( grunt ) {
grunt.registerMultiTask( 'build', '合并amd modules为一个单文件', function() {
var done = this.async(),
options = this.options({
banner: '',
footer: '',
process: null,
builtin: {
dollar: false,
promise: false
}
}),
pkg = grunt.config.get('pkg'),
dest = this.data.dest,
config, flag, custom;
config = {
baseUrl: 'src',
name: '',
out: '',
// We have multiple minify steps
optimize: 'none',
// Include dependencies loaded with require
findNestedDependencies: true,
// Avoid breaking semicolons inserted by r.js
skipSemiColonInsertion: true,
wrap: {
startFile: 'build/intro.js',
endFile: 'build/outro.js'
},
rawText: {},
onBuildWrite: function( name, _path ) {
var compiled = convert.apply( null, arguments );
if ( options.process ) {
compiled = options.process( compiled, _path );
}
// 调整缩进
compiled = compiled.replace( /(^|\r\n|\r|\n)/g, '$1 ');
compiled = compiled.replace(/@version@/g, function() {
return pkg.version;
});
return compiled;
},
paths: [],
include: []
};
options = grunt.util._.extend( options, this.data );
config.name = 'webuploader';
if ( options.builtin.dollar ) {
config.rawText.dollar = 'define([\n' +
' \'./dollar-builtin\'\n' +
'], function( $ ) {\n' +
' return $;\n' +
'});';
}
if ( options.builtin.promise ) {
config.rawText.promise = 'define([\n' +
' \'./promise-builtin\'\n' +
'], function( $ ) {\n' +
' return $;\n' +
'});';
}
if ( this.data.preset === 'custom' ) {
custom = [];
this.files.forEach(function( file ) {
var files = file.src,
cwd = file.cwd || '';
files.filter(function( filepath ) {
filepath = path.join( cwd, filepath );
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
}).forEach(function( filepath ) {
custom.push( '\'' + filepath.replace( /\.\w+$/, '' ) + '\'' );
});
});
custom.unshift('\'./base\'');
custom = 'define([\n ' + custom.join(',\n ') + '\n], function( Base ) {\n return Base;\n});';
config.rawText.webuploader = custom;
} else if (this.data.preset) {
config.rawText.webuploader = 'define([\n ' + ['\'./preset/' +
this.data.preset +'\''].join(',\n ') +
'\n], function( preset ) {\n return preset;\n});';
} else {
config.name = this.data.name;
}
// 处理最终输出
config.out = function( compiled ) {
var arr = [],
banner = grunt.template.process(options.banner),
footer = grunt.template.process(options.footer),
sep = '\n\n';
banner && arr.push( banner );
if ( options.builtin.dollar ) {
compiled = compiled.replace('define([ \'jquery\' ], exports );', 'define([], exports);');
}
arr.push(compiled);
footer && arr.push( footer );
// Write concatenated source to file
grunt.file.write( dest, arr.join( sep ) );
process.nextTick(function() {
// requirejs有bug, callback不一定会执行,目前调试的结果是
// prim的promise实现有问题。
if ( flag ) return;
grunt.log.ok( "File '" + dest + "' created." );
done();
flag = true;
});
};
if (options.fis) {
config.wrap = {
startFile: 'build/fis/intro.js',
endFile: 'build/fis/outro.js'
}
}
requirejs.optimize( config, function( response ) {
// requirejs有bug, callback不一定会执行,目前调试的结果是
// prim的promise实现有问题。
if ( flag ) return;
grunt.verbose.writeln( response );
grunt.log.ok( "File '" + name + "' created." );
done();
flag = true;
}, function( err ) {
done( err );
});
});
};
================================================
FILE: build/tasks/concat.js
================================================
/*
* grunt-contrib-concat
* http://gruntjs.com/
*
* Copyright (c) 2013 "Cowboy" Ben Alman, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
var path = require('path');
function stripBanner(src, options) {
if (!options) {
options = {};
}
var m = [];
if (options.line) {
// Strip // ... leading banners.
m.push('(?:.*\\/\\/.*\\r?\\n)*\\s*');
}
if (options.block) {
// Strips all /* ... */ block comment banners.
m.push('\\/\\*[\\s\\S]*?\\*\\/');
} else {
// Strips only /* ... */ block comment banners, excluding /*! ... */.
m.push('\\/\\*[^!][\\s\\S]*?\\*\\/');
}
var re = new RegExp('^\\s*(?:' + m.join('|') + ')\\s*', '');
return src.replace(re, '');
}
var intro = path.join(__dirname, '../intro.js');
var outro = path.join(__dirname, '../outro.js');
// 排序,把依赖的文件移动到最上面。
function filesFilter( f, files ) {
var cwd = f.cwd || '',
ret = [],
process = function( file ) {
var fileinfo = path.join( cwd, file ),
dirpath = path.dirname( fileinfo ),
depends = [],
str, matches, idx;
if ( !grunt.file.exists( fileinfo ) ) {
return;
}
ret.push( file );
str = grunt.file.read( fileinfo );
// 从require( dps )中找
// 从defind( id?, dps, factory )中找
str = str.replace( /(?:define|require)\s*\(\s*\[([^\]]+?)\],/g, function( _, m1 ) {
m1 = m1.replace(/\s/g, '').split(',');
depends = depends.concat( m1.map(function( item ) {
item = item.substring( 1, item.length - 1 );
item = item.substring(0, 1) === '.' ?
path.join( dirpath, item ):
path.join( cwd, item );
return path.relative( cwd, item ) + '.js';
}) );
return _;
});
str = str.replace( /require\s*\(\s*('|")(.+?)\1/g, function( _, m1, item ) {
item = item.substring(0, 1) === '.' ?
path.join( dirpath, item ):
path.join( cwd, item );
depends.push( path.relative( cwd, item ) + '.js' );
return _;
});
if ( depends.length ) {
depends = depends.filter(function( item, idx, array ) {
return array.indexOf( item ) === idx && grunt.file.exists( path.join( cwd, item ) );
});
idx = ret.indexOf( file );
[].splice.apply( ret, [ idx, 0 ].concat( depends ) );
depends.forEach( process );
}
};
// console.log( files );
files.forEach( process );
ret = ret.filter(function( item, idx, arr ){
return idx === arr.indexOf( item );
});
ret.unshift( path.relative( cwd, intro ) );
ret.push( path.relative( cwd, outro ) );
return ret;
}
// 缓存版本号
var version;
function fileProcess( src, filepath, cwd ) {
var dirpath = path.dirname( filepath );
version = version || grunt.config.get('pkg.version');
src = src.replace( /@version@/g, version );
// 不处理 outro.js
if (filepath.indexOf('outro') >= 0) {
return src;
}
// console.log( filepath, cwd );
// 处理 define( dps ?, factory );
// 处理 require( dps );
src = src.replace( /(define|require)\s*\((?:\s*\[([^\]]+)\],)?/g, function( _, m1, m2 ) {
var str = m1 + '(',
item;
if ( m1 === 'define' ) {
item = path.relative( cwd, filepath );
item = item.substring( 0, item.length - 3 );
str += ' \'' + item.replace(/\\/g, '/') + '\', ';
}
if ( m2 ) {
m2 = m2.replace(/\s/g, '').split(',');
m2 = m2.map(function( item ) {
var _file = item;
_file = _file.substring( 1, _file.length - 1 );
_file = _file.substring(0, 1) === '.' ?
path.join( dirpath, _file ) :
path.join( cwd, _file.substring( 1 ) );
if ( !grunt.file.exists( _file + '.js' ) ) {
return item;
}
_file = path.relative( cwd, _file );
return '\'' + _file.replace(/\\/g, '/').toLowerCase() + '\'';
});
if ( m2.length ) {
str += '[\n ' + m2.join(',\n ') + '\n],';
} else {
str += '[],';
}
}
// console.log( str );
return str;
});
// 处理 require( id );
src = src.replace( /require\s*\(\s*('|")(.+?)\1\s*\)/g, function( _, m1, m2 ) {
var _file = m2;
_file = _file.substring(0, 1) === '.' ?
path.join( dirpath, _file ) :
path.join( cwd, _file.substring( 1 ) );
if ( !grunt.file.exists( _file + '.js' ) ) {
return _;
}
_file = path.relative( cwd, _file );
return 'require(\'' + _file + '\')';
});
return src;
}
grunt.registerMultiTask('concat', 'Concatenate files.', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
separator: grunt.util.linefeed,
banner: '',
footer: '',
stripBanners: false,
process: null,
filesFilter: filesFilter
});
// Normalize boolean options that accept options objects.
if (options.stripBanners === true) {
options.stripBanners = {};
}
if (options.process === true) {
options.process = {};
}
// Process banner and footer.
var banner = grunt.template.process(options.banner);
var footer = grunt.template.process(options.footer);
// Iterate over all src-dest file pairs.
this.files.forEach(function(f) {
var files = f.src;
if (typeof options.filesFilter === 'function') {
files = options.filesFilter( f, files );
}
// Concat banner + specified files + footer.
var cwd = f.cwd || '',
src = banner + files.filter(function(filepath) {
filepath = path.join( cwd, filepath );
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
}).map(function(filepath) {
filepath = path.join( cwd, filepath );
// Read file source.
var src = grunt.file.read(filepath);
// 文件处理,用来支持amdefine
src = fileProcess( src, filepath, cwd );
// Process files as templates if requested.
if (typeof options.process === 'function') {
src = options.process(src, filepath);
} else if (options.process) {
src = grunt.template.process(src, options.process);
}
// Strip banners if requested.
if (options.stripBanners) {
src = stripBanner(src, options.stripBanners);
}
return src;
}).join(options.separator) + footer;
// Write the destination file.
grunt.file.write(f.dest, src);
// Print a success message.
grunt.log.writeln('File "' + f.dest + '" created.');
});
});
};
================================================
FILE: build/tasks/doc.js
================================================
module.exports = function( grunt ) {
grunt.registerTask( 'doc', '生成文档', function() {
var Doc = require( 'gmudoc/lib/doc.js' );
var opts = this.options({
cwd: '',
files: [],
theme: 'gmu',
outputDir: './doc'
}),
done = this.async();
var ins = new Doc( opts );
ins.run( done );
});
};
================================================
FILE: css/webuploader.css
================================================
.webuploader-container {
position: relative;
}
.webuploader-element-invisible {
position: absolute !important;
clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
clip: rect(1px,1px,1px,1px);
}
.webuploader-pick {
position: relative;
display: inline-block;
cursor: pointer;
background: #00b7ee;
padding: 10px 15px;
color: #fff;
text-align: center;
border-radius: 3px;
overflow: hidden;
}
.webuploader-pick-hover {
background: #00a2d4;
}
.webuploader-pick-disable {
opacity: 0.6;
pointer-events:none;
}
================================================
FILE: dist/README.md
================================================
目录说明
========================
```bash
├── Uploader.swf # SWF文件,当使用Flash运行时需要引入。
├
├── webuploader.js # 完全版本。
├── webuploader.min.js # min版本
├
├── webuploader.flashonly.js # 只有Flash实现的版本。
├── webuploader.flashonly.min.js # min版本
├
├── webuploader.html5only.js # 只有Html5实现的版本。
├── webuploader.html5only.min.js # min版本
├
├── webuploader.noimage.js # 去除图片处理的版本,包括HTML5和FLASH.
├── webuploader.noimage.min.js # min版本
├
├── webuploader.custom.js # 自定义打包方案,请查看 Gruntfile.js,满足移动端使用。
└── webuploader.custom.min.js # min版本
```
## 示例
请把整个 Git 包下载下来放在 php 服务器下,因为默认提供的文件接受是用 php 编写的,打开 examples 页面便能查看示例效果。
================================================
FILE: dist/webuploader.css
================================================
.webuploader-container {
position: relative;
}
.webuploader-element-invisible {
position: absolute !important;
clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
clip: rect(1px,1px,1px,1px);
}
.webuploader-pick {
position: relative;
display: inline-block;
cursor: pointer;
background: #00b7ee;
padding: 10px 15px;
color: #fff;
text-align: center;
border-radius: 3px;
overflow: hidden;
}
.webuploader-pick-hover {
background: #00a2d4;
}
.webuploader-pick-disable {
opacity: 0.6;
pointer-events:none;
}
================================================
FILE: dist/webuploader.custom.js
================================================
/*! WebUploader 0.1.8-alpha */
/**
* @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
* @require "jquery"
* @require "zepto"
*/
define('dollar-third',[],function() {
var req = window.require;
var $ = window.__dollar ||
window.jQuery ||
window.Zepto ||
req('jquery') ||
req('zepto');
if ( !$ ) {
throw new Error('jQuery or Zepto not found!');
}
return $;
});
/**
* @fileOverview Dom 操作相关
*/
define('dollar',[
'dollar-third'
], function( _ ) {
return _;
});
/**
* 直接来源于jquery的代码。
* @fileOverview Promise/A+
* @beta
*/
define('promise-builtin',[
'dollar'
], function( $ ) {
var api;
// 简单版Callbacks, 默认memory,可选once.
function Callbacks( once ) {
var list = [],
stack = !once && [],
fire = function( data ) {
memory = data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
list[ firingIndex ].apply( data[ 0 ], data[ 1 ] );
}
firing = false;
if ( list ) {
if ( stack ) {
stack.length && fire( stack.shift() );
} else {
list = [];
}
}
},
self = {
add: function() {
if ( list ) {
var start = list.length;
(function add ( args ) {
$.each( args, function( _, arg ) {
var type = $.type( arg );
if ( type === 'function' ) {
list.push( arg );
} else if ( arg && arg.length &&
type !== 'string' ) {
add( arg );
}
});
})( arguments );
if ( firing ) {
firingLength = list.length;
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
disable: function() {
list = stack = memory = undefined;
return this;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
fireWith: function( context, args ) {
if ( list && (!fired || stack) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
fire: function() {
self.fireWith( this, arguments );
return this;
}
},
fired, firing, firingStart, firingLength, firingIndex, memory;
return self;
}
function Deferred( func ) {
var tuples = [
// action, add listener, listener list, final state
[ 'resolve', 'done', Callbacks( true ), 'resolved' ],
[ 'reject', 'fail', Callbacks( true ), 'rejected' ],
[ 'notify', 'progress', Callbacks() ]
],
state = 'pending',
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return Deferred(function( newDefer ) {
$.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = $.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for
// forwarding actions to newDefer
deferred[ tuple[ 1 ] ](function() {
var returned;
returned = fn && fn.apply( this, arguments );
if ( returned &&
$.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + 'With' ](
this === promise ?
newDefer.promise() :
this,
fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? $.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
$.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[ 1 ] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[ 0 ] ] = function() {
deferred[ tuple[ 0 ] + 'With' ]( this === deferred ? promise :
this, arguments );
return this;
};
deferred[ tuple[ 0 ] + 'With' ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
}
api = {
/**
* 创建一个[Deferred](http://api.jquery.com/category/deferred-object/)对象。
* 详细的Deferred用法说明,请参照jQuery的API文档。
*
* Deferred对象在钩子回掉函数中经常要用到,用来处理需要等待的异步操作。
*
* @for Base
* @method Deferred
* @grammar Base.Deferred() => Deferred
* @example
* // 在文件开始发送前做些异步操作。
* // WebUploader会等待此异步操作完成后,开始发送文件。
* Uploader.register({
* 'before-send-file': 'doSomthingAsync'
* }, {
*
* doSomthingAsync: function() {
* var deferred = Base.Deferred();
*
* // 模拟一次异步操作。
* setTimeout(deferred.resolve, 2000);
*
* return deferred.promise();
* }
* });
*/
Deferred: Deferred,
/**
* 判断传入的参数是否为一个promise对象。
* @method isPromise
* @grammar Base.isPromise( anything ) => Boolean
* @param {*} anything 检测对象。
* @return {Boolean}
* @for Base
* @example
* console.log( Base.isPromise() ); // => false
* console.log( Base.isPromise({ key: '123' }) ); // => false
* console.log( Base.isPromise( Base.Deferred().promise() ) ); // => true
*
* // Deferred也是一个Promise
* console.log( Base.isPromise( Base.Deferred() ) ); // => true
*/
isPromise: function( anything ) {
return anything && typeof anything.then === 'function';
},
/**
* 返回一个promise,此promise在所有传入的promise都完成了后完成。
* 详细请查看[这里](http://api.jquery.com/jQuery.when/)。
*
* @method when
* @for Base
* @grammar Base.when( promise1[, promise2[, promise3...]] ) => Promise
*/
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
slice = [].slice,
resolveValues = slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || (subordinate &&
$.isFunction( subordinate.promise )) ? length : 0,
// the master Deferred. If resolveValues consist of
// only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ?
slice.call( arguments ) : value;
if ( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !(--remaining) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] &&
$.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts,
resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts,
progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
};
return api;
});
define('promise',[
'promise-builtin'
], 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.8-alpha',
/**
* @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 ||
file.lastModified && new Date(file.lastModified).toLocaleString() ||
(new Date()).toLocaleString();
Blob.apply( this, arguments );
}
return Base.inherits( Blob, File );
});
/**
* @fileOverview 错误信息
*/
define('lib/filepicker',[
'base',
'runtime/client',
'lib/file'
], function( Base, RuntimeClient, 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 );
RuntimeClient.call( this, 'FilePicker', true );
}
FilePicker.options = {
button: null,
container: null,
label: null,
innerHTML: null,
multiple: true,
accept: null,
name: 'file',
style: 'webuploader-pick' //pick element class attribute, default is "webuploader-pick"
};
Base.inherits( RuntimeClient, {
constructor: FilePicker,
init: function() {
var me = this,
opts = me.options,
button = opts.button,
style = opts.style;
if (style)
button.addClass('webuploader-pick');
me.on( 'all', function( type ) {
var files;
switch ( type ) {
case 'mouseenter':
if (style)
button.addClass('webuploader-pick-hover');
break;
case 'mouseleave':
if (style)
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(),
*/
width = button[0] && button[0].offsetWidth || button.outerWidth() || button.width(),
height = button[0] && button[0].offsetHeight || 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 {Array} [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.on('dialogopen', function() {
me.owner.trigger('dialogOpen', picker.button);
});
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.getAsDataUrl( opts.type ) );
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` 被移除的文件数。
* * `numOfInterrupt` 被中断的文件数。
* @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 ];
this._delFile(file);
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 );
});
}
},
_delFile : function(file){
for(var i = this._queue.length - 1 ; i >= 0 ; i-- ){
if(this._queue[i] == file){
this._queue.splice(i,1);
break;
}
}
},
_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 );
});
if ( files.length ) {
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();
},
getResponseHeaders: function() {
return this.exec('getResponseHeaders');
},
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 {Number} [chunkRetryDelay=1000]
* @namespace options
* @for Uploader
* @description 开启重试后,设置重试延时时间, 单位毫秒。默认1000毫秒,即1秒.
*/
chunkRetryDelay: 1000,
/**
* @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) {
file.setStatus( Status.QUEUED );
$.each( me.pool, function( _, v ) {
// 之前暂停过。
if (v.file !== file) {
return;
}
v.transport && v.transport.send();
file.setStatus( Status.PROGRESS );
});
} else if (file.getStatus() !== Status.PROGRESS) {
file.setStatus( Status.QUEUED );
}
} else {
$.each( me.request( 'get-files', [ Status.INITED ] ), function() {
this.setStatus( Status.QUEUED );
});
}
if ( me.runing ) {
me.owner.trigger('startUpload', file);// 开始上传或暂停恢复的,trigger event
return Base.nextTick( me.__tick );
}
me.runing = true;
var files = [];
// 如果有暂停的,则续传
file || $.each( me.pool, function( _, v ) {
var file = v.file;
if ( file.getStatus() === Status.INTERRUPT ) {
me._trigged = false;
files.push(file);
if (v.waiting) {
return;
}
// 文件 prepare 完后,如果暂停了,这个时候只会把文件插入 pool, 而不会创建 tranport,
v.transport ? v.transport.send() : me._doSend(v);
}
});
$.each(files, function() {
this.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) {
v.transport && v.transport.abort();
if (interrupt) {
me._putback(v);
me._popBlock(v);
}
}
});
me.owner.trigger('stopUpload', file);// 暂停,trigger event
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 );
},
/**
* 判断`Uploader`是否正在上传中。
* @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.remaning++;
block.file.remaning++;
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, 每个分片发送之前可能要做些异步的事情。
block.waiting = promise = me.request( 'before-send', block, function() {
delete block.waiting;
// 有可能文件已经上传出错了,所以不需要再传输了。
if ( file.getStatus() === Status.PROGRESS ) {
me._doSend( block );
} else if (block.file.getStatus() !== Status.INTERRUPT) {
me._popBlock(block);
}
Base.nextTick(me.__tick);
});
// 如果为fail了,则跳过此分片。
promise.fail(function() {
delete block.waiting;
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 = $.extend({}, me.options, block.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();
ret._headers = tr.getResponseHeaders();
block.response = ret;
fn = function( value ) {
reject = value;
};
// 服务端响应了,不代表成功了,询问是否响应正确。
if ( !owner.trigger( 'uploadAccept', block, ret, fn ) ) {
reject = reject || 'server';
}
return reject;
};
// 尝试重试,然后广播文件上传出错。
tr.on( 'error', function( type, flag ) {
// 在 runtime/html5/transport.js 上为 type 加上了状态码,形式:type|status|text(如:http-403-Forbidden)
// 这里把状态码解释出来,并还原后面代码所依赖的 type 变量
var typeArr = type.split( '|' ), status, statusText;
type = typeArr[0];
status = parseFloat( typeArr[1] ),
statusText = typeArr[2];
block.retried = block.retried || 0;
// 自动重试
if ( block.chunks > 1 && ~'http,abort,server'.indexOf( type.replace( /-.*/, '' ) ) &&
block.retried < opts.chunkRetry ) {
block.retried++;
me.retryTimer = setTimeout(function() {
tr.send();
}, opts.chunkRetryDelay || 1000);
} else {
// http status 500 ~ 600
if ( !flag && type === 'server' ) {
type = requestAccept( type );
}
file.setStatus( Status.ERROR, type );
owner.trigger( 'uploadError', file, type, status, statusText );
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 );
},
destroy: function() {
clearTimeout(this.retryTimer);
}
});
});
/**
* @fileOverview 日志组件,主要用来收集错误信息,可以帮助 webuploader 更好的定位问题和发展。
*
* 如果您不想要启用此功能,请在打包的时候去掉 log 模块。
*
* 或者可以在初始化的时候通过 options.disableWidgets 属性禁用。
*
* 如:
* WebUploader.create({
* ...
*
* disableWidgets: 'log',
*
* ...
* })
*/
define('widgets/log',[
'base',
'uploader',
'widgets/widget'
], function( Base, Uploader ) {
var $ = Base.$,
logUrl = ' http://static.tieba.baidu.com/tb/pms/img/st.gif??',
product = (location.hostname || location.host || 'protected').toLowerCase(),
// 只针对 baidu 内部产品用户做统计功能。
enable = product && /baidu/i.exec(product),
base;
if (!enable) {
return;
}
base = {
dv: 3,
master: 'webuploader',
online: /test/.exec(product) ? 0 : 1,
module: '',
product: product,
type: 0
};
function send(data) {
var obj = $.extend({}, base, data),
url = logUrl.replace(/^(.*)\?/, '$1' + $.param( obj )),
image = new Image();
image.src = url;
}
return Uploader.register({
name: 'log',
init: function() {
var owner = this.owner,
count = 0,
size = 0;
owner
.on('error', function(code) {
send({
type: 2,
c_error_code: code
});
})
.on('uploadError', function(file, reason) {
send({
type: 2,
c_error_code: 'UPLOAD_ERROR',
c_reason: '' + reason
});
})
.on('uploadComplete', function(file) {
count++;
size += file.size;
}).
on('uploadFinished', function() {
send({
c_count: count,
c_size: size
});
count = size = 0;
});
send({
c_usage: 1
});
}
});
});
/**
* @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 Html5Runtime
*/
define('runtime/html5/runtime',[
'base',
'runtime/runtime',
'runtime/compbase'
], function( Base, Runtime, CompBase ) {
var type = 'html5',
components = {};
function Html5Runtime() {
var pool = {},
me = this,
destroy = this.destroy;
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;
if ( components[ comp ] ) {
instance = pool[ uid ] = pool[ uid ] ||
new components[ comp ]( client, me );
if ( instance[ fn ] ) {
return instance[ fn ].apply( instance, args );
}
}
};
me.destroy = function() {
// @todo 删除池子中的所有实例
return destroy && destroy.apply( this, arguments );
};
}
Base.inherits( Runtime, {
constructor: Html5Runtime,
// 不需要连接其他程序,直接执行callback
init: function() {
var me = this;
setTimeout(function() {
me.trigger('ready');
}, 1 );
}
});
// 注册Components
Html5Runtime.register = function( name, component ) {
var klass = components[ name ] = Base.inherits( CompBase, component );
return klass;
};
// 注册html5运行时。
// 只有在支持的前提下注册。
if ( window.Blob && window.FileReader && window.DataView ) {
Runtime.addRuntime( type, Html5Runtime );
}
return Html5Runtime;
});
/**
* @fileOverview Blob Html实现
*/
define('runtime/html5/blob',[
'runtime/html5/runtime',
'lib/blob'
], function( Html5Runtime, Blob ) {
return Html5Runtime.register( 'Blob', {
slice: function( start, end ) {
var blob = this.owner.source,
slice = blob.slice || blob.webkitSlice || blob.mozSlice;
blob = slice.call( blob, start, end );
return new Blob( this.getRuid(), blob );
}
});
});
/**
* @fileOverview FilePicker
*/
define('runtime/html5/filepicker',[
'base',
'runtime/html5/runtime'
], function( Base, Html5Runtime ) {
var $ = Base.$;
return Html5Runtime.register( 'FilePicker', {
init: function() {
var container = this.getRuntime().getContainer(),
me = this,
owner = me.owner,
opts = me.options,
label = this.label = $( document.createElement('label') ),
input = this.input = $( document.createElement('input') ),
arr, i, len, mouseHandler, changeHandler;
input.attr( 'type', 'file' );
input.attr( 'capture', 'camera');
input.attr( 'name', opts.name );
input.addClass('webuploader-element-invisible');
label.on( 'click', function(e) {
input.trigger('click');
e.stopPropagation();
owner.trigger('dialogopen');
});
label.css({
opacity: 0,
width: '100%',
height: '100%',
display: 'block',
cursor: 'pointer',
background: '#ffffff'
});
if ( opts.multiple ) {
input.attr( 'multiple', 'multiple' );
}
// @todo Firefox不支持单独指定后缀
if ( opts.accept && opts.accept.length > 0 ) {
arr = [];
for ( i = 0, len = opts.accept.length; i < len; i++ ) {
arr.push( opts.accept[ i ].mimeTypes );
}
input.attr( 'accept', arr.join(',') );
}
container.append( input );
container.append( label );
mouseHandler = function( e ) {
owner.trigger( e.type );
};
changeHandler = function( e ) {
var clone;
// 解决chrome 56 第二次打开文件选择器,然后点击取消,依然会触发change事件的问题
if (e.target.files.length === 0){
return false;
}
// 第一次上传图片后,第二次再点击弹出文件选择器窗,等待
me.files = e.target.files;
// reset input
clone = this.cloneNode( true );
clone.value = null;
this.parentNode.replaceChild( clone, this );
input.off();
input = $( clone ).on( 'change', changeHandler )
.on( 'mouseenter mouseleave', mouseHandler );
owner.trigger('change');
}
input.on( 'change', changeHandler);
label.on( 'mouseenter mouseleave', mouseHandler );
},
getFiles: function() {
return this.files;
},
destroy: function() {
this.input.off();
this.label.off();
}
});
});
/**
* Terms:
*
* Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
* @fileOverview Image控件
*/
define('runtime/html5/util',[
'base'
], function( Base ) {
var urlAPI = window.createObjectURL && window ||
window.URL && URL.revokeObjectURL && URL ||
window.webkitURL,
createObjectURL = Base.noop,
revokeObjectURL = createObjectURL;
if ( urlAPI ) {
// 更安全的方式调用,比如android里面就能把context改成其他的对象。
createObjectURL = function() {
return urlAPI.createObjectURL.apply( urlAPI, arguments );
};
revokeObjectURL = function() {
return urlAPI.revokeObjectURL.apply( urlAPI, arguments );
};
}
return {
createObjectURL: createObjectURL,
revokeObjectURL: revokeObjectURL,
dataURL2Blob: function( dataURI ) {
var byteStr, intArray, ab, i, mimetype, parts;
parts = dataURI.split(',');
if ( ~parts[ 0 ].indexOf('base64') ) {
byteStr = atob( parts[ 1 ] );
} else {
byteStr = decodeURIComponent( parts[ 1 ] );
}
ab = new ArrayBuffer( byteStr.length );
intArray = new Uint8Array( ab );
for ( i = 0; i < byteStr.length; i++ ) {
intArray[ i ] = byteStr.charCodeAt( i );
}
mimetype = parts[ 0 ].split(':')[ 1 ].split(';')[ 0 ];
return this.arrayBufferToBlob( ab, mimetype );
},
dataURL2ArrayBuffer: function( dataURI ) {
var byteStr, intArray, i, parts;
parts = dataURI.split(',');
if ( ~parts[ 0 ].indexOf('base64') ) {
byteStr = atob( parts[ 1 ] );
} else {
byteStr = decodeURIComponent( parts[ 1 ] );
}
intArray = new Uint8Array( byteStr.length );
for ( i = 0; i < byteStr.length; i++ ) {
intArray[ i ] = byteStr.charCodeAt( i );
}
return intArray.buffer;
},
arrayBufferToBlob: function( buffer, type ) {
var builder = window.BlobBuilder || window.WebKitBlobBuilder,
bb;
// android不支持直接new Blob, 只能借助blobbuilder.
if ( builder ) {
bb = new builder();
bb.append( buffer );
return bb.getBlob( type );
}
return new Blob([ buffer ], type ? { type: type } : {} );
},
// 抽出来主要是为了解决android下面canvas.toDataUrl不支持jpeg.
// 你得到的结果是png.
canvasToDataUrl: function( canvas, type, quality ) {
return canvas.toDataURL( type, quality / 100 );
},
// imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
parseMeta: function( blob, callback ) {
callback( false, {});
},
// imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
updateImageHead: function( data ) {
return data;
}
};
});
/**
* Terms:
*
* Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
* @fileOverview Image控件
*/
define('runtime/html5/imagemeta',[
'runtime/html5/util'
], function( Util ) {
var api;
api = {
parsers: {
0xffe1: []
},
maxMetaDataSize: 262144,
parse: function( blob, cb ) {
var me = this,
fr = new FileReader();
fr.onload = function() {
cb( false, me._parse( this.result ) );
fr = fr.onload = fr.onerror = null;
};
fr.onerror = function( e ) {
cb( e.message );
fr = fr.onload = fr.onerror = null;
};
blob = blob.slice( 0, me.maxMetaDataSize );
fr.readAsArrayBuffer( blob.getSource() );
},
_parse: function( buffer, noParse ) {
if ( buffer.byteLength < 6 ) {
return;
}
var dataview = new DataView( buffer ),
offset = 2,
maxOffset = dataview.byteLength - 4,
headLength = offset,
ret = {},
markerBytes, markerLength, parsers, i;
if ( dataview.getUint16( 0 ) === 0xffd8 ) {
while ( offset < maxOffset ) {
markerBytes = dataview.getUint16( offset );
if ( markerBytes >= 0xffe0 && markerBytes <= 0xffef ||
markerBytes === 0xfffe ) {
markerLength = dataview.getUint16( offset + 2 ) + 2;
if ( offset + markerLength > dataview.byteLength ) {
break;
}
parsers = api.parsers[ markerBytes ];
if ( !noParse && parsers ) {
for ( i = 0; i < parsers.length; i += 1 ) {
parsers[ i ].call( api, dataview, offset,
markerLength, ret );
}
}
offset += markerLength;
headLength = offset;
} else {
break;
}
}
if ( headLength > 6 ) {
if ( buffer.slice ) {
ret.imageHead = buffer.slice( 2, headLength );
} else {
// Workaround for IE10, which does not yet
// support ArrayBuffer.slice:
ret.imageHead = new Uint8Array( buffer )
.subarray( 2, headLength );
}
}
}
return ret;
},
updateImageHead: function( buffer, head ) {
var data = this._parse( buffer, true ),
buf1, buf2, bodyoffset;
bodyoffset = 2;
if ( data.imageHead ) {
bodyoffset = 2 + data.imageHead.byteLength;
}
if ( buffer.slice ) {
buf2 = buffer.slice( bodyoffset );
} else {
buf2 = new Uint8Array( buffer ).subarray( bodyoffset );
}
buf1 = new Uint8Array( head.byteLength + 2 + buf2.byteLength );
buf1[ 0 ] = 0xFF;
buf1[ 1 ] = 0xD8;
buf1.set( new Uint8Array( head ), 2 );
buf1.set( new Uint8Array( buf2 ), head.byteLength + 2 );
return buf1.buffer;
}
};
Util.parseMeta = function() {
return api.parse.apply( api, arguments );
};
Util.updateImageHead = function() {
return api.updateImageHead.apply( api, arguments );
};
return api;
});
/**
* 代码来自于:https://github.com/blueimp/JavaScript-Load-Image
* 暂时项目中只用了orientation.
*
* 去除了 Exif Sub IFD Pointer, GPS Info IFD Pointer, Exif Thumbnail.
* @fileOverview EXIF解析
*/
// Sample
// ====================================
// Make : Apple
// Model : iPhone 4S
// Orientation : 1
// XResolution : 72 [72/1]
// YResolution : 72 [72/1]
// ResolutionUnit : 2
// Software : QuickTime 7.7.1
// DateTime : 2013:09:01 22:53:55
// ExifIFDPointer : 190
// ExposureTime : 0.058823529411764705 [1/17]
// FNumber : 2.4 [12/5]
// ExposureProgram : Normal program
// ISOSpeedRatings : 800
// ExifVersion : 0220
// DateTimeOriginal : 2013:09:01 22:52:51
// DateTimeDigitized : 2013:09:01 22:52:51
// ComponentsConfiguration : YCbCr
// ShutterSpeedValue : 4.058893515764426
// ApertureValue : 2.5260688216892597 [4845/1918]
// BrightnessValue : -0.3126686601998395
// MeteringMode : Pattern
// Flash : Flash did not fire, compulsory flash mode
// FocalLength : 4.28 [107/25]
// SubjectArea : [4 values]
// FlashpixVersion : 0100
// ColorSpace : 1
// PixelXDimension : 2448
// PixelYDimension : 3264
// SensingMethod : One-chip color area sensor
// ExposureMode : 0
// WhiteBalance : Auto white balance
// FocalLengthIn35mmFilm : 35
// SceneCaptureType : Standard
define('runtime/html5/imagemeta/exif',[
'base',
'runtime/html5/imagemeta'
], function( Base, ImageMeta ) {
var EXIF = {};
EXIF.ExifMap = function() {
return this;
};
EXIF.ExifMap.prototype.map = {
'Orientation': 0x0112
};
EXIF.ExifMap.prototype.get = function( id ) {
return this[ id ] || this[ this.map[ id ] ];
};
EXIF.exifTagTypes = {
// byte, 8-bit unsigned int:
1: {
getValue: function( dataView, dataOffset ) {
return dataView.getUint8( dataOffset );
},
size: 1
},
// ascii, 8-bit byte:
2: {
getValue: function( dataView, dataOffset ) {
return String.fromCharCode( dataView.getUint8( dataOffset ) );
},
size: 1,
ascii: true
},
// short, 16 bit int:
3: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getUint16( dataOffset, littleEndian );
},
size: 2
},
// long, 32 bit int:
4: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getUint32( dataOffset, littleEndian );
},
size: 4
},
// rational = two long values,
// first is numerator, second is denominator:
5: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getUint32( dataOffset, littleEndian ) /
dataView.getUint32( dataOffset + 4, littleEndian );
},
size: 8
},
// slong, 32 bit signed int:
9: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getInt32( dataOffset, littleEndian );
},
size: 4
},
// srational, two slongs, first is numerator, second is denominator:
10: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getInt32( dataOffset, littleEndian ) /
dataView.getInt32( dataOffset + 4, littleEndian );
},
size: 8
}
};
// undefined, 8-bit byte, value depending on field:
EXIF.exifTagTypes[ 7 ] = EXIF.exifTagTypes[ 1 ];
EXIF.getExifValue = function( dataView, tiffOffset, offset, type, length,
littleEndian ) {
var tagType = EXIF.exifTagTypes[ type ],
tagSize, dataOffset, values, i, str, c;
if ( !tagType ) {
Base.log('Invalid Exif data: Invalid tag type.');
return;
}
tagSize = tagType.size * length;
// Determine if the value is contained in the dataOffset bytes,
// or if the value at the dataOffset is a pointer to the actual data:
dataOffset = tagSize > 4 ? tiffOffset + dataView.getUint32( offset + 8,
littleEndian ) : (offset + 8);
if ( dataOffset + tagSize > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid data offset.');
return;
}
if ( length === 1 ) {
return tagType.getValue( dataView, dataOffset, littleEndian );
}
values = [];
for ( i = 0; i < length; i += 1 ) {
values[ i ] = tagType.getValue( dataView,
dataOffset + i * tagType.size, littleEndian );
}
if ( tagType.ascii ) {
str = '';
// Concatenate the chars:
for ( i = 0; i < values.length; i += 1 ) {
c = values[ i ];
// Ignore the terminating NULL byte(s):
if ( c === '\u0000' ) {
break;
}
str += c;
}
return str;
}
return values;
};
EXIF.parseExifTag = function( dataView, tiffOffset, offset, littleEndian,
data ) {
var tag = dataView.getUint16( offset, littleEndian );
data.exif[ tag ] = EXIF.getExifValue( dataView, tiffOffset, offset,
dataView.getUint16( offset + 2, littleEndian ), // tag type
dataView.getUint32( offset + 4, littleEndian ), // tag length
littleEndian );
};
EXIF.parseExifTags = function( dataView, tiffOffset, dirOffset,
littleEndian, data ) {
var tagsNumber, dirEndOffset, i;
if ( dirOffset + 6 > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid directory offset.');
return;
}
tagsNumber = dataView.getUint16( dirOffset, littleEndian );
dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
if ( dirEndOffset + 4 > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid directory size.');
return;
}
for ( i = 0; i < tagsNumber; i += 1 ) {
this.parseExifTag( dataView, tiffOffset,
dirOffset + 2 + 12 * i, // tag offset
littleEndian, data );
}
// Return the offset to the next directory:
return dataView.getUint32( dirEndOffset, littleEndian );
};
// EXIF.getExifThumbnail = function(dataView, offset, length) {
// var hexData,
// i,
// b;
// if (!length || offset + length > dataView.byteLength) {
// Base.log('Invalid Exif data: Invalid thumbnail data.');
// return;
// }
// hexData = [];
// for (i = 0; i < length; i += 1) {
// b = dataView.getUint8(offset + i);
// hexData.push((b < 16 ? '0' : '') + b.toString(16));
// }
// return 'data:image/jpeg,%' + hexData.join('%');
// };
EXIF.parseExifData = function( dataView, offset, length, data ) {
var tiffOffset = offset + 10,
littleEndian, dirOffset;
// Check for the ASCII code for "Exif" (0x45786966):
if ( dataView.getUint32( offset + 4 ) !== 0x45786966 ) {
// No Exif data, might be XMP data instead
return;
}
if ( tiffOffset + 8 > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid segment size.');
return;
}
// Check for the two null bytes:
if ( dataView.getUint16( offset + 8 ) !== 0x0000 ) {
Base.log('Invalid Exif data: Missing byte alignment offset.');
return;
}
// Check the byte alignment:
switch ( dataView.getUint16( tiffOffset ) ) {
case 0x4949:
littleEndian = true;
break;
case 0x4D4D:
littleEndian = false;
break;
default:
Base.log('Invalid Exif data: Invalid byte alignment marker.');
return;
}
// Check for the TIFF tag marker (0x002A):
if ( dataView.getUint16( tiffOffset + 2, littleEndian ) !== 0x002A ) {
Base.log('Invalid Exif data: Missing TIFF marker.');
return;
}
// Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
dirOffset = dataView.getUint32( tiffOffset + 4, littleEndian );
// Create the exif object to store the tags:
data.exif = new EXIF.ExifMap();
// Parse the tags of the main image directory and retrieve the
// offset to the next directory, usually the thumbnail directory:
dirOffset = EXIF.parseExifTags( dataView, tiffOffset,
tiffOffset + dirOffset, littleEndian, data );
// 尝试读取缩略图
// if ( dirOffset ) {
// thumbnailData = {exif: {}};
// dirOffset = EXIF.parseExifTags(
// dataView,
// tiffOffset,
// tiffOffset + dirOffset,
// littleEndian,
// thumbnailData
// );
// // Check for JPEG Thumbnail offset:
// if (thumbnailData.exif[0x0201]) {
// data.exif.Thumbnail = EXIF.getExifThumbnail(
// dataView,
// tiffOffset + thumbnailData.exif[0x0201],
// thumbnailData.exif[0x0202] // Thumbnail data length
// );
// }
// }
};
ImageMeta.parsers[ 0xffe1 ].push( EXIF.parseExifData );
return EXIF;
});
/**
* @fileOverview Image
*/
define('runtime/html5/image',[
'base',
'runtime/html5/runtime',
'runtime/html5/util'
], function( Base, Html5Runtime, Util ) {
var BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D';
return Html5Runtime.register( 'Image', {
// flag: 标记是否被修改过。
modified: false,
init: function() {
var me = this,
img = new Image();
img.onload = function() {
me._info = {
type: me.type,
width: this.width,
height: this.height
};
//debugger;
// 读取meta信息。
if ( !me._metas && 'image/jpeg' === me.type ) {
Util.parseMeta( me._blob, function( error, ret ) {
me._metas = ret;
me.owner.trigger('load');
});
} else {
me.owner.trigger('load');
}
};
img.onerror = function() {
me.owner.trigger('error');
};
me._img = img;
},
loadFromBlob: function( blob ) {
var me = this,
img = me._img;
me._blob = blob;
me.type = blob.type;
img.src = Util.createObjectURL( blob.getSource() );
me.owner.once( 'load', function() {
Util.revokeObjectURL( img.src );
});
},
resize: function( width, height ) {
var canvas = this._canvas ||
(this._canvas = document.createElement('canvas'));
this._resize( this._img, canvas, width, height );
this._blob = null; // 没用了,可以删掉了。
this.modified = true;
this.owner.trigger( 'complete', 'resize' );
},
crop: function( x, y, w, h, s ) {
var cvs = this._canvas ||
(this._canvas = document.createElement('canvas')),
opts = this.options,
img = this._img,
iw = img.naturalWidth,
ih = img.naturalHeight,
orientation = this.getOrientation();
s = s || 1;
// todo 解决 orientation 的问题。
// values that require 90 degree rotation
// if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) {
// switch ( orientation ) {
// case 6:
// tmp = x;
// x = y;
// y = iw * s - tmp - w;
// console.log(ih * s, tmp, w)
// break;
// }
// (w ^= h, h ^= w, w ^= h);
// }
cvs.width = w;
cvs.height = h;
opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation );
this._renderImageToCanvas( cvs, img, -x, -y, iw * s, ih * s );
this._blob = null; // 没用了,可以删掉了。
this.modified = true;
this.owner.trigger( 'complete', 'crop' );
},
getAsBlob: function( type ) {
var blob = this._blob,
opts = this.options,
canvas;
type = type || this.type;
// blob需要重新生成。
if ( this.modified || this.type !== type ) {
canvas = this._canvas;
if ( type === 'image/jpeg' ) {
blob = Util.canvasToDataUrl( canvas, type, opts.quality );
if ( opts.preserveHeaders && this._metas &&
this._metas.imageHead ) {
blob = Util.dataURL2ArrayBuffer( blob );
blob = Util.updateImageHead( blob,
this._metas.imageHead );
blob = Util.arrayBufferToBlob( blob, type );
return blob;
}
} else {
blob = Util.canvasToDataUrl( canvas, type );
}
blob = Util.dataURL2Blob( blob );
}
return blob;
},
getAsDataUrl: function( type ) {
var opts = this.options;
type = type || this.type;
if ( type === 'image/jpeg' ) {
return Util.canvasToDataUrl( this._canvas, type, opts.quality );
} else {
return this._canvas.toDataURL( type );
}
},
getOrientation: function() {
return this._metas && this._metas.exif &&
this._metas.exif.get('Orientation') || 1;
},
info: function( val ) {
// setter
if ( val ) {
this._info = val;
return this;
}
// getter
return this._info;
},
meta: function( val ) {
// setter
if ( val ) {
this._metas = val;
return this;
}
// getter
return this._metas;
},
destroy: function() {
var canvas = this._canvas;
this._img.onload = null;
if ( canvas ) {
canvas.getContext('2d')
.clearRect( 0, 0, canvas.width, canvas.height );
canvas.width = canvas.height = 0;
this._canvas = null;
}
// 释放内存。非常重要,否则释放不了image的内存。
this._img.src = BLANK;
this._img = this._blob = null;
},
_resize: function( img, cvs, width, height ) {
var opts = this.options,
naturalWidth = img.width,
naturalHeight = img.height,
orientation = this.getOrientation(),
scale, w, h, x, y;
// values that require 90 degree rotation
if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) {
// 交换width, height的值。
width ^= height;
height ^= width;
width ^= height;
}
scale = Math[ opts.crop ? 'max' : 'min' ]( width / naturalWidth,
height / naturalHeight );
// 不允许放大。
opts.allowMagnify || (scale = Math.min( 1, scale ));
w = naturalWidth * scale;
h = naturalHeight * scale;
if ( opts.crop ) {
cvs.width = width;
cvs.height = height;
} else {
cvs.width = w;
cvs.height = h;
}
x = (cvs.width - w) / 2;
y = (cvs.height - h) / 2;
opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation );
this._renderImageToCanvas( cvs, img, x, y, w, h );
},
_rotate2Orientaion: function( canvas, orientation ) {
var width = canvas.width,
height = canvas.height,
ctx = canvas.getContext('2d');
switch ( orientation ) {
case 5:
case 6:
case 7:
case 8:
canvas.width = height;
canvas.height = width;
break;
}
switch ( orientation ) {
case 2: // horizontal flip
ctx.translate( width, 0 );
ctx.scale( -1, 1 );
break;
case 3: // 180 rotate left
ctx.translate( width, height );
ctx.rotate( Math.PI );
break;
case 4: // vertical flip
ctx.translate( 0, height );
ctx.scale( 1, -1 );
break;
case 5: // vertical flip + 90 rotate right
ctx.rotate( 0.5 * Math.PI );
ctx.scale( 1, -1 );
break;
case 6: // 90 rotate right
ctx.rotate( 0.5 * Math.PI );
ctx.translate( 0, -height );
break;
case 7: // horizontal flip + 90 rotate right
ctx.rotate( 0.5 * Math.PI );
ctx.translate( width, -height );
ctx.scale( -1, 1 );
break;
case 8: // 90 rotate left
ctx.rotate( -0.5 * Math.PI );
ctx.translate( -width, 0 );
break;
}
},
// https://github.com/stomita/ios-imagefile-megapixel/
// blob/master/src/megapix-image.js
_renderImageToCanvas: (function() {
// 如果不是ios, 不需要这么复杂!
if ( !Base.os.ios ) {
return function( canvas ) {
var args = Base.slice( arguments, 1 ),
ctx = canvas.getContext('2d');
ctx.drawImage.apply( ctx, args );
};
}
/**
* Detecting vertical squash in loaded image.
* Fixes a bug which squash image vertically while drawing into
* canvas for some images.
*/
function detectVerticalSquash( img, iw, ih ) {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
sy = 0,
ey = ih,
py = ih,
data, alpha, ratio;
canvas.width = 1;
canvas.height = ih;
ctx.drawImage( img, 0, 0 );
data = ctx.getImageData( 0, 0, 1, ih ).data;
// search image edge pixel position in case
// it is squashed vertically.
while ( py > sy ) {
alpha = data[ (py - 1) * 4 + 3 ];
if ( alpha === 0 ) {
ey = py;
} else {
sy = py;
}
py = (ey + sy) >> 1;
}
ratio = (py / ih);
return (ratio === 0) ? 1 : ratio;
}
// fix ie7 bug
// http://stackoverflow.com/questions/11929099/
// html5-canvas-drawimage-ratio-bug-ios
if ( Base.os.ios >= 7 ) {
return function( canvas, img, x, y, w, h ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
vertSquashRatio = detectVerticalSquash( img, iw, ih );
return canvas.getContext('2d').drawImage( img, 0, 0,
iw * vertSquashRatio, ih * vertSquashRatio,
x, y, w, h );
};
}
/**
* Detect subsampling in loaded image.
* In iOS, larger images than 2M pixels may be
* subsampled in rendering.
*/
function detectSubsampling( img ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
canvas, ctx;
// subsampling may happen overmegapixel image
if ( iw * ih > 1024 * 1024 ) {
canvas = document.createElement('canvas');
canvas.width = canvas.height = 1;
ctx = canvas.getContext('2d');
ctx.drawImage( img, -iw + 1, 0 );
// subsampled image becomes half smaller in rendering size.
// check alpha channel value to confirm image is covering
// edge pixel or not. if alpha value is 0
// image is not covering, hence subsampled.
return ctx.getImageData( 0, 0, 1, 1 ).data[ 3 ] === 0;
} else {
return false;
}
}
return function( canvas, img, x, y, width, height ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
ctx = canvas.getContext('2d'),
subsampled = detectSubsampling( img ),
doSquash = this.type === 'image/jpeg',
d = 1024,
sy = 0,
dy = 0,
tmpCanvas, tmpCtx, vertSquashRatio, dw, dh, sx, dx;
if ( subsampled ) {
iw /= 2;
ih /= 2;
}
ctx.save();
tmpCanvas = document.createElement('canvas');
tmpCanvas.width = tmpCanvas.height = d;
tmpCtx = tmpCanvas.getContext('2d');
vertSquashRatio = doSquash ?
detectVerticalSquash( img, iw, ih ) : 1;
dw = Math.ceil( d * width / iw );
dh = Math.ceil( d * height / ih / vertSquashRatio );
while ( sy < ih ) {
sx = 0;
dx = 0;
while ( sx < iw ) {
tmpCtx.clearRect( 0, 0, d, d );
tmpCtx.drawImage( img, -sx, -sy );
ctx.drawImage( tmpCanvas, 0, 0, d, d,
x + dx, y + dy, dw, dh );
sx += d;
dx += dw;
}
sy += d;
dy += dh;
}
ctx.restore();
tmpCanvas = tmpCtx = null;
};
})()
});
});
/**
* 这个方式性能不行,但是可以解决android里面的toDataUrl的bug
* android里面toDataUrl('image/jpege')得到的结果却是png.
*
* 所以这里没辙,只能借助这个工具
* @fileOverview jpeg encoder
*/
define('runtime/html5/jpegencoder',[], function( require, exports, module ) {
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009
Basic GUI blocking jpeg encoder
*/
function JPEGEncoder(quality) {
var self = this;
var fround = Math.round;
var ffloor = Math.floor;
var YTable = new Array(64);
var UVTable = new Array(64);
var fdtbl_Y = new Array(64);
var fdtbl_UV = new Array(64);
var YDC_HT;
var UVDC_HT;
var YAC_HT;
var UVAC_HT;
var bitcode = new Array(65535);
var category = new Array(65535);
var outputfDCTQuant = new Array(64);
var DU = new Array(64);
var byteout = [];
var bytenew = 0;
var bytepos = 7;
var YDU = new Array(64);
var UDU = new Array(64);
var VDU = new Array(64);
var clt = new Array(256);
var RGB_YUV_TABLE = new Array(2048);
var currentQuality;
var ZigZag = [
0, 1, 5, 6,14,15,27,28,
2, 4, 7,13,16,26,29,42,
3, 8,12,17,25,30,41,43,
9,11,18,24,31,40,44,53,
10,19,23,32,39,45,52,54,
20,22,33,38,46,51,55,60,
21,34,37,47,50,56,59,61,
35,36,48,49,57,58,62,63
];
var std_dc_luminance_nrcodes = [0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0];
var std_dc_luminance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
var std_ac_luminance_nrcodes = [0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d];
var std_ac_luminance_values = [
0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,
0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,
0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,
0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,
0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,
0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,
0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,
0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,
0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,
0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,
0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,
0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,
0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,
0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,
0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,
0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,
0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,
0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,
0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
0xf9,0xfa
];
var std_dc_chrominance_nrcodes = [0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0];
var std_dc_chrominance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
var std_ac_chrominance_nrcodes = [0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77];
var std_ac_chrominance_values = [
0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,
0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,
0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,
0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,
0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,
0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,
0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,
0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,
0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,
0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,
0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,
0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,
0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,
0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,
0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,
0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,
0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,
0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,
0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
0xf9,0xfa
];
function initQuantTables(sf){
var YQT = [
16, 11, 10, 16, 24, 40, 51, 61,
12, 12, 14, 19, 26, 58, 60, 55,
14, 13, 16, 24, 40, 57, 69, 56,
14, 17, 22, 29, 51, 87, 80, 62,
18, 22, 37, 56, 68,109,103, 77,
24, 35, 55, 64, 81,104,113, 92,
49, 64, 78, 87,103,121,120,101,
72, 92, 95, 98,112,100,103, 99
];
for (var i = 0; i < 64; i++) {
var t = ffloor((YQT[i]*sf+50)/100);
if (t < 1) {
t = 1;
} else if (t > 255) {
t = 255;
}
YTable[ZigZag[i]] = t;
}
var UVQT = [
17, 18, 24, 47, 99, 99, 99, 99,
18, 21, 26, 66, 99, 99, 99, 99,
24, 26, 56, 99, 99, 99, 99, 99,
47, 66, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99
];
for (var j = 0; j < 64; j++) {
var u = ffloor((UVQT[j]*sf+50)/100);
if (u < 1) {
u = 1;
} else if (u > 255) {
u = 255;
}
UVTable[ZigZag[j]] = u;
}
var aasf = [
1.0, 1.387039845, 1.306562965, 1.175875602,
1.0, 0.785694958, 0.541196100, 0.275899379
];
var k = 0;
for (var row = 0; row < 8; row++)
{
for (var col = 0; col < 8; col++)
{
fdtbl_Y[k] = (1.0 / (YTable [ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
fdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
k++;
}
}
}
function computeHuffmanTbl(nrcodes, std_table){
var codevalue = 0;
var pos_in_table = 0;
var HT = new Array();
for (var k = 1; k <= 16; k++) {
for (var j = 1; j <= nrcodes[k]; j++) {
HT[std_table[pos_in_table]] = [];
HT[std_table[pos_in_table]][0] = codevalue;
HT[std_table[pos_in_table]][1] = k;
pos_in_table++;
codevalue++;
}
codevalue*=2;
}
return HT;
}
function initHuffmanTbl()
{
YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values);
UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values);
YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values);
UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values);
}
function initCategoryNumber()
{
var nrlower = 1;
var nrupper = 2;
for (var cat = 1; cat <= 15; cat++) {
//Positive numbers
for (var nr = nrlower; nr>0] = 38470 * i;
RGB_YUV_TABLE[(i+ 512)>>0] = 7471 * i + 0x8000;
RGB_YUV_TABLE[(i+ 768)>>0] = -11059 * i;
RGB_YUV_TABLE[(i+1024)>>0] = -21709 * i;
RGB_YUV_TABLE[(i+1280)>>0] = 32768 * i + 0x807FFF;
RGB_YUV_TABLE[(i+1536)>>0] = -27439 * i;
RGB_YUV_TABLE[(i+1792)>>0] = - 5329 * i;
}
}
// IO functions
function writeBits(bs)
{
var value = bs[0];
var posval = bs[1]-1;
while ( posval >= 0 ) {
if (value & (1 << posval) ) {
bytenew |= (1 << bytepos);
}
posval--;
bytepos--;
if (bytepos < 0) {
if (bytenew == 0xFF) {
writeByte(0xFF);
writeByte(0);
}
else {
writeByte(bytenew);
}
bytepos=7;
bytenew=0;
}
}
}
function writeByte(value)
{
byteout.push(clt[value]); // write char directly instead of converting later
}
function writeWord(value)
{
writeByte((value>>8)&0xFF);
writeByte((value )&0xFF);
}
// DCT & quantization core
function fDCTQuant(data, fdtbl)
{
var d0, d1, d2, d3, d4, d5, d6, d7;
/* Pass 1: process rows. */
var dataOff=0;
var i;
var I8 = 8;
var I64 = 64;
for (i=0; i 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0);
//outputfDCTQuant[i] = fround(fDCTQuant);
}
return outputfDCTQuant;
}
function writeAPP0()
{
writeWord(0xFFE0); // marker
writeWord(16); // length
writeByte(0x4A); // J
writeByte(0x46); // F
writeByte(0x49); // I
writeByte(0x46); // F
writeByte(0); // = "JFIF",'\0'
writeByte(1); // versionhi
writeByte(1); // versionlo
writeByte(0); // xyunits
writeWord(1); // xdensity
writeWord(1); // ydensity
writeByte(0); // thumbnwidth
writeByte(0); // thumbnheight
}
function writeSOF0(width, height)
{
writeWord(0xFFC0); // marker
writeWord(17); // length, truecolor YUV JPG
writeByte(8); // precision
writeWord(height);
writeWord(width);
writeByte(3); // nrofcomponents
writeByte(1); // IdY
writeByte(0x11); // HVY
writeByte(0); // QTY
writeByte(2); // IdU
writeByte(0x11); // HVU
writeByte(1); // QTU
writeByte(3); // IdV
writeByte(0x11); // HVV
writeByte(1); // QTV
}
function writeDQT()
{
writeWord(0xFFDB); // marker
writeWord(132); // length
writeByte(0);
for (var i=0; i<64; i++) {
writeByte(YTable[i]);
}
writeByte(1);
for (var j=0; j<64; j++) {
writeByte(UVTable[j]);
}
}
function writeDHT()
{
writeWord(0xFFC4); // marker
writeWord(0x01A2); // length
writeByte(0); // HTYDCinfo
for (var i=0; i<16; i++) {
writeByte(std_dc_luminance_nrcodes[i+1]);
}
for (var j=0; j<=11; j++) {
writeByte(std_dc_luminance_values[j]);
}
writeByte(0x10); // HTYACinfo
for (var k=0; k<16; k++) {
writeByte(std_ac_luminance_nrcodes[k+1]);
}
for (var l=0; l<=161; l++) {
writeByte(std_ac_luminance_values[l]);
}
writeByte(1); // HTUDCinfo
for (var m=0; m<16; m++) {
writeByte(std_dc_chrominance_nrcodes[m+1]);
}
for (var n=0; n<=11; n++) {
writeByte(std_dc_chrominance_values[n]);
}
writeByte(0x11); // HTUACinfo
for (var o=0; o<16; o++) {
writeByte(std_ac_chrominance_nrcodes[o+1]);
}
for (var p=0; p<=161; p++) {
writeByte(std_ac_chrominance_values[p]);
}
}
function writeSOS()
{
writeWord(0xFFDA); // marker
writeWord(12); // length
writeByte(3); // nrofcomponents
writeByte(1); // IdY
writeByte(0); // HTY
writeByte(2); // IdU
writeByte(0x11); // HTU
writeByte(3); // IdV
writeByte(0x11); // HTV
writeByte(0); // Ss
writeByte(0x3f); // Se
writeByte(0); // Bf
}
function processDU(CDU, fdtbl, DC, HTDC, HTAC){
var EOB = HTAC[0x00];
var M16zeroes = HTAC[0xF0];
var pos;
var I16 = 16;
var I63 = 63;
var I64 = 64;
var DU_DCT = fDCTQuant(CDU, fdtbl);
//ZigZag reorder
for (var j=0;j0)&&(DU[end0pos]==0); end0pos--) {};
//end0pos = first element in reverse order !=0
if ( end0pos == 0) {
writeBits(EOB);
return DC;
}
var i = 1;
var lng;
while ( i <= end0pos ) {
var startpos = i;
for (; (DU[i]==0) && (i<=end0pos); ++i) {}
var nrzeroes = i-startpos;
if ( nrzeroes >= I16 ) {
lng = nrzeroes>>4;
for (var nrmarker=1; nrmarker <= lng; ++nrmarker)
writeBits(M16zeroes);
nrzeroes = nrzeroes&0xF;
}
pos = 32767+DU[i];
writeBits(HTAC[(nrzeroes<<4)+category[pos]]);
writeBits(bitcode[pos]);
i++;
}
if ( end0pos != I63 ) {
writeBits(EOB);
}
return DC;
}
function initCharLookupTable(){
var sfcc = String.fromCharCode;
for(var i=0; i < 256; i++){ ///// ACHTUNG // 255
clt[i] = sfcc(i);
}
}
this.encode = function(image,quality) // image data object
{
// var time_start = new Date().getTime();
if(quality) setQuality(quality);
// Initialize bit writer
byteout = new Array();
bytenew=0;
bytepos=7;
// Add JPEG headers
writeWord(0xFFD8); // SOI
writeAPP0();
writeDQT();
writeSOF0(image.width,image.height);
writeDHT();
writeSOS();
// Encode 8x8 macroblocks
var DCY=0;
var DCU=0;
var DCV=0;
bytenew=0;
bytepos=7;
this.encode.displayName = "_encode_";
var imageData = image.data;
var width = image.width;
var height = image.height;
var quadWidth = width*4;
var tripleWidth = width*3;
var x, y = 0;
var r, g, b;
var start,p, col,row,pos;
while(y < height){
x = 0;
while(x < quadWidth){
start = quadWidth * y + x;
p = start;
col = -1;
row = 0;
for(pos=0; pos < 64; pos++){
row = pos >> 3;// /8
col = ( pos & 7 ) * 4; // %8
p = start + ( row * quadWidth ) + col;
if(y+row >= height){ // padding bottom
p-= (quadWidth*(y+1+row-height));
}
if(x+col >= quadWidth){ // padding right
p-= ((x+col) - quadWidth +4)
}
r = imageData[ p++ ];
g = imageData[ p++ ];
b = imageData[ p++ ];
/* // calculate YUV values dynamically
YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80
UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));
VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));
*/
// use lookup table (slightly faster)
YDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256)>>0] + RGB_YUV_TABLE[(b + 512)>>0]) >> 16)-128;
UDU[pos] = ((RGB_YUV_TABLE[(r + 768)>>0] + RGB_YUV_TABLE[(g + 1024)>>0] + RGB_YUV_TABLE[(b + 1280)>>0]) >> 16)-128;
VDU[pos] = ((RGB_YUV_TABLE[(r + 1280)>>0] + RGB_YUV_TABLE[(g + 1536)>>0] + RGB_YUV_TABLE[(b + 1792)>>0]) >> 16)-128;
}
DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
x+=32;
}
y+=8;
}
////////////////////////////////////////////////////////////////
// Do the bit alignment of the EOI marker
if ( bytepos >= 0 ) {
var fillbits = [];
fillbits[1] = bytepos+1;
fillbits[0] = (1<<(bytepos+1))-1;
writeBits(fillbits);
}
writeWord(0xFFD9); //EOI
var jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join(''));
byteout = [];
// benchmarking
// var duration = new Date().getTime() - time_start;
// console.log('Encoding time: '+ currentQuality + 'ms');
//
return jpegDataUri
}
function setQuality(quality){
if (quality <= 0) {
quality = 1;
}
if (quality > 100) {
quality = 100;
}
if(currentQuality == quality) return // don't recalc if unchanged
var sf = 0;
if (quality < 50) {
sf = Math.floor(5000 / quality);
} else {
sf = Math.floor(200 - quality*2);
}
initQuantTables(sf);
currentQuality = quality;
// console.log('Quality set to: '+quality +'%');
}
function init(){
// var time_start = new Date().getTime();
if(!quality) quality = 50;
// Create tables
initCharLookupTable()
initHuffmanTbl();
initCategoryNumber();
initRGBYUVTable();
setQuality(quality);
// var duration = new Date().getTime() - time_start;
// console.log('Initialization '+ duration + 'ms');
}
init();
};
JPEGEncoder.encode = function( data, quality ) {
var encoder = new JPEGEncoder( quality );
return encoder.encode( data );
}
return JPEGEncoder;
});
/**
* @fileOverview Fix android canvas.toDataUrl bug.
*/
define('runtime/html5/androidpatch',[
'runtime/html5/util',
'runtime/html5/jpegencoder',
'base'
], function( Util, encoder, Base ) {
var origin = Util.canvasToDataUrl,
supportJpeg;
Util.canvasToDataUrl = function( canvas, type, quality ) {
var ctx, w, h, fragement, parts;
// 非android手机直接跳过。
if ( !Base.os.android ) {
return origin.apply( null, arguments );
}
// 检测是否canvas支持jpeg导出,根据数据格式来判断。
// JPEG 前两位分别是:255, 216
if ( type === 'image/jpeg' && typeof supportJpeg === 'undefined' ) {
fragement = origin.apply( null, arguments );
parts = fragement.split(',');
if ( ~parts[ 0 ].indexOf('base64') ) {
fragement = atob( parts[ 1 ] );
} else {
fragement = decodeURIComponent( parts[ 1 ] );
}
fragement = fragement.substring( 0, 2 );
supportJpeg = fragement.charCodeAt( 0 ) === 255 &&
fragement.charCodeAt( 1 ) === 216;
}
// 只有在android环境下才修复
if ( type === 'image/jpeg' && !supportJpeg ) {
w = canvas.width;
h = canvas.height;
ctx = canvas.getContext('2d');
return encoder.encode( ctx.getImageData( 0, 0, w, h ), quality );
}
return origin.apply( null, arguments );
};
});
/**
* @fileOverview Transport
* @todo 支持chunked传输,优势:
* 可以将大文件分成小块,挨个传输,可以提高大文件成功率,当失败的时候,也只需要重传那小部分,
* 而不需要重头再传一次。另外断点续传也需要用chunked方式。
*/
define('runtime/html5/transport',[
'base',
'runtime/html5/runtime'
], function( Base, Html5Runtime ) {
var noop = Base.noop,
$ = Base.$;
return Html5Runtime.register( 'Transport', {
init: function() {
this._status = 0;
this._response = null;
},
send: function() {
var owner = this.owner,
opts = this.options,
xhr = this._initAjax(),
blob = owner._blob,
server = opts.server,
formData, binary, fr;
if ( opts.sendAsBinary ) {
server += opts.attachInfoToQuery !== false ? ((/\?/.test( server ) ? '&' : '?') +
$.param( owner._formData )) : '';
binary = blob.getSource();
} else {
formData = new FormData();
$.each( owner._formData, function( k, v ) {
formData.append( k, v );
});
formData.append( opts.fileVal, blob.getSource(),
opts.filename || owner._formData.name || '' );
}
if ( opts.withCredentials && 'withCredentials' in xhr ) {
xhr.open( opts.method, server, true );
xhr.withCredentials = true;
} else {
xhr.open( opts.method, server );
}
this._setRequestHeader( xhr, opts.headers );
if ( binary ) {
// 强制设置成 content-type 为文件流。
xhr.overrideMimeType &&
xhr.overrideMimeType('application/octet-stream');
// android直接发送blob会导致服务端接收到的是空文件。
// bug详情。
// https://code.google.com/p/android/issues/detail?id=39882
// 所以先用fileReader读取出来再通过arraybuffer的方式发送。
if ( Base.os.android ) {
fr = new FileReader();
fr.onload = function() {
xhr.send( this.result );
fr = fr.onload = null;
};
fr.readAsArrayBuffer( binary );
} else {
xhr.send( binary );
}
} else {
xhr.send( formData );
}
},
getResponse: function() {
return this._response;
},
getResponseAsJson: function() {
return this._parseJson( this._response );
},
getResponseHeaders: function() {
return this._headers;
},
getStatus: function() {
return this._status;
},
abort: function() {
var xhr = this._xhr;
if ( xhr ) {
xhr.upload.onprogress = noop;
xhr.onreadystatechange = noop;
xhr.abort();
this._xhr = xhr = null;
}
},
destroy: function() {
this.abort();
},
_parseHeader: function(raw) {
var ret = {};
raw && raw.replace(/^([^\:]+):(.*)$/mg, function(_, key, value) {
ret[key.trim()] = value.trim();
});
return ret;
},
_initAjax: function() {
var me = this,
xhr = new XMLHttpRequest(),
opts = this.options;
if ( opts.withCredentials && !('withCredentials' in xhr) &&
typeof XDomainRequest !== 'undefined' ) {
xhr = new XDomainRequest();
}
xhr.upload.onprogress = function( e ) {
var percentage = 0;
if ( e.lengthComputable ) {
percentage = e.loaded / e.total;
}
return me.trigger( 'progress', percentage );
};
xhr.onreadystatechange = function() {
if ( xhr.readyState !== 4 ) {
return;
}
xhr.upload.onprogress = noop;
xhr.onreadystatechange = noop;
me._xhr = null;
me._status = xhr.status;
var separator = '|', // 分隔符
// 拼接的状态,在 widgets/upload.js 会有代码用到这个分隔符
status = separator + xhr.status +
separator + xhr.statusText;
if ( xhr.status >= 200 && xhr.status < 300 ) {
me._response = xhr.responseText;
me._headers = me._parseHeader(xhr.getAllResponseHeaders());
return me.trigger('load');
} else if ( xhr.status >= 500 && xhr.status < 600 ) {
me._response = xhr.responseText;
me._headers = me._parseHeader(xhr.getAllResponseHeaders());
return me.trigger( 'error', 'server' + status );
}
return me.trigger( 'error', me._status ? 'http' + status : 'abort' );
};
me._xhr = xhr;
return xhr;
},
_setRequestHeader: function( xhr, headers ) {
$.each( headers, function( key, val ) {
xhr.setRequestHeader( key, val );
});
},
_parseJson: function( str ) {
var json;
try {
json = JSON.parse( str );
} catch ( ex ) {
json = {};
}
return json;
}
});
});
define('webuploader',[
'base',
'widgets/filepicker',
'widgets/image',
'widgets/queue',
'widgets/runtime',
'widgets/upload',
'widgets/log',
'runtime/html5/blob',
'runtime/html5/filepicker',
'runtime/html5/imagemeta/exif',
'runtime/html5/image',
'runtime/html5/androidpatch',
'runtime/html5/transport'
], function( Base ) {
return Base;
});
return require('webuploader');
});
================================================
FILE: dist/webuploader.fis.js
================================================
/*! WebUploader 0.1.8-alpha */
var jQuery = require('example:widget/ui/jquery/jquery.js');
module.exports = (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 ) );
};
return makeExport( jQuery );
})( window, function( window, define, require ) {
/**
* @fileOverview jQuery or Zepto
* @require "jquery"
* @require "zepto"
*/
define('dollar-third',[],function() {
var req = window.require;
var $ = window.__dollar ||
window.jQuery ||
window.Zepto ||
req('jquery') ||
req('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.8-alpha',
/**
* @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 错误信息
*/
define('lib/dnd',[
'base',
'mediator',
'runtime/client'
], function( Base, Mediator, RuntimeClent ) {
var $ = Base.$;
function DragAndDrop( opts ) {
opts = this.options = $.extend({}, DragAndDrop.options, opts );
opts.container = $( opts.container );
if ( !opts.container.length ) {
return;
}
RuntimeClent.call( this, 'DragAndDrop' );
}
DragAndDrop.options = {
accept: null,
disableGlobalDnd: false
};
Base.inherits( RuntimeClent, {
constructor: DragAndDrop,
init: function() {
var me = this;
me.connectRuntime( me.options, function() {
me.exec('init');
me.trigger('ready');
});
}
});
Mediator.installTo( DragAndDrop.prototype );
return DragAndDrop;
});
/**
* @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 DragAndDrop Widget。
*/
define('widgets/filednd',[
'base',
'uploader',
'lib/dnd',
'widgets/widget'
], function( Base, Uploader, Dnd ) {
var $ = Base.$;
Uploader.options.dnd = '';
/**
* @property {Selector} [dnd=undefined] 指定Drag And Drop拖拽的容器,如果不指定,则不启动。
* @namespace options
* @for Uploader
*/
/**
* @property {Selector} [disableGlobalDnd=false] 是否禁掉整个页面的拖拽功能,如果不禁用,图片拖进来的时候会默认被浏览器打开。
* @namespace options
* @for Uploader
*/
/**
* @event dndAccept
* @param {DataTransferItemList} items DataTransferItem
* @description 阻止此事件可以拒绝某些类型的文件拖入进来。目前只有 chrome 提供这样的 API,且只能通过 mime-type 验证。
* @for Uploader
*/
return Uploader.register({
name: 'dnd',
init: function( opts ) {
if ( !opts.dnd ||
this.request('predict-runtime-type') !== 'html5' ) {
return;
}
var me = this,
deferred = Base.Deferred(),
options = $.extend({}, {
disableGlobalDnd: opts.disableGlobalDnd,
container: opts.dnd,
accept: opts.accept
}),
dnd;
this.dnd = dnd = new Dnd( options );
dnd.once( 'ready', deferred.resolve );
dnd.on( 'drop', function( files ) {
me.request( 'add-file', [ files ]);
});
// 检测文件是否全部允许添加。
dnd.on( 'accept', function( items ) {
return me.owner.trigger( 'dndAccept', items );
});
dnd.init();
return deferred.promise();
},
destroy: function() {
this.dnd && this.dnd.destroy();
}
});
});
/**
* @fileOverview 错误信息
*/
define('lib/filepaste',[
'base',
'mediator',
'runtime/client'
], function( Base, Mediator, RuntimeClent ) {
var $ = Base.$;
function FilePaste( opts ) {
opts = this.options = $.extend({}, opts );
opts.container = $( opts.container || document.body );
RuntimeClent.call( this, 'FilePaste' );
}
Base.inherits( RuntimeClent, {
constructor: FilePaste,
init: function() {
var me = this;
me.connectRuntime( me.options, function() {
me.exec('init');
me.trigger('ready');
});
}
});
Mediator.installTo( FilePaste.prototype );
return FilePaste;
});
/**
* @fileOverview 组件基类。
*/
define('widgets/filepaste',[
'base',
'uploader',
'lib/filepaste',
'widgets/widget'
], function( Base, Uploader, FilePaste ) {
var $ = Base.$;
/**
* @property {Selector} [paste=undefined] 指定监听paste事件的容器,如果不指定,不启用此功能。此功能为通过粘贴来添加截屏的图片。建议设置为`document.body`.
* @namespace options
* @for Uploader
*/
return Uploader.register({
name: 'paste',
init: function( opts ) {
if ( !opts.paste ||
this.request('predict-runtime-type') !== 'html5' ) {
return;
}
var me = this,
deferred = Base.Deferred(),
options = $.extend({}, {
container: opts.paste,
accept: opts.accept
}),
paste;
this.paste = paste = new FilePaste( options );
paste.once( 'ready', deferred.resolve );
paste.on( 'paste', function( files ) {
me.owner.request( 'add-file', [ files ]);
});
paste.init();
return deferred.promise();
},
destroy: function() {
this.paste && this.paste.destroy();
}
});
});
/**
* @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 ||
file.lastModified && new Date(file.lastModified).toLocaleString() ||
(new Date()).toLocaleString();
Blob.apply( this, arguments );
}
return Base.inherits( Blob, File );
});
/**
* @fileOverview 错误信息
*/
define('lib/filepicker',[
'base',
'runtime/client',
'lib/file'
], function( Base, RuntimeClient, 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 );
RuntimeClient.call( this, 'FilePicker', true );
}
FilePicker.options = {
button: null,
container: null,
label: null,
innerHTML: null,
multiple: true,
accept: null,
name: 'file',
style: 'webuploader-pick' //pick element class attribute, default is "webuploader-pick"
};
Base.inherits( RuntimeClient, {
constructor: FilePicker,
init: function() {
var me = this,
opts = me.options,
button = opts.button,
style = opts.style;
if (style)
button.addClass('webuploader-pick');
me.on( 'all', function( type ) {
var files;
switch ( type ) {
case 'mouseenter':
if (style)
button.addClass('webuploader-pick-hover');
break;
case 'mouseleave':
if (style)
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(),
*/
width = button[0] && button[0].offsetWidth || button.outerWidth() || button.width(),
height = button[0] && button[0].offsetHeight || 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/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 {Array} [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.on('dialogopen', function() {
me.owner.trigger('dialogOpen', picker.button);
});
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.getAsDataUrl( opts.type ) );
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` 被移除的文件数。
* * `numOfInterrupt` 被中断的文件数。
* @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 ];
this._delFile(file);
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 );
});
}
},
_delFile : function(file){
for(var i = this._queue.length - 1 ; i >= 0 ; i-- ){
if(this._queue[i] == file){
this._queue.splice(i,1);
break;
}
}
},
_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 );
});
if ( files.length ) {
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();
},
getResponseHeaders: function() {
return this.exec('getResponseHeaders');
},
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 {Number} [chunkRetryDelay=1000]
* @namespace options
* @for Uploader
* @description 开启重试后,设置重试延时时间, 单位毫秒。默认1000毫秒,即1秒.
*/
chunkRetryDelay: 1000,
/**
* @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) {
file.setStatus( Status.QUEUED );
$.each( me.pool, function( _, v ) {
// 之前暂停过。
if (v.file !== file) {
return;
}
v.transport && v.transport.send();
file.setStatus( Status.PROGRESS );
});
} else if (file.getStatus() !== Status.PROGRESS) {
file.setStatus( Status.QUEUED );
}
} else {
$.each( me.request( 'get-files', [ Status.INITED ] ), function() {
this.setStatus( Status.QUEUED );
});
}
if ( me.runing ) {
me.owner.trigger('startUpload', file);// 开始上传或暂停恢复的,trigger event
return Base.nextTick( me.__tick );
}
me.runing = true;
var files = [];
// 如果有暂停的,则续传
file || $.each( me.pool, function( _, v ) {
var file = v.file;
if ( file.getStatus() === Status.INTERRUPT ) {
me._trigged = false;
files.push(file);
if (v.waiting) {
return;
}
// 文件 prepare 完后,如果暂停了,这个时候只会把文件插入 pool, 而不会创建 tranport,
v.transport ? v.transport.send() : me._doSend(v);
}
});
$.each(files, function() {
this.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) {
v.transport && v.transport.abort();
if (interrupt) {
me._putback(v);
me._popBlock(v);
}
}
});
me.owner.trigger('stopUpload', file);// 暂停,trigger event
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 );
},
/**
* 判断`Uploader`是否正在上传中。
* @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.remaning++;
block.file.remaning++;
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, 每个分片发送之前可能要做些异步的事情。
block.waiting = promise = me.request( 'before-send', block, function() {
delete block.waiting;
// 有可能文件已经上传出错了,所以不需要再传输了。
if ( file.getStatus() === Status.PROGRESS ) {
me._doSend( block );
} else if (block.file.getStatus() !== Status.INTERRUPT) {
me._popBlock(block);
}
Base.nextTick(me.__tick);
});
// 如果为fail了,则跳过此分片。
promise.fail(function() {
delete block.waiting;
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 = $.extend({}, me.options, block.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();
ret._headers = tr.getResponseHeaders();
block.response = ret;
fn = function( value ) {
reject = value;
};
// 服务端响应了,不代表成功了,询问是否响应正确。
if ( !owner.trigger( 'uploadAccept', block, ret, fn ) ) {
reject = reject || 'server';
}
return reject;
};
// 尝试重试,然后广播文件上传出错。
tr.on( 'error', function( type, flag ) {
// 在 runtime/html5/transport.js 上为 type 加上了状态码,形式:type|status|text(如:http-403-Forbidden)
// 这里把状态码解释出来,并还原后面代码所依赖的 type 变量
var typeArr = type.split( '|' ), status, statusText;
type = typeArr[0];
status = parseFloat( typeArr[1] ),
statusText = typeArr[2];
block.retried = block.retried || 0;
// 自动重试
if ( block.chunks > 1 && ~'http,abort,server'.indexOf( type.replace( /-.*/, '' ) ) &&
block.retried < opts.chunkRetry ) {
block.retried++;
me.retryTimer = setTimeout(function() {
tr.send();
}, opts.chunkRetryDelay || 1000);
} else {
// http status 500 ~ 600
if ( !flag && type === 'server' ) {
type = requestAccept( type );
}
file.setStatus( Status.ERROR, type );
owner.trigger( 'uploadError', file, type, status, statusText );
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 );
},
destroy: function() {
clearTimeout(this.retryTimer);
}
});
});
/**
* @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 ) {
// 增加beforeFileQueuedCheckfileNumLimit验证,主要为了再次加载时(已存在历史文件)验证数量是否超过设置项
if (!this.trigger('beforeFileQueuedCheckfileNumLimit', file,count)) {
return false;
}
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 Md5
*/
define('lib/md5',[
'runtime/client',
'mediator'
], function( RuntimeClient, Mediator ) {
function Md5() {
RuntimeClient.call( this, 'Md5' );
}
// 让 Md5 具备事件功能。
Mediator.installTo( Md5.prototype );
Md5.prototype.loadFromBlob = function( blob ) {
var me = this;
if ( me.getRuid() ) {
me.disconnectRuntime();
}
// 连接到blob归属的同一个runtime.
me.connectRuntime( blob.ruid, function() {
me.exec('init');
me.exec( 'loadFromBlob', blob );
});
};
Md5.prototype.getResult = function() {
return this.exec('getResult');
};
return Md5;
});
/**
* @fileOverview 图片操作, 负责预览图片和上传前压缩图片
*/
define('widgets/md5',[
'base',
'uploader',
'lib/md5',
'lib/blob',
'widgets/widget'
], function( Base, Uploader, Md5, Blob ) {
return Uploader.register({
name: 'md5',
/**
* 计算文件 md5 值,返回一个 promise 对象,可以监听 progress 进度。
*
*
* @method md5File
* @grammar md5File( file[, start[, end]] ) => promise
* @for Uploader
* @example
*
* uploader.on( 'fileQueued', function( file ) {
* var $li = ...;
*
* uploader.md5File( file )
*
* // 及时显示进度
* .progress(function(percentage) {
* console.log('Percentage:', percentage);
* })
*
* // 完成
* .then(function(val) {
* console.log('md5 result:', val);
* });
*
* });
*/
md5File: function( file, start, end ) {
var md5 = new Md5(),
deferred = Base.Deferred(),
blob = (file instanceof Blob) ? file :
this.request( 'get-file', file ).source;
md5.on( 'progress load', function( e ) {
e = e || {};
deferred.notify( e.total ? e.loaded / e.total : 1 );
});
md5.on( 'complete', function() {
deferred.resolve( md5.getResult() );
});
md5.on( 'error', function( reason ) {
deferred.reject( reason );
});
if ( arguments.length > 1 ) {
start = start || 0;
end = end || 0;
start < 0 && (start = blob.size + start);
end < 0 && (end = blob.size + end);
end = Math.min( end, blob.size );
blob = blob.slice( start, end );
}
md5.loadFromBlob( blob );
return deferred.promise();
}
});
});
/**
* @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 Html5Runtime
*/
define('runtime/html5/runtime',[
'base',
'runtime/runtime',
'runtime/compbase'
], function( Base, Runtime, CompBase ) {
var type = 'html5',
components = {};
function Html5Runtime() {
var pool = {},
me = this,
destroy = this.destroy;
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;
if ( components[ comp ] ) {
instance = pool[ uid ] = pool[ uid ] ||
new components[ comp ]( client, me );
if ( instance[ fn ] ) {
return instance[ fn ].apply( instance, args );
}
}
};
me.destroy = function() {
// @todo 删除池子中的所有实例
return destroy && destroy.apply( this, arguments );
};
}
Base.inherits( Runtime, {
constructor: Html5Runtime,
// 不需要连接其他程序,直接执行callback
init: function() {
var me = this;
setTimeout(function() {
me.trigger('ready');
}, 1 );
}
});
// 注册Components
Html5Runtime.register = function( name, component ) {
var klass = components[ name ] = Base.inherits( CompBase, component );
return klass;
};
// 注册html5运行时。
// 只有在支持的前提下注册。
if ( window.Blob && window.FileReader && window.DataView ) {
Runtime.addRuntime( type, Html5Runtime );
}
return Html5Runtime;
});
/**
* @fileOverview Blob Html实现
*/
define('runtime/html5/blob',[
'runtime/html5/runtime',
'lib/blob'
], function( Html5Runtime, Blob ) {
return Html5Runtime.register( 'Blob', {
slice: function( start, end ) {
var blob = this.owner.source,
slice = blob.slice || blob.webkitSlice || blob.mozSlice;
blob = slice.call( blob, start, end );
return new Blob( this.getRuid(), blob );
}
});
});
/**
* @fileOverview FilePaste
*/
define('runtime/html5/dnd',[
'base',
'runtime/html5/runtime',
'lib/file'
], function( Base, Html5Runtime, File ) {
var $ = Base.$,
prefix = 'webuploader-dnd-';
return Html5Runtime.register( 'DragAndDrop', {
init: function() {
var elem = this.elem = this.options.container;
this.dragEnterHandler = Base.bindFn( this._dragEnterHandler, this );
this.dragOverHandler = Base.bindFn( this._dragOverHandler, this );
this.dragLeaveHandler = Base.bindFn( this._dragLeaveHandler, this );
this.dropHandler = Base.bindFn( this._dropHandler, this );
this.dndOver = false;
elem.on( 'dragenter', this.dragEnterHandler );
elem.on( 'dragover', this.dragOverHandler );
elem.on( 'dragleave', this.dragLeaveHandler );
elem.on( 'drop', this.dropHandler );
if ( this.options.disableGlobalDnd ) {
$( document ).on( 'dragover', this.dragOverHandler );
$( document ).on( 'drop', this.dropHandler );
}
},
_dragEnterHandler: function( e ) {
var me = this,
denied = me._denied || false,
items;
e = e.originalEvent || e;
if ( !me.dndOver ) {
me.dndOver = true;
// 注意只有 chrome 支持。
items = e.dataTransfer.items;
if ( items && items.length ) {
me._denied = denied = !me.trigger( 'accept', items );
}
me.elem.addClass( prefix + 'over' );
me.elem[ denied ? 'addClass' :
'removeClass' ]( prefix + 'denied' );
}
e.dataTransfer.dropEffect = denied ? 'none' : 'copy';
return false;
},
_dragOverHandler: function( e ) {
// 只处理框内的。
var parentElem = this.elem.parent().get( 0 );
if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) {
return false;
}
clearTimeout( this._leaveTimer );
this._dragEnterHandler.call( this, e );
return false;
},
_dragLeaveHandler: function() {
var me = this,
handler;
handler = function() {
me.dndOver = false;
me.elem.removeClass( prefix + 'over ' + prefix + 'denied' );
};
clearTimeout( me._leaveTimer );
me._leaveTimer = setTimeout( handler, 100 );
return false;
},
_dropHandler: function( e ) {
var me = this,
ruid = me.getRuid(),
parentElem = me.elem.parent().get( 0 ),
dataTransfer, data;
// 只处理框内的。
if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) {
return false;
}
e = e.originalEvent || e;
dataTransfer = e.dataTransfer;
// 如果是页面内拖拽,还不能处理,不阻止事件。
// 此处 ie11 下会报参数错误,
try {
data = dataTransfer.getData('text/html');
} catch( err ) {
}
me.dndOver = false;
me.elem.removeClass( prefix + 'over' );
if ( !dataTransfer || data ) {
return;
}
me._getTansferFiles( dataTransfer, function( results ) {
me.trigger( 'drop', $.map( results, function( file ) {
return new File( ruid, file );
}) );
});
return false;
},
// 如果传入 callback 则去查看文件夹,否则只管当前文件夹。
_getTansferFiles: function( dataTransfer, callback ) {
var results = [],
promises = [],
items, files, file, item, i, len, canAccessFolder;
items = dataTransfer.items;
files = dataTransfer.files;
canAccessFolder = !!(items && items[ 0 ].webkitGetAsEntry);
for ( i = 0, len = files.length; i < len; i++ ) {
file = files[ i ];
item = items && items[ i ];
if ( canAccessFolder && item.webkitGetAsEntry().isDirectory ) {
promises.push( this._traverseDirectoryTree(
item.webkitGetAsEntry(), results ) );
} else {
results.push( file );
}
}
Base.when.apply( Base, promises ).done(function() {
if ( !results.length ) {
return;
}
callback( results );
});
},
_traverseDirectoryTree: function( entry, results ) {
var deferred = Base.Deferred(),
me = this;
if ( entry.isFile ) {
entry.file(function( file ) {
results.push( file );
deferred.resolve();
});
} else if ( entry.isDirectory ) {
entry.createReader().readEntries(function( entries ) {
var len = entries.length,
promises = [],
arr = [], // 为了保证顺序。
i;
for ( i = 0; i < len; i++ ) {
promises.push( me._traverseDirectoryTree(
entries[ i ], arr ) );
}
Base.when.apply( Base, promises ).then(function() {
results.push.apply( results, arr );
deferred.resolve();
}, deferred.reject );
});
}
return deferred.promise();
},
destroy: function() {
var elem = this.elem;
// 还没 init 就调用 destroy
if (!elem) {
return;
}
elem.off( 'dragenter', this.dragEnterHandler );
elem.off( 'dragover', this.dragOverHandler );
elem.off( 'dragleave', this.dragLeaveHandler );
elem.off( 'drop', this.dropHandler );
if ( this.options.disableGlobalDnd ) {
$( document ).off( 'dragover', this.dragOverHandler );
$( document ).off( 'drop', this.dropHandler );
}
}
});
});
/**
* @fileOverview FilePaste
*/
define('runtime/html5/filepaste',[
'base',
'runtime/html5/runtime',
'lib/file'
], function( Base, Html5Runtime, File ) {
return Html5Runtime.register( 'FilePaste', {
init: function() {
var opts = this.options,
elem = this.elem = opts.container,
accept = '.*',
arr, i, len, item;
// accetp的mimeTypes中生成匹配正则。
if ( opts.accept ) {
arr = [];
for ( i = 0, len = opts.accept.length; i < len; i++ ) {
item = opts.accept[ i ].mimeTypes;
item && arr.push( item );
}
if ( arr.length ) {
accept = arr.join(',');
accept = accept.replace( /,/g, '|' ).replace( /\*/g, '.*' );
}
}
this.accept = accept = new RegExp( accept, 'i' );
this.hander = Base.bindFn( this._pasteHander, this );
elem.on( 'paste', this.hander );
},
_pasteHander: function( e ) {
var allowed = [],
ruid = this.getRuid(),
items, item, blob, i, len;
e = e.originalEvent || e;
items = e.clipboardData.items;
for ( i = 0, len = items.length; i < len; i++ ) {
item = items[ i ];
if ( item.kind !== 'file' || !(blob = item.getAsFile()) ) {
continue;
}
allowed.push( new File( ruid, blob ) );
}
if ( allowed.length ) {
// 不阻止非文件粘贴(文字粘贴)的事件冒泡
e.preventDefault();
e.stopPropagation();
this.trigger( 'paste', allowed );
}
},
destroy: function() {
this.elem.off( 'paste', this.hander );
}
});
});
/**
* @fileOverview FilePicker
*/
define('runtime/html5/filepicker',[
'base',
'runtime/html5/runtime'
], function( Base, Html5Runtime ) {
var $ = Base.$;
return Html5Runtime.register( 'FilePicker', {
init: function() {
var container = this.getRuntime().getContainer(),
me = this,
owner = me.owner,
opts = me.options,
label = this.label = $( document.createElement('label') ),
input = this.input = $( document.createElement('input') ),
arr, i, len, mouseHandler, changeHandler;
input.attr( 'type', 'file' );
input.attr( 'capture', 'camera');
input.attr( 'name', opts.name );
input.addClass('webuploader-element-invisible');
label.on( 'click', function(e) {
input.trigger('click');
e.stopPropagation();
owner.trigger('dialogopen');
});
label.css({
opacity: 0,
width: '100%',
height: '100%',
display: 'block',
cursor: 'pointer',
background: '#ffffff'
});
if ( opts.multiple ) {
input.attr( 'multiple', 'multiple' );
}
// @todo Firefox不支持单独指定后缀
if ( opts.accept && opts.accept.length > 0 ) {
arr = [];
for ( i = 0, len = opts.accept.length; i < len; i++ ) {
arr.push( opts.accept[ i ].mimeTypes );
}
input.attr( 'accept', arr.join(',') );
}
container.append( input );
container.append( label );
mouseHandler = function( e ) {
owner.trigger( e.type );
};
changeHandler = function( e ) {
var clone;
// 解决chrome 56 第二次打开文件选择器,然后点击取消,依然会触发change事件的问题
if (e.target.files.length === 0){
return false;
}
// 第一次上传图片后,第二次再点击弹出文件选择器窗,等待
me.files = e.target.files;
// reset input
clone = this.cloneNode( true );
clone.value = null;
this.parentNode.replaceChild( clone, this );
input.off();
input = $( clone ).on( 'change', changeHandler )
.on( 'mouseenter mouseleave', mouseHandler );
owner.trigger('change');
}
input.on( 'change', changeHandler);
label.on( 'mouseenter mouseleave', mouseHandler );
},
getFiles: function() {
return this.files;
},
destroy: function() {
this.input.off();
this.label.off();
}
});
});
/**
* Terms:
*
* Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
* @fileOverview Image控件
*/
define('runtime/html5/util',[
'base'
], function( Base ) {
var urlAPI = window.createObjectURL && window ||
window.URL && URL.revokeObjectURL && URL ||
window.webkitURL,
createObjectURL = Base.noop,
revokeObjectURL = createObjectURL;
if ( urlAPI ) {
// 更安全的方式调用,比如android里面就能把context改成其他的对象。
createObjectURL = function() {
return urlAPI.createObjectURL.apply( urlAPI, arguments );
};
revokeObjectURL = function() {
return urlAPI.revokeObjectURL.apply( urlAPI, arguments );
};
}
return {
createObjectURL: createObjectURL,
revokeObjectURL: revokeObjectURL,
dataURL2Blob: function( dataURI ) {
var byteStr, intArray, ab, i, mimetype, parts;
parts = dataURI.split(',');
if ( ~parts[ 0 ].indexOf('base64') ) {
byteStr = atob( parts[ 1 ] );
} else {
byteStr = decodeURIComponent( parts[ 1 ] );
}
ab = new ArrayBuffer( byteStr.length );
intArray = new Uint8Array( ab );
for ( i = 0; i < byteStr.length; i++ ) {
intArray[ i ] = byteStr.charCodeAt( i );
}
mimetype = parts[ 0 ].split(':')[ 1 ].split(';')[ 0 ];
return this.arrayBufferToBlob( ab, mimetype );
},
dataURL2ArrayBuffer: function( dataURI ) {
var byteStr, intArray, i, parts;
parts = dataURI.split(',');
if ( ~parts[ 0 ].indexOf('base64') ) {
byteStr = atob( parts[ 1 ] );
} else {
byteStr = decodeURIComponent( parts[ 1 ] );
}
intArray = new Uint8Array( byteStr.length );
for ( i = 0; i < byteStr.length; i++ ) {
intArray[ i ] = byteStr.charCodeAt( i );
}
return intArray.buffer;
},
arrayBufferToBlob: function( buffer, type ) {
var builder = window.BlobBuilder || window.WebKitBlobBuilder,
bb;
// android不支持直接new Blob, 只能借助blobbuilder.
if ( builder ) {
bb = new builder();
bb.append( buffer );
return bb.getBlob( type );
}
return new Blob([ buffer ], type ? { type: type } : {} );
},
// 抽出来主要是为了解决android下面canvas.toDataUrl不支持jpeg.
// 你得到的结果是png.
canvasToDataUrl: function( canvas, type, quality ) {
return canvas.toDataURL( type, quality / 100 );
},
// imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
parseMeta: function( blob, callback ) {
callback( false, {});
},
// imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
updateImageHead: function( data ) {
return data;
}
};
});
/**
* Terms:
*
* Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
* @fileOverview Image控件
*/
define('runtime/html5/imagemeta',[
'runtime/html5/util'
], function( Util ) {
var api;
api = {
parsers: {
0xffe1: []
},
maxMetaDataSize: 262144,
parse: function( blob, cb ) {
var me = this,
fr = new FileReader();
fr.onload = function() {
cb( false, me._parse( this.result ) );
fr = fr.onload = fr.onerror = null;
};
fr.onerror = function( e ) {
cb( e.message );
fr = fr.onload = fr.onerror = null;
};
blob = blob.slice( 0, me.maxMetaDataSize );
fr.readAsArrayBuffer( blob.getSource() );
},
_parse: function( buffer, noParse ) {
if ( buffer.byteLength < 6 ) {
return;
}
var dataview = new DataView( buffer ),
offset = 2,
maxOffset = dataview.byteLength - 4,
headLength = offset,
ret = {},
markerBytes, markerLength, parsers, i;
if ( dataview.getUint16( 0 ) === 0xffd8 ) {
while ( offset < maxOffset ) {
markerBytes = dataview.getUint16( offset );
if ( markerBytes >= 0xffe0 && markerBytes <= 0xffef ||
markerBytes === 0xfffe ) {
markerLength = dataview.getUint16( offset + 2 ) + 2;
if ( offset + markerLength > dataview.byteLength ) {
break;
}
parsers = api.parsers[ markerBytes ];
if ( !noParse && parsers ) {
for ( i = 0; i < parsers.length; i += 1 ) {
parsers[ i ].call( api, dataview, offset,
markerLength, ret );
}
}
offset += markerLength;
headLength = offset;
} else {
break;
}
}
if ( headLength > 6 ) {
if ( buffer.slice ) {
ret.imageHead = buffer.slice( 2, headLength );
} else {
// Workaround for IE10, which does not yet
// support ArrayBuffer.slice:
ret.imageHead = new Uint8Array( buffer )
.subarray( 2, headLength );
}
}
}
return ret;
},
updateImageHead: function( buffer, head ) {
var data = this._parse( buffer, true ),
buf1, buf2, bodyoffset;
bodyoffset = 2;
if ( data.imageHead ) {
bodyoffset = 2 + data.imageHead.byteLength;
}
if ( buffer.slice ) {
buf2 = buffer.slice( bodyoffset );
} else {
buf2 = new Uint8Array( buffer ).subarray( bodyoffset );
}
buf1 = new Uint8Array( head.byteLength + 2 + buf2.byteLength );
buf1[ 0 ] = 0xFF;
buf1[ 1 ] = 0xD8;
buf1.set( new Uint8Array( head ), 2 );
buf1.set( new Uint8Array( buf2 ), head.byteLength + 2 );
return buf1.buffer;
}
};
Util.parseMeta = function() {
return api.parse.apply( api, arguments );
};
Util.updateImageHead = function() {
return api.updateImageHead.apply( api, arguments );
};
return api;
});
/**
* 代码来自于:https://github.com/blueimp/JavaScript-Load-Image
* 暂时项目中只用了orientation.
*
* 去除了 Exif Sub IFD Pointer, GPS Info IFD Pointer, Exif Thumbnail.
* @fileOverview EXIF解析
*/
// Sample
// ====================================
// Make : Apple
// Model : iPhone 4S
// Orientation : 1
// XResolution : 72 [72/1]
// YResolution : 72 [72/1]
// ResolutionUnit : 2
// Software : QuickTime 7.7.1
// DateTime : 2013:09:01 22:53:55
// ExifIFDPointer : 190
// ExposureTime : 0.058823529411764705 [1/17]
// FNumber : 2.4 [12/5]
// ExposureProgram : Normal program
// ISOSpeedRatings : 800
// ExifVersion : 0220
// DateTimeOriginal : 2013:09:01 22:52:51
// DateTimeDigitized : 2013:09:01 22:52:51
// ComponentsConfiguration : YCbCr
// ShutterSpeedValue : 4.058893515764426
// ApertureValue : 2.5260688216892597 [4845/1918]
// BrightnessValue : -0.3126686601998395
// MeteringMode : Pattern
// Flash : Flash did not fire, compulsory flash mode
// FocalLength : 4.28 [107/25]
// SubjectArea : [4 values]
// FlashpixVersion : 0100
// ColorSpace : 1
// PixelXDimension : 2448
// PixelYDimension : 3264
// SensingMethod : One-chip color area sensor
// ExposureMode : 0
// WhiteBalance : Auto white balance
// FocalLengthIn35mmFilm : 35
// SceneCaptureType : Standard
define('runtime/html5/imagemeta/exif',[
'base',
'runtime/html5/imagemeta'
], function( Base, ImageMeta ) {
var EXIF = {};
EXIF.ExifMap = function() {
return this;
};
EXIF.ExifMap.prototype.map = {
'Orientation': 0x0112
};
EXIF.ExifMap.prototype.get = function( id ) {
return this[ id ] || this[ this.map[ id ] ];
};
EXIF.exifTagTypes = {
// byte, 8-bit unsigned int:
1: {
getValue: function( dataView, dataOffset ) {
return dataView.getUint8( dataOffset );
},
size: 1
},
// ascii, 8-bit byte:
2: {
getValue: function( dataView, dataOffset ) {
return String.fromCharCode( dataView.getUint8( dataOffset ) );
},
size: 1,
ascii: true
},
// short, 16 bit int:
3: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getUint16( dataOffset, littleEndian );
},
size: 2
},
// long, 32 bit int:
4: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getUint32( dataOffset, littleEndian );
},
size: 4
},
// rational = two long values,
// first is numerator, second is denominator:
5: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getUint32( dataOffset, littleEndian ) /
dataView.getUint32( dataOffset + 4, littleEndian );
},
size: 8
},
// slong, 32 bit signed int:
9: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getInt32( dataOffset, littleEndian );
},
size: 4
},
// srational, two slongs, first is numerator, second is denominator:
10: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getInt32( dataOffset, littleEndian ) /
dataView.getInt32( dataOffset + 4, littleEndian );
},
size: 8
}
};
// undefined, 8-bit byte, value depending on field:
EXIF.exifTagTypes[ 7 ] = EXIF.exifTagTypes[ 1 ];
EXIF.getExifValue = function( dataView, tiffOffset, offset, type, length,
littleEndian ) {
var tagType = EXIF.exifTagTypes[ type ],
tagSize, dataOffset, values, i, str, c;
if ( !tagType ) {
Base.log('Invalid Exif data: Invalid tag type.');
return;
}
tagSize = tagType.size * length;
// Determine if the value is contained in the dataOffset bytes,
// or if the value at the dataOffset is a pointer to the actual data:
dataOffset = tagSize > 4 ? tiffOffset + dataView.getUint32( offset + 8,
littleEndian ) : (offset + 8);
if ( dataOffset + tagSize > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid data offset.');
return;
}
if ( length === 1 ) {
return tagType.getValue( dataView, dataOffset, littleEndian );
}
values = [];
for ( i = 0; i < length; i += 1 ) {
values[ i ] = tagType.getValue( dataView,
dataOffset + i * tagType.size, littleEndian );
}
if ( tagType.ascii ) {
str = '';
// Concatenate the chars:
for ( i = 0; i < values.length; i += 1 ) {
c = values[ i ];
// Ignore the terminating NULL byte(s):
if ( c === '\u0000' ) {
break;
}
str += c;
}
return str;
}
return values;
};
EXIF.parseExifTag = function( dataView, tiffOffset, offset, littleEndian,
data ) {
var tag = dataView.getUint16( offset, littleEndian );
data.exif[ tag ] = EXIF.getExifValue( dataView, tiffOffset, offset,
dataView.getUint16( offset + 2, littleEndian ), // tag type
dataView.getUint32( offset + 4, littleEndian ), // tag length
littleEndian );
};
EXIF.parseExifTags = function( dataView, tiffOffset, dirOffset,
littleEndian, data ) {
var tagsNumber, dirEndOffset, i;
if ( dirOffset + 6 > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid directory offset.');
return;
}
tagsNumber = dataView.getUint16( dirOffset, littleEndian );
dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
if ( dirEndOffset + 4 > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid directory size.');
return;
}
for ( i = 0; i < tagsNumber; i += 1 ) {
this.parseExifTag( dataView, tiffOffset,
dirOffset + 2 + 12 * i, // tag offset
littleEndian, data );
}
// Return the offset to the next directory:
return dataView.getUint32( dirEndOffset, littleEndian );
};
// EXIF.getExifThumbnail = function(dataView, offset, length) {
// var hexData,
// i,
// b;
// if (!length || offset + length > dataView.byteLength) {
// Base.log('Invalid Exif data: Invalid thumbnail data.');
// return;
// }
// hexData = [];
// for (i = 0; i < length; i += 1) {
// b = dataView.getUint8(offset + i);
// hexData.push((b < 16 ? '0' : '') + b.toString(16));
// }
// return 'data:image/jpeg,%' + hexData.join('%');
// };
EXIF.parseExifData = function( dataView, offset, length, data ) {
var tiffOffset = offset + 10,
littleEndian, dirOffset;
// Check for the ASCII code for "Exif" (0x45786966):
if ( dataView.getUint32( offset + 4 ) !== 0x45786966 ) {
// No Exif data, might be XMP data instead
return;
}
if ( tiffOffset + 8 > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid segment size.');
return;
}
// Check for the two null bytes:
if ( dataView.getUint16( offset + 8 ) !== 0x0000 ) {
Base.log('Invalid Exif data: Missing byte alignment offset.');
return;
}
// Check the byte alignment:
switch ( dataView.getUint16( tiffOffset ) ) {
case 0x4949:
littleEndian = true;
break;
case 0x4D4D:
littleEndian = false;
break;
default:
Base.log('Invalid Exif data: Invalid byte alignment marker.');
return;
}
// Check for the TIFF tag marker (0x002A):
if ( dataView.getUint16( tiffOffset + 2, littleEndian ) !== 0x002A ) {
Base.log('Invalid Exif data: Missing TIFF marker.');
return;
}
// Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
dirOffset = dataView.getUint32( tiffOffset + 4, littleEndian );
// Create the exif object to store the tags:
data.exif = new EXIF.ExifMap();
// Parse the tags of the main image directory and retrieve the
// offset to the next directory, usually the thumbnail directory:
dirOffset = EXIF.parseExifTags( dataView, tiffOffset,
tiffOffset + dirOffset, littleEndian, data );
// 尝试读取缩略图
// if ( dirOffset ) {
// thumbnailData = {exif: {}};
// dirOffset = EXIF.parseExifTags(
// dataView,
// tiffOffset,
// tiffOffset + dirOffset,
// littleEndian,
// thumbnailData
// );
// // Check for JPEG Thumbnail offset:
// if (thumbnailData.exif[0x0201]) {
// data.exif.Thumbnail = EXIF.getExifThumbnail(
// dataView,
// tiffOffset + thumbnailData.exif[0x0201],
// thumbnailData.exif[0x0202] // Thumbnail data length
// );
// }
// }
};
ImageMeta.parsers[ 0xffe1 ].push( EXIF.parseExifData );
return EXIF;
});
/**
* 这个方式性能不行,但是可以解决android里面的toDataUrl的bug
* android里面toDataUrl('image/jpege')得到的结果却是png.
*
* 所以这里没辙,只能借助这个工具
* @fileOverview jpeg encoder
*/
define('runtime/html5/jpegencoder',[], function( require, exports, module ) {
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009
Basic GUI blocking jpeg encoder
*/
function JPEGEncoder(quality) {
var self = this;
var fround = Math.round;
var ffloor = Math.floor;
var YTable = new Array(64);
var UVTable = new Array(64);
var fdtbl_Y = new Array(64);
var fdtbl_UV = new Array(64);
var YDC_HT;
var UVDC_HT;
var YAC_HT;
var UVAC_HT;
var bitcode = new Array(65535);
var category = new Array(65535);
var outputfDCTQuant = new Array(64);
var DU = new Array(64);
var byteout = [];
var bytenew = 0;
var bytepos = 7;
var YDU = new Array(64);
var UDU = new Array(64);
var VDU = new Array(64);
var clt = new Array(256);
var RGB_YUV_TABLE = new Array(2048);
var currentQuality;
var ZigZag = [
0, 1, 5, 6,14,15,27,28,
2, 4, 7,13,16,26,29,42,
3, 8,12,17,25,30,41,43,
9,11,18,24,31,40,44,53,
10,19,23,32,39,45,52,54,
20,22,33,38,46,51,55,60,
21,34,37,47,50,56,59,61,
35,36,48,49,57,58,62,63
];
var std_dc_luminance_nrcodes = [0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0];
var std_dc_luminance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
var std_ac_luminance_nrcodes = [0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d];
var std_ac_luminance_values = [
0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,
0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,
0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,
0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,
0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,
0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,
0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,
0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,
0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,
0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,
0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,
0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,
0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,
0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,
0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,
0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,
0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,
0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,
0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
0xf9,0xfa
];
var std_dc_chrominance_nrcodes = [0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0];
var std_dc_chrominance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
var std_ac_chrominance_nrcodes = [0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77];
var std_ac_chrominance_values = [
0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,
0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,
0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,
0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,
0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,
0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,
0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,
0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,
0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,
0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,
0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,
0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,
0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,
0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,
0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,
0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,
0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,
0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,
0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
0xf9,0xfa
];
function initQuantTables(sf){
var YQT = [
16, 11, 10, 16, 24, 40, 51, 61,
12, 12, 14, 19, 26, 58, 60, 55,
14, 13, 16, 24, 40, 57, 69, 56,
14, 17, 22, 29, 51, 87, 80, 62,
18, 22, 37, 56, 68,109,103, 77,
24, 35, 55, 64, 81,104,113, 92,
49, 64, 78, 87,103,121,120,101,
72, 92, 95, 98,112,100,103, 99
];
for (var i = 0; i < 64; i++) {
var t = ffloor((YQT[i]*sf+50)/100);
if (t < 1) {
t = 1;
} else if (t > 255) {
t = 255;
}
YTable[ZigZag[i]] = t;
}
var UVQT = [
17, 18, 24, 47, 99, 99, 99, 99,
18, 21, 26, 66, 99, 99, 99, 99,
24, 26, 56, 99, 99, 99, 99, 99,
47, 66, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99
];
for (var j = 0; j < 64; j++) {
var u = ffloor((UVQT[j]*sf+50)/100);
if (u < 1) {
u = 1;
} else if (u > 255) {
u = 255;
}
UVTable[ZigZag[j]] = u;
}
var aasf = [
1.0, 1.387039845, 1.306562965, 1.175875602,
1.0, 0.785694958, 0.541196100, 0.275899379
];
var k = 0;
for (var row = 0; row < 8; row++)
{
for (var col = 0; col < 8; col++)
{
fdtbl_Y[k] = (1.0 / (YTable [ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
fdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
k++;
}
}
}
function computeHuffmanTbl(nrcodes, std_table){
var codevalue = 0;
var pos_in_table = 0;
var HT = new Array();
for (var k = 1; k <= 16; k++) {
for (var j = 1; j <= nrcodes[k]; j++) {
HT[std_table[pos_in_table]] = [];
HT[std_table[pos_in_table]][0] = codevalue;
HT[std_table[pos_in_table]][1] = k;
pos_in_table++;
codevalue++;
}
codevalue*=2;
}
return HT;
}
function initHuffmanTbl()
{
YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values);
UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values);
YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values);
UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values);
}
function initCategoryNumber()
{
var nrlower = 1;
var nrupper = 2;
for (var cat = 1; cat <= 15; cat++) {
//Positive numbers
for (var nr = nrlower; nr>0] = 38470 * i;
RGB_YUV_TABLE[(i+ 512)>>0] = 7471 * i + 0x8000;
RGB_YUV_TABLE[(i+ 768)>>0] = -11059 * i;
RGB_YUV_TABLE[(i+1024)>>0] = -21709 * i;
RGB_YUV_TABLE[(i+1280)>>0] = 32768 * i + 0x807FFF;
RGB_YUV_TABLE[(i+1536)>>0] = -27439 * i;
RGB_YUV_TABLE[(i+1792)>>0] = - 5329 * i;
}
}
// IO functions
function writeBits(bs)
{
var value = bs[0];
var posval = bs[1]-1;
while ( posval >= 0 ) {
if (value & (1 << posval) ) {
bytenew |= (1 << bytepos);
}
posval--;
bytepos--;
if (bytepos < 0) {
if (bytenew == 0xFF) {
writeByte(0xFF);
writeByte(0);
}
else {
writeByte(bytenew);
}
bytepos=7;
bytenew=0;
}
}
}
function writeByte(value)
{
byteout.push(clt[value]); // write char directly instead of converting later
}
function writeWord(value)
{
writeByte((value>>8)&0xFF);
writeByte((value )&0xFF);
}
// DCT & quantization core
function fDCTQuant(data, fdtbl)
{
var d0, d1, d2, d3, d4, d5, d6, d7;
/* Pass 1: process rows. */
var dataOff=0;
var i;
var I8 = 8;
var I64 = 64;
for (i=0; i 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0);
//outputfDCTQuant[i] = fround(fDCTQuant);
}
return outputfDCTQuant;
}
function writeAPP0()
{
writeWord(0xFFE0); // marker
writeWord(16); // length
writeByte(0x4A); // J
writeByte(0x46); // F
writeByte(0x49); // I
writeByte(0x46); // F
writeByte(0); // = "JFIF",'\0'
writeByte(1); // versionhi
writeByte(1); // versionlo
writeByte(0); // xyunits
writeWord(1); // xdensity
writeWord(1); // ydensity
writeByte(0); // thumbnwidth
writeByte(0); // thumbnheight
}
function writeSOF0(width, height)
{
writeWord(0xFFC0); // marker
writeWord(17); // length, truecolor YUV JPG
writeByte(8); // precision
writeWord(height);
writeWord(width);
writeByte(3); // nrofcomponents
writeByte(1); // IdY
writeByte(0x11); // HVY
writeByte(0); // QTY
writeByte(2); // IdU
writeByte(0x11); // HVU
writeByte(1); // QTU
writeByte(3); // IdV
writeByte(0x11); // HVV
writeByte(1); // QTV
}
function writeDQT()
{
writeWord(0xFFDB); // marker
writeWord(132); // length
writeByte(0);
for (var i=0; i<64; i++) {
writeByte(YTable[i]);
}
writeByte(1);
for (var j=0; j<64; j++) {
writeByte(UVTable[j]);
}
}
function writeDHT()
{
writeWord(0xFFC4); // marker
writeWord(0x01A2); // length
writeByte(0); // HTYDCinfo
for (var i=0; i<16; i++) {
writeByte(std_dc_luminance_nrcodes[i+1]);
}
for (var j=0; j<=11; j++) {
writeByte(std_dc_luminance_values[j]);
}
writeByte(0x10); // HTYACinfo
for (var k=0; k<16; k++) {
writeByte(std_ac_luminance_nrcodes[k+1]);
}
for (var l=0; l<=161; l++) {
writeByte(std_ac_luminance_values[l]);
}
writeByte(1); // HTUDCinfo
for (var m=0; m<16; m++) {
writeByte(std_dc_chrominance_nrcodes[m+1]);
}
for (var n=0; n<=11; n++) {
writeByte(std_dc_chrominance_values[n]);
}
writeByte(0x11); // HTUACinfo
for (var o=0; o<16; o++) {
writeByte(std_ac_chrominance_nrcodes[o+1]);
}
for (var p=0; p<=161; p++) {
writeByte(std_ac_chrominance_values[p]);
}
}
function writeSOS()
{
writeWord(0xFFDA); // marker
writeWord(12); // length
writeByte(3); // nrofcomponents
writeByte(1); // IdY
writeByte(0); // HTY
writeByte(2); // IdU
writeByte(0x11); // HTU
writeByte(3); // IdV
writeByte(0x11); // HTV
writeByte(0); // Ss
writeByte(0x3f); // Se
writeByte(0); // Bf
}
function processDU(CDU, fdtbl, DC, HTDC, HTAC){
var EOB = HTAC[0x00];
var M16zeroes = HTAC[0xF0];
var pos;
var I16 = 16;
var I63 = 63;
var I64 = 64;
var DU_DCT = fDCTQuant(CDU, fdtbl);
//ZigZag reorder
for (var j=0;j0)&&(DU[end0pos]==0); end0pos--) {};
//end0pos = first element in reverse order !=0
if ( end0pos == 0) {
writeBits(EOB);
return DC;
}
var i = 1;
var lng;
while ( i <= end0pos ) {
var startpos = i;
for (; (DU[i]==0) && (i<=end0pos); ++i) {}
var nrzeroes = i-startpos;
if ( nrzeroes >= I16 ) {
lng = nrzeroes>>4;
for (var nrmarker=1; nrmarker <= lng; ++nrmarker)
writeBits(M16zeroes);
nrzeroes = nrzeroes&0xF;
}
pos = 32767+DU[i];
writeBits(HTAC[(nrzeroes<<4)+category[pos]]);
writeBits(bitcode[pos]);
i++;
}
if ( end0pos != I63 ) {
writeBits(EOB);
}
return DC;
}
function initCharLookupTable(){
var sfcc = String.fromCharCode;
for(var i=0; i < 256; i++){ ///// ACHTUNG // 255
clt[i] = sfcc(i);
}
}
this.encode = function(image,quality) // image data object
{
// var time_start = new Date().getTime();
if(quality) setQuality(quality);
// Initialize bit writer
byteout = new Array();
bytenew=0;
bytepos=7;
// Add JPEG headers
writeWord(0xFFD8); // SOI
writeAPP0();
writeDQT();
writeSOF0(image.width,image.height);
writeDHT();
writeSOS();
// Encode 8x8 macroblocks
var DCY=0;
var DCU=0;
var DCV=0;
bytenew=0;
bytepos=7;
this.encode.displayName = "_encode_";
var imageData = image.data;
var width = image.width;
var height = image.height;
var quadWidth = width*4;
var tripleWidth = width*3;
var x, y = 0;
var r, g, b;
var start,p, col,row,pos;
while(y < height){
x = 0;
while(x < quadWidth){
start = quadWidth * y + x;
p = start;
col = -1;
row = 0;
for(pos=0; pos < 64; pos++){
row = pos >> 3;// /8
col = ( pos & 7 ) * 4; // %8
p = start + ( row * quadWidth ) + col;
if(y+row >= height){ // padding bottom
p-= (quadWidth*(y+1+row-height));
}
if(x+col >= quadWidth){ // padding right
p-= ((x+col) - quadWidth +4)
}
r = imageData[ p++ ];
g = imageData[ p++ ];
b = imageData[ p++ ];
/* // calculate YUV values dynamically
YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80
UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));
VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));
*/
// use lookup table (slightly faster)
YDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256)>>0] + RGB_YUV_TABLE[(b + 512)>>0]) >> 16)-128;
UDU[pos] = ((RGB_YUV_TABLE[(r + 768)>>0] + RGB_YUV_TABLE[(g + 1024)>>0] + RGB_YUV_TABLE[(b + 1280)>>0]) >> 16)-128;
VDU[pos] = ((RGB_YUV_TABLE[(r + 1280)>>0] + RGB_YUV_TABLE[(g + 1536)>>0] + RGB_YUV_TABLE[(b + 1792)>>0]) >> 16)-128;
}
DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
x+=32;
}
y+=8;
}
////////////////////////////////////////////////////////////////
// Do the bit alignment of the EOI marker
if ( bytepos >= 0 ) {
var fillbits = [];
fillbits[1] = bytepos+1;
fillbits[0] = (1<<(bytepos+1))-1;
writeBits(fillbits);
}
writeWord(0xFFD9); //EOI
var jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join(''));
byteout = [];
// benchmarking
// var duration = new Date().getTime() - time_start;
// console.log('Encoding time: '+ currentQuality + 'ms');
//
return jpegDataUri
}
function setQuality(quality){
if (quality <= 0) {
quality = 1;
}
if (quality > 100) {
quality = 100;
}
if(currentQuality == quality) return // don't recalc if unchanged
var sf = 0;
if (quality < 50) {
sf = Math.floor(5000 / quality);
} else {
sf = Math.floor(200 - quality*2);
}
initQuantTables(sf);
currentQuality = quality;
// console.log('Quality set to: '+quality +'%');
}
function init(){
// var time_start = new Date().getTime();
if(!quality) quality = 50;
// Create tables
initCharLookupTable()
initHuffmanTbl();
initCategoryNumber();
initRGBYUVTable();
setQuality(quality);
// var duration = new Date().getTime() - time_start;
// console.log('Initialization '+ duration + 'ms');
}
init();
};
JPEGEncoder.encode = function( data, quality ) {
var encoder = new JPEGEncoder( quality );
return encoder.encode( data );
}
return JPEGEncoder;
});
/**
* @fileOverview Fix android canvas.toDataUrl bug.
*/
define('runtime/html5/androidpatch',[
'runtime/html5/util',
'runtime/html5/jpegencoder',
'base'
], function( Util, encoder, Base ) {
var origin = Util.canvasToDataUrl,
supportJpeg;
Util.canvasToDataUrl = function( canvas, type, quality ) {
var ctx, w, h, fragement, parts;
// 非android手机直接跳过。
if ( !Base.os.android ) {
return origin.apply( null, arguments );
}
// 检测是否canvas支持jpeg导出,根据数据格式来判断。
// JPEG 前两位分别是:255, 216
if ( type === 'image/jpeg' && typeof supportJpeg === 'undefined' ) {
fragement = origin.apply( null, arguments );
parts = fragement.split(',');
if ( ~parts[ 0 ].indexOf('base64') ) {
fragement = atob( parts[ 1 ] );
} else {
fragement = decodeURIComponent( parts[ 1 ] );
}
fragement = fragement.substring( 0, 2 );
supportJpeg = fragement.charCodeAt( 0 ) === 255 &&
fragement.charCodeAt( 1 ) === 216;
}
// 只有在android环境下才修复
if ( type === 'image/jpeg' && !supportJpeg ) {
w = canvas.width;
h = canvas.height;
ctx = canvas.getContext('2d');
return encoder.encode( ctx.getImageData( 0, 0, w, h ), quality );
}
return origin.apply( null, arguments );
};
});
/**
* @fileOverview Image
*/
define('runtime/html5/image',[
'base',
'runtime/html5/runtime',
'runtime/html5/util'
], function( Base, Html5Runtime, Util ) {
var BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D';
return Html5Runtime.register( 'Image', {
// flag: 标记是否被修改过。
modified: false,
init: function() {
var me = this,
img = new Image();
img.onload = function() {
me._info = {
type: me.type,
width: this.width,
height: this.height
};
//debugger;
// 读取meta信息。
if ( !me._metas && 'image/jpeg' === me.type ) {
Util.parseMeta( me._blob, function( error, ret ) {
me._metas = ret;
me.owner.trigger('load');
});
} else {
me.owner.trigger('load');
}
};
img.onerror = function() {
me.owner.trigger('error');
};
me._img = img;
},
loadFromBlob: function( blob ) {
var me = this,
img = me._img;
me._blob = blob;
me.type = blob.type;
img.src = Util.createObjectURL( blob.getSource() );
me.owner.once( 'load', function() {
Util.revokeObjectURL( img.src );
});
},
resize: function( width, height ) {
var canvas = this._canvas ||
(this._canvas = document.createElement('canvas'));
this._resize( this._img, canvas, width, height );
this._blob = null; // 没用了,可以删掉了。
this.modified = true;
this.owner.trigger( 'complete', 'resize' );
},
crop: function( x, y, w, h, s ) {
var cvs = this._canvas ||
(this._canvas = document.createElement('canvas')),
opts = this.options,
img = this._img,
iw = img.naturalWidth,
ih = img.naturalHeight,
orientation = this.getOrientation();
s = s || 1;
// todo 解决 orientation 的问题。
// values that require 90 degree rotation
// if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) {
// switch ( orientation ) {
// case 6:
// tmp = x;
// x = y;
// y = iw * s - tmp - w;
// console.log(ih * s, tmp, w)
// break;
// }
// (w ^= h, h ^= w, w ^= h);
// }
cvs.width = w;
cvs.height = h;
opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation );
this._renderImageToCanvas( cvs, img, -x, -y, iw * s, ih * s );
this._blob = null; // 没用了,可以删掉了。
this.modified = true;
this.owner.trigger( 'complete', 'crop' );
},
getAsBlob: function( type ) {
var blob = this._blob,
opts = this.options,
canvas;
type = type || this.type;
// blob需要重新生成。
if ( this.modified || this.type !== type ) {
canvas = this._canvas;
if ( type === 'image/jpeg' ) {
blob = Util.canvasToDataUrl( canvas, type, opts.quality );
if ( opts.preserveHeaders && this._metas &&
this._metas.imageHead ) {
blob = Util.dataURL2ArrayBuffer( blob );
blob = Util.updateImageHead( blob,
this._metas.imageHead );
blob = Util.arrayBufferToBlob( blob, type );
return blob;
}
} else {
blob = Util.canvasToDataUrl( canvas, type );
}
blob = Util.dataURL2Blob( blob );
}
return blob;
},
getAsDataUrl: function( type ) {
var opts = this.options;
type = type || this.type;
if ( type === 'image/jpeg' ) {
return Util.canvasToDataUrl( this._canvas, type, opts.quality );
} else {
return this._canvas.toDataURL( type );
}
},
getOrientation: function() {
return this._metas && this._metas.exif &&
this._metas.exif.get('Orientation') || 1;
},
info: function( val ) {
// setter
if ( val ) {
this._info = val;
return this;
}
// getter
return this._info;
},
meta: function( val ) {
// setter
if ( val ) {
this._metas = val;
return this;
}
// getter
return this._metas;
},
destroy: function() {
var canvas = this._canvas;
this._img.onload = null;
if ( canvas ) {
canvas.getContext('2d')
.clearRect( 0, 0, canvas.width, canvas.height );
canvas.width = canvas.height = 0;
this._canvas = null;
}
// 释放内存。非常重要,否则释放不了image的内存。
this._img.src = BLANK;
this._img = this._blob = null;
},
_resize: function( img, cvs, width, height ) {
var opts = this.options,
naturalWidth = img.width,
naturalHeight = img.height,
orientation = this.getOrientation(),
scale, w, h, x, y;
// values that require 90 degree rotation
if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) {
// 交换width, height的值。
width ^= height;
height ^= width;
width ^= height;
}
scale = Math[ opts.crop ? 'max' : 'min' ]( width / naturalWidth,
height / naturalHeight );
// 不允许放大。
opts.allowMagnify || (scale = Math.min( 1, scale ));
w = naturalWidth * scale;
h = naturalHeight * scale;
if ( opts.crop ) {
cvs.width = width;
cvs.height = height;
} else {
cvs.width = w;
cvs.height = h;
}
x = (cvs.width - w) / 2;
y = (cvs.height - h) / 2;
opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation );
this._renderImageToCanvas( cvs, img, x, y, w, h );
},
_rotate2Orientaion: function( canvas, orientation ) {
var width = canvas.width,
height = canvas.height,
ctx = canvas.getContext('2d');
switch ( orientation ) {
case 5:
case 6:
case 7:
case 8:
canvas.width = height;
canvas.height = width;
break;
}
switch ( orientation ) {
case 2: // horizontal flip
ctx.translate( width, 0 );
ctx.scale( -1, 1 );
break;
case 3: // 180 rotate left
ctx.translate( width, height );
ctx.rotate( Math.PI );
break;
case 4: // vertical flip
ctx.translate( 0, height );
ctx.scale( 1, -1 );
break;
case 5: // vertical flip + 90 rotate right
ctx.rotate( 0.5 * Math.PI );
ctx.scale( 1, -1 );
break;
case 6: // 90 rotate right
ctx.rotate( 0.5 * Math.PI );
ctx.translate( 0, -height );
break;
case 7: // horizontal flip + 90 rotate right
ctx.rotate( 0.5 * Math.PI );
ctx.translate( width, -height );
ctx.scale( -1, 1 );
break;
case 8: // 90 rotate left
ctx.rotate( -0.5 * Math.PI );
ctx.translate( -width, 0 );
break;
}
},
// https://github.com/stomita/ios-imagefile-megapixel/
// blob/master/src/megapix-image.js
_renderImageToCanvas: (function() {
// 如果不是ios, 不需要这么复杂!
if ( !Base.os.ios ) {
return function( canvas ) {
var args = Base.slice( arguments, 1 ),
ctx = canvas.getContext('2d');
ctx.drawImage.apply( ctx, args );
};
}
/**
* Detecting vertical squash in loaded image.
* Fixes a bug which squash image vertically while drawing into
* canvas for some images.
*/
function detectVerticalSquash( img, iw, ih ) {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
sy = 0,
ey = ih,
py = ih,
data, alpha, ratio;
canvas.width = 1;
canvas.height = ih;
ctx.drawImage( img, 0, 0 );
data = ctx.getImageData( 0, 0, 1, ih ).data;
// search image edge pixel position in case
// it is squashed vertically.
while ( py > sy ) {
alpha = data[ (py - 1) * 4 + 3 ];
if ( alpha === 0 ) {
ey = py;
} else {
sy = py;
}
py = (ey + sy) >> 1;
}
ratio = (py / ih);
return (ratio === 0) ? 1 : ratio;
}
// fix ie7 bug
// http://stackoverflow.com/questions/11929099/
// html5-canvas-drawimage-ratio-bug-ios
if ( Base.os.ios >= 7 ) {
return function( canvas, img, x, y, w, h ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
vertSquashRatio = detectVerticalSquash( img, iw, ih );
return canvas.getContext('2d').drawImage( img, 0, 0,
iw * vertSquashRatio, ih * vertSquashRatio,
x, y, w, h );
};
}
/**
* Detect subsampling in loaded image.
* In iOS, larger images than 2M pixels may be
* subsampled in rendering.
*/
function detectSubsampling( img ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
canvas, ctx;
// subsampling may happen overmegapixel image
if ( iw * ih > 1024 * 1024 ) {
canvas = document.createElement('canvas');
canvas.width = canvas.height = 1;
ctx = canvas.getContext('2d');
ctx.drawImage( img, -iw + 1, 0 );
// subsampled image becomes half smaller in rendering size.
// check alpha channel value to confirm image is covering
// edge pixel or not. if alpha value is 0
// image is not covering, hence subsampled.
return ctx.getImageData( 0, 0, 1, 1 ).data[ 3 ] === 0;
} else {
return false;
}
}
return function( canvas, img, x, y, width, height ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
ctx = canvas.getContext('2d'),
subsampled = detectSubsampling( img ),
doSquash = this.type === 'image/jpeg',
d = 1024,
sy = 0,
dy = 0,
tmpCanvas, tmpCtx, vertSquashRatio, dw, dh, sx, dx;
if ( subsampled ) {
iw /= 2;
ih /= 2;
}
ctx.save();
tmpCanvas = document.createElement('canvas');
tmpCanvas.width = tmpCanvas.height = d;
tmpCtx = tmpCanvas.getContext('2d');
vertSquashRatio = doSquash ?
detectVerticalSquash( img, iw, ih ) : 1;
dw = Math.ceil( d * width / iw );
dh = Math.ceil( d * height / ih / vertSquashRatio );
while ( sy < ih ) {
sx = 0;
dx = 0;
while ( sx < iw ) {
tmpCtx.clearRect( 0, 0, d, d );
tmpCtx.drawImage( img, -sx, -sy );
ctx.drawImage( tmpCanvas, 0, 0, d, d,
x + dx, y + dy, dw, dh );
sx += d;
dx += dw;
}
sy += d;
dy += dh;
}
ctx.restore();
tmpCanvas = tmpCtx = null;
};
})()
});
});
/**
* @fileOverview Transport
* @todo 支持chunked传输,优势:
* 可以将大文件分成小块,挨个传输,可以提高大文件成功率,当失败的时候,也只需要重传那小部分,
* 而不需要重头再传一次。另外断点续传也需要用chunked方式。
*/
define('runtime/html5/transport',[
'base',
'runtime/html5/runtime'
], function( Base, Html5Runtime ) {
var noop = Base.noop,
$ = Base.$;
return Html5Runtime.register( 'Transport', {
init: function() {
this._status = 0;
this._response = null;
},
send: function() {
var owner = this.owner,
opts = this.options,
xhr = this._initAjax(),
blob = owner._blob,
server = opts.server,
formData, binary, fr;
if ( opts.sendAsBinary ) {
server += opts.attachInfoToQuery !== false ? ((/\?/.test( server ) ? '&' : '?') +
$.param( owner._formData )) : '';
binary = blob.getSource();
} else {
formData = new FormData();
$.each( owner._formData, function( k, v ) {
formData.append( k, v );
});
formData.append( opts.fileVal, blob.getSource(),
opts.filename || owner._formData.name || '' );
}
if ( opts.withCredentials && 'withCredentials' in xhr ) {
xhr.open( opts.method, server, true );
xhr.withCredentials = true;
} else {
xhr.open( opts.method, server );
}
this._setRequestHeader( xhr, opts.headers );
if ( binary ) {
// 强制设置成 content-type 为文件流。
xhr.overrideMimeType &&
xhr.overrideMimeType('application/octet-stream');
// android直接发送blob会导致服务端接收到的是空文件。
// bug详情。
// https://code.google.com/p/android/issues/detail?id=39882
// 所以先用fileReader读取出来再通过arraybuffer的方式发送。
if ( Base.os.android ) {
fr = new FileReader();
fr.onload = function() {
xhr.send( this.result );
fr = fr.onload = null;
};
fr.readAsArrayBuffer( binary );
} else {
xhr.send( binary );
}
} else {
xhr.send( formData );
}
},
getResponse: function() {
return this._response;
},
getResponseAsJson: function() {
return this._parseJson( this._response );
},
getResponseHeaders: function() {
return this._headers;
},
getStatus: function() {
return this._status;
},
abort: function() {
var xhr = this._xhr;
if ( xhr ) {
xhr.upload.onprogress = noop;
xhr.onreadystatechange = noop;
xhr.abort();
this._xhr = xhr = null;
}
},
destroy: function() {
this.abort();
},
_parseHeader: function(raw) {
var ret = {};
raw && raw.replace(/^([^\:]+):(.*)$/mg, function(_, key, value) {
ret[key.trim()] = value.trim();
});
return ret;
},
_initAjax: function() {
var me = this,
xhr = new XMLHttpRequest(),
opts = this.options;
if ( opts.withCredentials && !('withCredentials' in xhr) &&
typeof XDomainRequest !== 'undefined' ) {
xhr = new XDomainRequest();
}
xhr.upload.onprogress = function( e ) {
var percentage = 0;
if ( e.lengthComputable ) {
percentage = e.loaded / e.total;
}
return me.trigger( 'progress', percentage );
};
xhr.onreadystatechange = function() {
if ( xhr.readyState !== 4 ) {
return;
}
xhr.upload.onprogress = noop;
xhr.onreadystatechange = noop;
me._xhr = null;
me._status = xhr.status;
var separator = '|', // 分隔符
// 拼接的状态,在 widgets/upload.js 会有代码用到这个分隔符
status = separator + xhr.status +
separator + xhr.statusText;
if ( xhr.status >= 200 && xhr.status < 300 ) {
me._response = xhr.responseText;
me._headers = me._parseHeader(xhr.getAllResponseHeaders());
return me.trigger('load');
} else if ( xhr.status >= 500 && xhr.status < 600 ) {
me._response = xhr.responseText;
me._headers = me._parseHeader(xhr.getAllResponseHeaders());
return me.trigger( 'error', 'server' + status );
}
return me.trigger( 'error', me._status ? 'http' + status : 'abort' );
};
me._xhr = xhr;
return xhr;
},
_setRequestHeader: function( xhr, headers ) {
$.each( headers, function( key, val ) {
xhr.setRequestHeader( key, val );
});
},
_parseJson: function( str ) {
var json;
try {
json = JSON.parse( str );
} catch ( ex ) {
json = {};
}
return json;
}
});
});
/**
* @fileOverview Transport flash实现
*/
define('runtime/html5/md5',[
'runtime/html5/runtime'
], function( FlashRuntime ) {
/*
* Fastest md5 implementation around (JKM md5)
* Credits: Joseph Myers
*
* @see http://www.myersdaily.org/joseph/javascript/md5-text.html
* @see http://jsperf.com/md5-shootout/7
*/
/* this function is much faster,
so if possible we use it. Some IEs
are the only ones I know of that
need the idiotic second function,
generated by an if clause. */
var add32 = function (a, b) {
return (a + b) & 0xFFFFFFFF;
},
cmn = function (q, a, b, x, s, t) {
a = add32(add32(a, q), add32(x, t));
return add32((a << s) | (a >>> (32 - s)), b);
},
ff = function (a, b, c, d, x, s, t) {
return cmn((b & c) | ((~b) & d), a, b, x, s, t);
},
gg = function (a, b, c, d, x, s, t) {
return cmn((b & d) | (c & (~d)), a, b, x, s, t);
},
hh = function (a, b, c, d, x, s, t) {
return cmn(b ^ c ^ d, a, b, x, s, t);
},
ii = function (a, b, c, d, x, s, t) {
return cmn(c ^ (b | (~d)), a, b, x, s, t);
},
md5cycle = function (x, k) {
var a = x[0],
b = x[1],
c = x[2],
d = x[3];
a = ff(a, b, c, d, k[0], 7, -680876936);
d = ff(d, a, b, c, k[1], 12, -389564586);
c = ff(c, d, a, b, k[2], 17, 606105819);
b = ff(b, c, d, a, k[3], 22, -1044525330);
a = ff(a, b, c, d, k[4], 7, -176418897);
d = ff(d, a, b, c, k[5], 12, 1200080426);
c = ff(c, d, a, b, k[6], 17, -1473231341);
b = ff(b, c, d, a, k[7], 22, -45705983);
a = ff(a, b, c, d, k[8], 7, 1770035416);
d = ff(d, a, b, c, k[9], 12, -1958414417);
c = ff(c, d, a, b, k[10], 17, -42063);
b = ff(b, c, d, a, k[11], 22, -1990404162);
a = ff(a, b, c, d, k[12], 7, 1804603682);
d = ff(d, a, b, c, k[13], 12, -40341101);
c = ff(c, d, a, b, k[14], 17, -1502002290);
b = ff(b, c, d, a, k[15], 22, 1236535329);
a = gg(a, b, c, d, k[1], 5, -165796510);
d = gg(d, a, b, c, k[6], 9, -1069501632);
c = gg(c, d, a, b, k[11], 14, 643717713);
b = gg(b, c, d, a, k[0], 20, -373897302);
a = gg(a, b, c, d, k[5], 5, -701558691);
d = gg(d, a, b, c, k[10], 9, 38016083);
c = gg(c, d, a, b, k[15], 14, -660478335);
b = gg(b, c, d, a, k[4], 20, -405537848);
a = gg(a, b, c, d, k[9], 5, 568446438);
d = gg(d, a, b, c, k[14], 9, -1019803690);
c = gg(c, d, a, b, k[3], 14, -187363961);
b = gg(b, c, d, a, k[8], 20, 1163531501);
a = gg(a, b, c, d, k[13], 5, -1444681467);
d = gg(d, a, b, c, k[2], 9, -51403784);
c = gg(c, d, a, b, k[7], 14, 1735328473);
b = gg(b, c, d, a, k[12], 20, -1926607734);
a = hh(a, b, c, d, k[5], 4, -378558);
d = hh(d, a, b, c, k[8], 11, -2022574463);
c = hh(c, d, a, b, k[11], 16, 1839030562);
b = hh(b, c, d, a, k[14], 23, -35309556);
a = hh(a, b, c, d, k[1], 4, -1530992060);
d = hh(d, a, b, c, k[4], 11, 1272893353);
c = hh(c, d, a, b, k[7], 16, -155497632);
b = hh(b, c, d, a, k[10], 23, -1094730640);
a = hh(a, b, c, d, k[13], 4, 681279174);
d = hh(d, a, b, c, k[0], 11, -358537222);
c = hh(c, d, a, b, k[3], 16, -722521979);
b = hh(b, c, d, a, k[6], 23, 76029189);
a = hh(a, b, c, d, k[9], 4, -640364487);
d = hh(d, a, b, c, k[12], 11, -421815835);
c = hh(c, d, a, b, k[15], 16, 530742520);
b = hh(b, c, d, a, k[2], 23, -995338651);
a = ii(a, b, c, d, k[0], 6, -198630844);
d = ii(d, a, b, c, k[7], 10, 1126891415);
c = ii(c, d, a, b, k[14], 15, -1416354905);
b = ii(b, c, d, a, k[5], 21, -57434055);
a = ii(a, b, c, d, k[12], 6, 1700485571);
d = ii(d, a, b, c, k[3], 10, -1894986606);
c = ii(c, d, a, b, k[10], 15, -1051523);
b = ii(b, c, d, a, k[1], 21, -2054922799);
a = ii(a, b, c, d, k[8], 6, 1873313359);
d = ii(d, a, b, c, k[15], 10, -30611744);
c = ii(c, d, a, b, k[6], 15, -1560198380);
b = ii(b, c, d, a, k[13], 21, 1309151649);
a = ii(a, b, c, d, k[4], 6, -145523070);
d = ii(d, a, b, c, k[11], 10, -1120210379);
c = ii(c, d, a, b, k[2], 15, 718787259);
b = ii(b, c, d, a, k[9], 21, -343485551);
x[0] = add32(a, x[0]);
x[1] = add32(b, x[1]);
x[2] = add32(c, x[2]);
x[3] = add32(d, x[3]);
},
/* there needs to be support for Unicode here,
* unless we pretend that we can redefine the MD-5
* algorithm for multi-byte characters (perhaps
* by adding every four 16-bit characters and
* shortening the sum to 32 bits). Otherwise
* I suggest performing MD-5 as if every character
* was two bytes--e.g., 0040 0025 = @%--but then
* how will an ordinary MD-5 sum be matched?
* There is no way to standardize text to something
* like UTF-8 before transformation; speed cost is
* utterly prohibitive. The JavaScript standard
* itself needs to look at this: it should start
* providing access to strings as preformed UTF-8
* 8-bit unsigned value arrays.
*/
md5blk = function (s) {
var md5blks = [],
i; /* Andy King said do it this way. */
for (i = 0; i < 64; i += 4) {
md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
}
return md5blks;
},
md5blk_array = function (a) {
var md5blks = [],
i; /* Andy King said do it this way. */
for (i = 0; i < 64; i += 4) {
md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
}
return md5blks;
},
md51 = function (s) {
var n = s.length,
state = [1732584193, -271733879, -1732584194, 271733878],
i,
length,
tail,
tmp,
lo,
hi;
for (i = 64; i <= n; i += 64) {
md5cycle(state, md5blk(s.substring(i - 64, i)));
}
s = s.substring(i - 64);
length = s.length;
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
}
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i = 0; i < 16; i += 1) {
tail[i] = 0;
}
}
// Beware that the final length might not fit in 32 bits so we take care of that
tmp = n * 8;
tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
lo = parseInt(tmp[2], 16);
hi = parseInt(tmp[1], 16) || 0;
tail[14] = lo;
tail[15] = hi;
md5cycle(state, tail);
return state;
},
md51_array = function (a) {
var n = a.length,
state = [1732584193, -271733879, -1732584194, 271733878],
i,
length,
tail,
tmp,
lo,
hi;
for (i = 64; i <= n; i += 64) {
md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
}
// Not sure if it is a bug, however IE10 will always produce a sub array of length 1
// containing the last element of the parent array if the sub array specified starts
// beyond the length of the parent array - weird.
// https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue
a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
length = a.length;
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= a[i] << ((i % 4) << 3);
}
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i = 0; i < 16; i += 1) {
tail[i] = 0;
}
}
// Beware that the final length might not fit in 32 bits so we take care of that
tmp = n * 8;
tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
lo = parseInt(tmp[2], 16);
hi = parseInt(tmp[1], 16) || 0;
tail[14] = lo;
tail[15] = hi;
md5cycle(state, tail);
return state;
},
hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'],
rhex = function (n) {
var s = '',
j;
for (j = 0; j < 4; j += 1) {
s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
}
return s;
},
hex = function (x) {
var i;
for (i = 0; i < x.length; i += 1) {
x[i] = rhex(x[i]);
}
return x.join('');
},
md5 = function (s) {
return hex(md51(s));
},
////////////////////////////////////////////////////////////////////////////
/**
* SparkMD5 OOP implementation.
*
* Use this class to perform an incremental md5, otherwise use the
* static methods instead.
*/
SparkMD5 = function () {
// call reset to init the instance
this.reset();
};
// In some cases the fast add32 function cannot be used..
if (md5('hello') !== '5d41402abc4b2a76b9719d911017c592') {
add32 = function (x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF),
msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
};
}
/**
* Appends a string.
* A conversion will be applied if an utf8 string is detected.
*
* @param {String} str The string to be appended
*
* @return {SparkMD5} The instance itself
*/
SparkMD5.prototype.append = function (str) {
// converts the string to utf8 bytes if necessary
if (/[\u0080-\uFFFF]/.test(str)) {
str = unescape(encodeURIComponent(str));
}
// then append as binary
this.appendBinary(str);
return this;
};
/**
* Appends a binary string.
*
* @param {String} contents The binary string to be appended
*
* @return {SparkMD5} The instance itself
*/
SparkMD5.prototype.appendBinary = function (contents) {
this._buff += contents;
this._length += contents.length;
var length = this._buff.length,
i;
for (i = 64; i <= length; i += 64) {
md5cycle(this._state, md5blk(this._buff.substring(i - 64, i)));
}
this._buff = this._buff.substr(i - 64);
return this;
};
/**
* Finishes the incremental computation, reseting the internal state and
* returning the result.
* Use the raw parameter to obtain the raw result instead of the hex one.
*
* @param {Boolean} raw True to get the raw result, false to get the hex result
*
* @return {String|Array} The result
*/
SparkMD5.prototype.end = function (raw) {
var buff = this._buff,
length = buff.length,
i,
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
ret;
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
}
this._finish(tail, length);
ret = !!raw ? this._state : hex(this._state);
this.reset();
return ret;
};
/**
* Finish the final calculation based on the tail.
*
* @param {Array} tail The tail (will be modified)
* @param {Number} length The length of the remaining buffer
*/
SparkMD5.prototype._finish = function (tail, length) {
var i = length,
tmp,
lo,
hi;
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(this._state, tail);
for (i = 0; i < 16; i += 1) {
tail[i] = 0;
}
}
// Do the final computation based on the tail and length
// Beware that the final length may not fit in 32 bits so we take care of that
tmp = this._length * 8;
tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
lo = parseInt(tmp[2], 16);
hi = parseInt(tmp[1], 16) || 0;
tail[14] = lo;
tail[15] = hi;
md5cycle(this._state, tail);
};
/**
* Resets the internal state of the computation.
*
* @return {SparkMD5} The instance itself
*/
SparkMD5.prototype.reset = function () {
this._buff = "";
this._length = 0;
this._state = [1732584193, -271733879, -1732584194, 271733878];
return this;
};
/**
* Releases memory used by the incremental buffer and other aditional
* resources. If you plan to use the instance again, use reset instead.
*/
SparkMD5.prototype.destroy = function () {
delete this._state;
delete this._buff;
delete this._length;
};
/**
* Performs the md5 hash on a string.
* A conversion will be applied if utf8 string is detected.
*
* @param {String} str The string
* @param {Boolean} raw True to get the raw result, false to get the hex result
*
* @return {String|Array} The result
*/
SparkMD5.hash = function (str, raw) {
// converts the string to utf8 bytes if necessary
if (/[\u0080-\uFFFF]/.test(str)) {
str = unescape(encodeURIComponent(str));
}
var hash = md51(str);
return !!raw ? hash : hex(hash);
};
/**
* Performs the md5 hash on a binary string.
*
* @param {String} content The binary string
* @param {Boolean} raw True to get the raw result, false to get the hex result
*
* @return {String|Array} The result
*/
SparkMD5.hashBinary = function (content, raw) {
var hash = md51(content);
return !!raw ? hash : hex(hash);
};
/**
* SparkMD5 OOP implementation for array buffers.
*
* Use this class to perform an incremental md5 ONLY for array buffers.
*/
SparkMD5.ArrayBuffer = function () {
// call reset to init the instance
this.reset();
};
////////////////////////////////////////////////////////////////////////////
/**
* Appends an array buffer.
*
* @param {ArrayBuffer} arr The array to be appended
*
* @return {SparkMD5.ArrayBuffer} The instance itself
*/
SparkMD5.ArrayBuffer.prototype.append = function (arr) {
// TODO: we could avoid the concatenation here but the algorithm would be more complex
// if you find yourself needing extra performance, please make a PR.
var buff = this._concatArrayBuffer(this._buff, arr),
length = buff.length,
i;
this._length += arr.byteLength;
for (i = 64; i <= length; i += 64) {
md5cycle(this._state, md5blk_array(buff.subarray(i - 64, i)));
}
// Avoids IE10 weirdness (documented above)
this._buff = (i - 64) < length ? buff.subarray(i - 64) : new Uint8Array(0);
return this;
};
/**
* Finishes the incremental computation, reseting the internal state and
* returning the result.
* Use the raw parameter to obtain the raw result instead of the hex one.
*
* @param {Boolean} raw True to get the raw result, false to get the hex result
*
* @return {String|Array} The result
*/
SparkMD5.ArrayBuffer.prototype.end = function (raw) {
var buff = this._buff,
length = buff.length,
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
i,
ret;
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= buff[i] << ((i % 4) << 3);
}
this._finish(tail, length);
ret = !!raw ? this._state : hex(this._state);
this.reset();
return ret;
};
SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
/**
* Resets the internal state of the computation.
*
* @return {SparkMD5.ArrayBuffer} The instance itself
*/
SparkMD5.ArrayBuffer.prototype.reset = function () {
this._buff = new Uint8Array(0);
this._length = 0;
this._state = [1732584193, -271733879, -1732584194, 271733878];
return this;
};
/**
* Releases memory used by the incremental buffer and other aditional
* resources. If you plan to use the instance again, use reset instead.
*/
SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
/**
* Concats two array buffers, returning a new one.
*
* @param {ArrayBuffer} first The first array buffer
* @param {ArrayBuffer} second The second array buffer
*
* @return {ArrayBuffer} The new array buffer
*/
SparkMD5.ArrayBuffer.prototype._concatArrayBuffer = function (first, second) {
var firstLength = first.length,
result = new Uint8Array(firstLength + second.byteLength);
result.set(first);
result.set(new Uint8Array(second), firstLength);
return result;
};
/**
* Performs the md5 hash on an array buffer.
*
* @param {ArrayBuffer} arr The array buffer
* @param {Boolean} raw True to get the raw result, false to get the hex result
*
* @return {String|Array} The result
*/
SparkMD5.ArrayBuffer.hash = function (arr, raw) {
var hash = md51_array(new Uint8Array(arr));
return !!raw ? hash : hex(hash);
};
return FlashRuntime.register( 'Md5', {
init: function() {
// do nothing.
},
loadFromBlob: function( file ) {
var blob = file.getSource(),
chunkSize = 2 * 1024 * 1024,
chunks = Math.ceil( blob.size / chunkSize ),
chunk = 0,
owner = this.owner,
spark = new SparkMD5.ArrayBuffer(),
me = this,
blobSlice = blob.mozSlice || blob.webkitSlice || blob.slice,
loadNext, fr;
fr = new FileReader();
loadNext = function() {
var start, end;
start = chunk * chunkSize;
end = Math.min( start + chunkSize, blob.size );
fr.onload = function( e ) {
spark.append( e.target.result );
owner.trigger( 'progress', {
total: file.size,
loaded: end
});
};
fr.onloadend = function() {
fr.onloadend = fr.onload = null;
if ( ++chunk < chunks ) {
setTimeout( loadNext, 1 );
} else {
setTimeout(function(){
owner.trigger('load');
me.result = spark.end();
loadNext = file = blob = spark = null;
owner.trigger('complete');
}, 50 );
}
};
fr.readAsArrayBuffer( blobSlice.call( blob, start, end ) );
};
loadNext();
},
getResult: function() {
return this.result;
}
});
});
/**
* @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 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;
},
getResponseHeaders: function() {
// flash 暂不支持
return {};
},
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-'+status;
} else {
err = 'http-'+status;
}
if ( readBody ) {
me._response = xhr.exec('getResponse');
me._response = decodeURIComponent( me._response );
// flash 处理可能存在 bug, 没辙只能靠 js 了
// try {
// me._responseJson = xhr.exec('getResponseAsJson');
// } catch ( error ) {
p = function( s ) {
try {
if (window.JSON && window.JSON.parse) {
return JSON.parse(s);
}
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() {
var status = xhr.exec('getStatus'),err = status?'http-'+status:'http';
xhr.off();
me._xhr = null;
me.trigger( 'error', err );
});
me._xhr = xhr;
return xhr;
},
_setRequestHeader: function( xhr, headers ) {
$.each( headers, function( key, val ) {
xhr.exec( 'setRequestHeader', key, val );
});
}
});
});
/**
* @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( this.getRuid(), blob );
}
});
});
/**
* @fileOverview Md5 flash实现
*/
define('runtime/flash/md5',[
'runtime/flash/runtime'
], function( FlashRuntime ) {
return FlashRuntime.register( 'Md5', {
init: function() {
// do nothing.
},
loadFromBlob: function( blob ) {
return this.flashExec( 'Md5', 'loadFromBlob', blob.uid );
}
});
});
/**
* @fileOverview 完全版本。
*/
define('preset/all',[
'base',
// widgets
'widgets/filednd',
'widgets/filepaste',
'widgets/filepicker',
'widgets/image',
'widgets/queue',
'widgets/runtime',
'widgets/upload',
'widgets/validator',
'widgets/md5',
// runtimes
// html5
'runtime/html5/blob',
'runtime/html5/dnd',
'runtime/html5/filepaste',
'runtime/html5/filepicker',
'runtime/html5/imagemeta/exif',
'runtime/html5/androidpatch',
'runtime/html5/image',
'runtime/html5/transport',
'runtime/html5/md5',
// flash
'runtime/flash/filepicker',
'runtime/flash/image',
'runtime/flash/transport',
'runtime/flash/blob',
'runtime/flash/md5'
], function( Base ) {
return Base;
});
/**
* @fileOverview 日志组件,主要用来收集错误信息,可以帮助 webuploader 更好的定位问题和发展。
*
* 如果您不想要启用此功能,请在打包的时候去掉 log 模块。
*
* 或者可以在初始化的时候通过 options.disableWidgets 属性禁用。
*
* 如:
* WebUploader.create({
* ...
*
* disableWidgets: 'log',
*
* ...
* })
*/
define('widgets/log',[
'base',
'uploader',
'widgets/widget'
], function( Base, Uploader ) {
var $ = Base.$,
logUrl = ' http://static.tieba.baidu.com/tb/pms/img/st.gif??',
product = (location.hostname || location.host || 'protected').toLowerCase(),
// 只针对 baidu 内部产品用户做统计功能。
enable = product && /baidu/i.exec(product),
base;
if (!enable) {
return;
}
base = {
dv: 3,
master: 'webuploader',
online: /test/.exec(product) ? 0 : 1,
module: '',
product: product,
type: 0
};
function send(data) {
var obj = $.extend({}, base, data),
url = logUrl.replace(/^(.*)\?/, '$1' + $.param( obj )),
image = new Image();
image.src = url;
}
return Uploader.register({
name: 'log',
init: function() {
var owner = this.owner,
count = 0,
size = 0;
owner
.on('error', function(code) {
send({
type: 2,
c_error_code: code
});
})
.on('uploadError', function(file, reason) {
send({
type: 2,
c_error_code: 'UPLOAD_ERROR',
c_reason: '' + reason
});
})
.on('uploadComplete', function(file) {
count++;
size += file.size;
}).
on('uploadFinished', function() {
send({
c_count: count,
c_size: size
});
count = size = 0;
});
send({
c_usage: 1
});
}
});
});
/**
* @fileOverview Uploader上传类
*/
define('webuploader',[
'preset/all',
'widgets/log'
], function( preset ) {
return preset;
});
var _require = require;
return _require('webuploader');
});
================================================
FILE: dist/webuploader.flashonly.js
================================================
/*! WebUploader 0.1.8-alpha */
/**
* @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
* @require "jquery"
* @require "zepto"
*/
define('dollar-third',[],function() {
var req = window.require;
var $ = window.__dollar ||
window.jQuery ||
window.Zepto ||
req('jquery') ||
req('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.8-alpha',
/**
* @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 ||
file.lastModified && new Date(file.lastModified).toLocaleString() ||
(new Date()).toLocaleString();
Blob.apply( this, arguments );
}
return Base.inherits( Blob, File );
});
/**
* @fileOverview 错误信息
*/
define('lib/filepicker',[
'base',
'runtime/client',
'lib/file'
], function( Base, RuntimeClient, 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 );
RuntimeClient.call( this, 'FilePicker', true );
}
FilePicker.options = {
button: null,
container: null,
label: null,
innerHTML: null,
multiple: true,
accept: null,
name: 'file',
style: 'webuploader-pick' //pick element class attribute, default is "webuploader-pick"
};
Base.inherits( RuntimeClient, {
constructor: FilePicker,
init: function() {
var me = this,
opts = me.options,
button = opts.button,
style = opts.style;
if (style)
button.addClass('webuploader-pick');
me.on( 'all', function( type ) {
var files;
switch ( type ) {
case 'mouseenter':
if (style)
button.addClass('webuploader-pick-hover');
break;
case 'mouseleave':
if (style)
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(),
*/
width = button[0] && button[0].offsetWidth || button.outerWidth() || button.width(),
height = button[0] && button[0].offsetHeight || 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 {Array} [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.on('dialogopen', function() {
me.owner.trigger('dialogOpen', picker.button);
});
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.getAsDataUrl( opts.type ) );
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` 被移除的文件数。
* * `numOfInterrupt` 被中断的文件数。
* @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 ];
this._delFile(file);
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 );
});
}
},
_delFile : function(file){
for(var i = this._queue.length - 1 ; i >= 0 ; i-- ){
if(this._queue[i] == file){
this._queue.splice(i,1);
break;
}
}
},
_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 );
});
if ( files.length ) {
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();
},
getResponseHeaders: function() {
return this.exec('getResponseHeaders');
},
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 {Number} [chunkRetryDelay=1000]
* @namespace options
* @for Uploader
* @description 开启重试后,设置重试延时时间, 单位毫秒。默认1000毫秒,即1秒.
*/
chunkRetryDelay: 1000,
/**
* @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) {
file.setStatus( Status.QUEUED );
$.each( me.pool, function( _, v ) {
// 之前暂停过。
if (v.file !== file) {
return;
}
v.transport && v.transport.send();
file.setStatus( Status.PROGRESS );
});
} else if (file.getStatus() !== Status.PROGRESS) {
file.setStatus( Status.QUEUED );
}
} else {
$.each( me.request( 'get-files', [ Status.INITED ] ), function() {
this.setStatus( Status.QUEUED );
});
}
if ( me.runing ) {
me.owner.trigger('startUpload', file);// 开始上传或暂停恢复的,trigger event
return Base.nextTick( me.__tick );
}
me.runing = true;
var files = [];
// 如果有暂停的,则续传
file || $.each( me.pool, function( _, v ) {
var file = v.file;
if ( file.getStatus() === Status.INTERRUPT ) {
me._trigged = false;
files.push(file);
if (v.waiting) {
return;
}
// 文件 prepare 完后,如果暂停了,这个时候只会把文件插入 pool, 而不会创建 tranport,
v.transport ? v.transport.send() : me._doSend(v);
}
});
$.each(files, function() {
this.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) {
v.transport && v.transport.abort();
if (interrupt) {
me._putback(v);
me._popBlock(v);
}
}
});
me.owner.trigger('stopUpload', file);// 暂停,trigger event
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 );
},
/**
* 判断`Uploader`是否正在上传中。
* @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.remaning++;
block.file.remaning++;
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, 每个分片发送之前可能要做些异步的事情。
block.waiting = promise = me.request( 'before-send', block, function() {
delete block.waiting;
// 有可能文件已经上传出错了,所以不需要再传输了。
if ( file.getStatus() === Status.PROGRESS ) {
me._doSend( block );
} else if (block.file.getStatus() !== Status.INTERRUPT) {
me._popBlock(block);
}
Base.nextTick(me.__tick);
});
// 如果为fail了,则跳过此分片。
promise.fail(function() {
delete block.waiting;
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 = $.extend({}, me.options, block.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();
ret._headers = tr.getResponseHeaders();
block.response = ret;
fn = function( value ) {
reject = value;
};
// 服务端响应了,不代表成功了,询问是否响应正确。
if ( !owner.trigger( 'uploadAccept', block, ret, fn ) ) {
reject = reject || 'server';
}
return reject;
};
// 尝试重试,然后广播文件上传出错。
tr.on( 'error', function( type, flag ) {
// 在 runtime/html5/transport.js 上为 type 加上了状态码,形式:type|status|text(如:http-403-Forbidden)
// 这里把状态码解释出来,并还原后面代码所依赖的 type 变量
var typeArr = type.split( '|' ), status, statusText;
type = typeArr[0];
status = parseFloat( typeArr[1] ),
statusText = typeArr[2];
block.retried = block.retried || 0;
// 自动重试
if ( block.chunks > 1 && ~'http,abort,server'.indexOf( type.replace( /-.*/, '' ) ) &&
block.retried < opts.chunkRetry ) {
block.retried++;
me.retryTimer = setTimeout(function() {
tr.send();
}, opts.chunkRetryDelay || 1000);
} else {
// http status 500 ~ 600
if ( !flag && type === 'server' ) {
type = requestAccept( type );
}
file.setStatus( Status.ERROR, type );
owner.trigger( 'uploadError', file, type, status, statusText );
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 );
},
destroy: function() {
clearTimeout(this.retryTimer);
}
});
});
/**
* @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 ) {
// 增加beforeFileQueuedCheckfileNumLimit验证,主要为了再次加载时(已存在历史文件)验证数量是否超过设置项
if (!this.trigger('beforeFileQueuedCheckfileNumLimit', file,count)) {
return false;
}
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( this.getRuid(), 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;
},
getResponseHeaders: function() {
// flash 暂不支持
return {};
},
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-'+status;
} else {
err = 'http-'+status;
}
if ( readBody ) {
me._response = xhr.exec('getResponse');
me._response = decodeURIComponent( me._response );
// flash 处理可能存在 bug, 没辙只能靠 js 了
// try {
// me._responseJson = xhr.exec('getResponseAsJson');
// } catch ( error ) {
p = function( s ) {
try {
if (window.JSON && window.JSON.parse) {
return JSON.parse(s);
}
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() {
var status = xhr.exec('getStatus'),err = status?'http-'+status:'http';
xhr.off();
me._xhr = null;
me.trigger( 'error', err );
});
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');
});
================================================
FILE: dist/webuploader.html5nodepend.js
================================================
/*! WebUploader 0.1.8-alpha */
/**
* @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 jq-bridge 主要实现像jQuery一样的功能方法,可以替换成jQuery,
* 这里只实现了此组件所需的部分。
*
* **此文件的代码还不可用,还是直接用jquery吧**
* @beta
*/
define('dollar-builtin',[],function() {
var doc = window.document,
emptyArray = [],
slice = emptyArray.slice,
class2type = {},
hasOwn = class2type.hasOwnProperty,
toString = class2type.toString,
rId = /^#(.*)$/;
function each( obj, iterator ) {
var i;
//fix error, add guard here
if(!obj) {
return;
}
// like array
if ( typeof obj !== 'function' && typeof obj.length === 'number' ) {
for ( i = 0; i < obj.length; i++ ) {
if ( iterator.call( obj[ i ], i, obj[ i ] ) === false ) {
return obj;
}
}
} else {
for ( i in obj ) {
if ( hasOwn.call( obj, i ) && iterator.call( obj[ i ], i,
obj[ i ] ) === false ) {
return obj;
}
}
}
return obj;
}
function extend( target, source, deep ) {
each( source, function( key, val ) {
if ( deep && typeof val === 'object' ) {
if ( typeof target[ key ] !== 'object' ) {
target[ key ] = type( val ) === 'array' ? [] : {};
}
extend( target[ key ], val, deep );
} else {
target[ key ] = val;
}
});
}
each( ('Boolean Number String Function Array Date RegExp Object' +
' Error').split(' '), function( i, name ) {
class2type[ '[object ' + name + ']' ] = name.toLowerCase();
});
function setAttribute( node, name, value ) {
value == null ? node.removeAttribute( name ) :
node.setAttribute( name, value );
}
/**
* 只支持ID选择。
*/
function $( elem ) {
var api = {};
elem = typeof elem === 'string' && rId.test( elem ) ?
doc.getElementById( RegExp.$1 ) : elem;
if ( elem ) {
api[ 0 ] = elem;
api.length = 1;
}
return $.extend( api, {
_wrap: true,
get: function() {
return elem;
},
/**
* 添加className
*/
addClass: function( classname ) {
elem.classList.add( classname );
return this;
},
removeClass: function( classname ) {
elem.classList.remove( classname );
return this;
},
//fix error, $(...).each is used in the source
each: function(callback){
[].every.call(this, function(el, idx){
return callback.call(el, idx, el) !== false
})
return this
},
html: function( html ) {
if ( html ) {
elem.innerHTML = html;
}
return elem.innerHTML;
},
attr: function( key, val ) {
if ( $.isObject( key ) ) {
$.each( key, function( k, v ) {
setAttribute( elem, k, v );
});
} else {
setAttribute( elem, key, val );
}
},
empty: function() {
elem.innerHTML = '';
return this;
},
before: function( el ) {
elem.parentNode.insertBefore( el, elem );
},
append: function( el ) {
el = el._wrap ? el.get() : el;
elem.appendChild( el );
},
text: function() {
return elem.textContent;
},
// on
on: function( type, fn ) {
if ( elem.addEventListener ) {
elem.addEventListener( type, fn, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( 'on' + type, fn );
}
return this;
},
// off
off: function( type, fn ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, fn, false );
} else if ( elem.attachEvent ) {
elem.detachEvent( 'on' + type, fn );
}
return this;
}
});
}
$.each = each;
$.extend = function( /*[deep, ]*/target/*, source...*/ ) {
var args = slice.call( arguments, 1 ),
deep;
if ( typeof target === 'boolean' ) {
deep = target;
target = args.shift();
}
args.forEach(function( arg ) {
arg && extend( target, arg, deep );
});
return target;
};
function type( obj ) {
/*jshint eqnull:true*/
return obj == null ? String( obj ) :
class2type[ toString.call( obj ) ] || 'object';
}
$.type = type;
//fix error, $.grep is used in the source
$.grep = function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
}
$.isWindow = function( obj ) {
return obj && obj.window === obj;
};
$.isPlainObject = function( obj ) {
if ( type( obj ) !== 'object' || obj.nodeType || $.isWindow( obj ) ) {
return false;
}
try {
if ( obj.constructor && !hasOwn.call( obj.constructor.prototype,
'isPrototypeOf' ) ) {
return false;
}
} catch ( ex ) {
return false;
}
return true;
};
$.isObject = function( anything ) {
return type( anything ) === 'object';
};
$.trim = function( str ) {
return str ? str.trim() : '';
};
$.isFunction = function( obj ) {
return type( obj ) === 'function';
};
emptyArray = null;
return $;
});
define('dollar',[
'dollar-builtin'
], function( $ ) {
return $;
});
/**
* 直接来源于jquery的代码。
* @fileOverview Promise/A+
* @beta
*/
define('promise-builtin',[
'dollar'
], function( $ ) {
var api;
// 简单版Callbacks, 默认memory,可选once.
function Callbacks( once ) {
var list = [],
stack = !once && [],
fire = function( data ) {
memory = data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
list[ firingIndex ].apply( data[ 0 ], data[ 1 ] );
}
firing = false;
if ( list ) {
if ( stack ) {
stack.length && fire( stack.shift() );
} else {
list = [];
}
}
},
self = {
add: function() {
if ( list ) {
var start = list.length;
(function add ( args ) {
$.each( args, function( _, arg ) {
var type = $.type( arg );
if ( type === 'function' ) {
list.push( arg );
} else if ( arg && arg.length &&
type !== 'string' ) {
add( arg );
}
});
})( arguments );
if ( firing ) {
firingLength = list.length;
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
disable: function() {
list = stack = memory = undefined;
return this;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
fireWith: function( context, args ) {
if ( list && (!fired || stack) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
fire: function() {
self.fireWith( this, arguments );
return this;
}
},
fired, firing, firingStart, firingLength, firingIndex, memory;
return self;
}
function Deferred( func ) {
var tuples = [
// action, add listener, listener list, final state
[ 'resolve', 'done', Callbacks( true ), 'resolved' ],
[ 'reject', 'fail', Callbacks( true ), 'rejected' ],
[ 'notify', 'progress', Callbacks() ]
],
state = 'pending',
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return Deferred(function( newDefer ) {
$.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = $.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for
// forwarding actions to newDefer
deferred[ tuple[ 1 ] ](function() {
var returned;
returned = fn && fn.apply( this, arguments );
if ( returned &&
$.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + 'With' ](
this === promise ?
newDefer.promise() :
this,
fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? $.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
$.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[ 1 ] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[ 0 ] ] = function() {
deferred[ tuple[ 0 ] + 'With' ]( this === deferred ? promise :
this, arguments );
return this;
};
deferred[ tuple[ 0 ] + 'With' ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
}
api = {
/**
* 创建一个[Deferred](http://api.jquery.com/category/deferred-object/)对象。
* 详细的Deferred用法说明,请参照jQuery的API文档。
*
* Deferred对象在钩子回掉函数中经常要用到,用来处理需要等待的异步操作。
*
* @for Base
* @method Deferred
* @grammar Base.Deferred() => Deferred
* @example
* // 在文件开始发送前做些异步操作。
* // WebUploader会等待此异步操作完成后,开始发送文件。
* Uploader.register({
* 'before-send-file': 'doSomthingAsync'
* }, {
*
* doSomthingAsync: function() {
* var deferred = Base.Deferred();
*
* // 模拟一次异步操作。
* setTimeout(deferred.resolve, 2000);
*
* return deferred.promise();
* }
* });
*/
Deferred: Deferred,
/**
* 判断传入的参数是否为一个promise对象。
* @method isPromise
* @grammar Base.isPromise( anything ) => Boolean
* @param {*} anything 检测对象。
* @return {Boolean}
* @for Base
* @example
* console.log( Base.isPromise() ); // => false
* console.log( Base.isPromise({ key: '123' }) ); // => false
* console.log( Base.isPromise( Base.Deferred().promise() ) ); // => true
*
* // Deferred也是一个Promise
* console.log( Base.isPromise( Base.Deferred() ) ); // => true
*/
isPromise: function( anything ) {
return anything && typeof anything.then === 'function';
},
/**
* 返回一个promise,此promise在所有传入的promise都完成了后完成。
* 详细请查看[这里](http://api.jquery.com/jQuery.when/)。
*
* @method when
* @for Base
* @grammar Base.when( promise1[, promise2[, promise3...]] ) => Promise
*/
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
slice = [].slice,
resolveValues = slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || (subordinate &&
$.isFunction( subordinate.promise )) ? length : 0,
// the master Deferred. If resolveValues consist of
// only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ?
slice.call( arguments ) : value;
if ( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !(--remaining) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] &&
$.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts,
resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts,
progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
};
return api;
});
define('promise',[
'promise-builtin'
], 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.8-alpha',
/**
* @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 错误信息
*/
define('lib/dnd',[
'base',
'mediator',
'runtime/client'
], function( Base, Mediator, RuntimeClent ) {
var $ = Base.$;
function DragAndDrop( opts ) {
opts = this.options = $.extend({}, DragAndDrop.options, opts );
opts.container = $( opts.container );
if ( !opts.container.length ) {
return;
}
RuntimeClent.call( this, 'DragAndDrop' );
}
DragAndDrop.options = {
accept: null,
disableGlobalDnd: false
};
Base.inherits( RuntimeClent, {
constructor: DragAndDrop,
init: function() {
var me = this;
me.connectRuntime( me.options, function() {
me.exec('init');
me.trigger('ready');
});
}
});
Mediator.installTo( DragAndDrop.prototype );
return DragAndDrop;
});
/**
* @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 DragAndDrop Widget。
*/
define('widgets/filednd',[
'base',
'uploader',
'lib/dnd',
'widgets/widget'
], function( Base, Uploader, Dnd ) {
var $ = Base.$;
Uploader.options.dnd = '';
/**
* @property {Selector} [dnd=undefined] 指定Drag And Drop拖拽的容器,如果不指定,则不启动。
* @namespace options
* @for Uploader
*/
/**
* @property {Selector} [disableGlobalDnd=false] 是否禁掉整个页面的拖拽功能,如果不禁用,图片拖进来的时候会默认被浏览器打开。
* @namespace options
* @for Uploader
*/
/**
* @event dndAccept
* @param {DataTransferItemList} items DataTransferItem
* @description 阻止此事件可以拒绝某些类型的文件拖入进来。目前只有 chrome 提供这样的 API,且只能通过 mime-type 验证。
* @for Uploader
*/
return Uploader.register({
name: 'dnd',
init: function( opts ) {
if ( !opts.dnd ||
this.request('predict-runtime-type') !== 'html5' ) {
return;
}
var me = this,
deferred = Base.Deferred(),
options = $.extend({}, {
disableGlobalDnd: opts.disableGlobalDnd,
container: opts.dnd,
accept: opts.accept
}),
dnd;
this.dnd = dnd = new Dnd( options );
dnd.once( 'ready', deferred.resolve );
dnd.on( 'drop', function( files ) {
me.request( 'add-file', [ files ]);
});
// 检测文件是否全部允许添加。
dnd.on( 'accept', function( items ) {
return me.owner.trigger( 'dndAccept', items );
});
dnd.init();
return deferred.promise();
},
destroy: function() {
this.dnd && this.dnd.destroy();
}
});
});
/**
* @fileOverview 错误信息
*/
define('lib/filepaste',[
'base',
'mediator',
'runtime/client'
], function( Base, Mediator, RuntimeClent ) {
var $ = Base.$;
function FilePaste( opts ) {
opts = this.options = $.extend({}, opts );
opts.container = $( opts.container || document.body );
RuntimeClent.call( this, 'FilePaste' );
}
Base.inherits( RuntimeClent, {
constructor: FilePaste,
init: function() {
var me = this;
me.connectRuntime( me.options, function() {
me.exec('init');
me.trigger('ready');
});
}
});
Mediator.installTo( FilePaste.prototype );
return FilePaste;
});
/**
* @fileOverview 组件基类。
*/
define('widgets/filepaste',[
'base',
'uploader',
'lib/filepaste',
'widgets/widget'
], function( Base, Uploader, FilePaste ) {
var $ = Base.$;
/**
* @property {Selector} [paste=undefined] 指定监听paste事件的容器,如果不指定,不启用此功能。此功能为通过粘贴来添加截屏的图片。建议设置为`document.body`.
* @namespace options
* @for Uploader
*/
return Uploader.register({
name: 'paste',
init: function( opts ) {
if ( !opts.paste ||
this.request('predict-runtime-type') !== 'html5' ) {
return;
}
var me = this,
deferred = Base.Deferred(),
options = $.extend({}, {
container: opts.paste,
accept: opts.accept
}),
paste;
this.paste = paste = new FilePaste( options );
paste.once( 'ready', deferred.resolve );
paste.on( 'paste', function( files ) {
me.owner.request( 'add-file', [ files ]);
});
paste.init();
return deferred.promise();
},
destroy: function() {
this.paste && this.paste.destroy();
}
});
});
/**
* @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 ||
file.lastModified && new Date(file.lastModified).toLocaleString() ||
(new Date()).toLocaleString();
Blob.apply( this, arguments );
}
return Base.inherits( Blob, File );
});
/**
* @fileOverview 错误信息
*/
define('lib/filepicker',[
'base',
'runtime/client',
'lib/file'
], function( Base, RuntimeClient, 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 );
RuntimeClient.call( this, 'FilePicker', true );
}
FilePicker.options = {
button: null,
container: null,
label: null,
innerHTML: null,
multiple: true,
accept: null,
name: 'file',
style: 'webuploader-pick' //pick element class attribute, default is "webuploader-pick"
};
Base.inherits( RuntimeClient, {
constructor: FilePicker,
init: function() {
var me = this,
opts = me.options,
button = opts.button,
style = opts.style;
if (style)
button.addClass('webuploader-pick');
me.on( 'all', function( type ) {
var files;
switch ( type ) {
case 'mouseenter':
if (style)
button.addClass('webuploader-pick-hover');
break;
case 'mouseleave':
if (style)
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(),
*/
width = button[0] && button[0].offsetWidth || button.outerWidth() || button.width(),
height = button[0] && button[0].offsetHeight || 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/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 {Array} [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.on('dialogopen', function() {
me.owner.trigger('dialogOpen', picker.button);
});
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.getAsDataUrl( opts.type ) );
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` 被移除的文件数。
* * `numOfInterrupt` 被中断的文件数。
* @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 ];
this._delFile(file);
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 );
});
}
},
_delFile : function(file){
for(var i = this._queue.length - 1 ; i >= 0 ; i-- ){
if(this._queue[i] == file){
this._queue.splice(i,1);
break;
}
}
},
_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 );
});
if ( files.length ) {
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();
},
getResponseHeaders: function() {
return this.exec('getResponseHeaders');
},
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 {Number} [chunkRetryDelay=1000]
* @namespace options
* @for Uploader
* @description 开启重试后,设置重试延时时间, 单位毫秒。默认1000毫秒,即1秒.
*/
chunkRetryDelay: 1000,
/**
* @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) {
file.setStatus( Status.QUEUED );
$.each( me.pool, function( _, v ) {
// 之前暂停过。
if (v.file !== file) {
return;
}
v.transport && v.transport.send();
file.setStatus( Status.PROGRESS );
});
} else if (file.getStatus() !== Status.PROGRESS) {
file.setStatus( Status.QUEUED );
}
} else {
$.each( me.request( 'get-files', [ Status.INITED ] ), function() {
this.setStatus( Status.QUEUED );
});
}
if ( me.runing ) {
me.owner.trigger('startUpload', file);// 开始上传或暂停恢复的,trigger event
return Base.nextTick( me.__tick );
}
me.runing = true;
var files = [];
// 如果有暂停的,则续传
file || $.each( me.pool, function( _, v ) {
var file = v.file;
if ( file.getStatus() === Status.INTERRUPT ) {
me._trigged = false;
files.push(file);
if (v.waiting) {
return;
}
// 文件 prepare 完后,如果暂停了,这个时候只会把文件插入 pool, 而不会创建 tranport,
v.transport ? v.transport.send() : me._doSend(v);
}
});
$.each(files, function() {
this.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) {
v.transport && v.transport.abort();
if (interrupt) {
me._putback(v);
me._popBlock(v);
}
}
});
me.owner.trigger('stopUpload', file);// 暂停,trigger event
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 );
},
/**
* 判断`Uploader`是否正在上传中。
* @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.remaning++;
block.file.remaning++;
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, 每个分片发送之前可能要做些异步的事情。
block.waiting = promise = me.request( 'before-send', block, function() {
delete block.waiting;
// 有可能文件已经上传出错了,所以不需要再传输了。
if ( file.getStatus() === Status.PROGRESS ) {
me._doSend( block );
} else if (block.file.getStatus() !== Status.INTERRUPT) {
me._popBlock(block);
}
Base.nextTick(me.__tick);
});
// 如果为fail了,则跳过此分片。
promise.fail(function() {
delete block.waiting;
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 = $.extend({}, me.options, block.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();
ret._headers = tr.getResponseHeaders();
block.response = ret;
fn = function( value ) {
reject = value;
};
// 服务端响应了,不代表成功了,询问是否响应正确。
if ( !owner.trigger( 'uploadAccept', block, ret, fn ) ) {
reject = reject || 'server';
}
return reject;
};
// 尝试重试,然后广播文件上传出错。
tr.on( 'error', function( type, flag ) {
// 在 runtime/html5/transport.js 上为 type 加上了状态码,形式:type|status|text(如:http-403-Forbidden)
// 这里把状态码解释出来,并还原后面代码所依赖的 type 变量
var typeArr = type.split( '|' ), status, statusText;
type = typeArr[0];
status = parseFloat( typeArr[1] ),
statusText = typeArr[2];
block.retried = block.retried || 0;
// 自动重试
if ( block.chunks > 1 && ~'http,abort,server'.indexOf( type.replace( /-.*/, '' ) ) &&
block.retried < opts.chunkRetry ) {
block.retried++;
me.retryTimer = setTimeout(function() {
tr.send();
}, opts.chunkRetryDelay || 1000);
} else {
// http status 500 ~ 600
if ( !flag && type === 'server' ) {
type = requestAccept( type );
}
file.setStatus( Status.ERROR, type );
owner.trigger( 'uploadError', file, type, status, statusText );
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 );
},
destroy: function() {
clearTimeout(this.retryTimer);
}
});
});
/**
* @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 ) {
// 增加beforeFileQueuedCheckfileNumLimit验证,主要为了再次加载时(已存在历史文件)验证数量是否超过设置项
if (!this.trigger('beforeFileQueuedCheckfileNumLimit', file,count)) {
return false;
}
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 Html5Runtime
*/
define('runtime/html5/runtime',[
'base',
'runtime/runtime',
'runtime/compbase'
], function( Base, Runtime, CompBase ) {
var type = 'html5',
components = {};
function Html5Runtime() {
var pool = {},
me = this,
destroy = this.destroy;
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;
if ( components[ comp ] ) {
instance = pool[ uid ] = pool[ uid ] ||
new components[ comp ]( client, me );
if ( instance[ fn ] ) {
return instance[ fn ].apply( instance, args );
}
}
};
me.destroy = function() {
// @todo 删除池子中的所有实例
return destroy && destroy.apply( this, arguments );
};
}
Base.inherits( Runtime, {
constructor: Html5Runtime,
// 不需要连接其他程序,直接执行callback
init: function() {
var me = this;
setTimeout(function() {
me.trigger('ready');
}, 1 );
}
});
// 注册Components
Html5Runtime.register = function( name, component ) {
var klass = components[ name ] = Base.inherits( CompBase, component );
return klass;
};
// 注册html5运行时。
// 只有在支持的前提下注册。
if ( window.Blob && window.FileReader && window.DataView ) {
Runtime.addRuntime( type, Html5Runtime );
}
return Html5Runtime;
});
/**
* @fileOverview Blob Html实现
*/
define('runtime/html5/blob',[
'runtime/html5/runtime',
'lib/blob'
], function( Html5Runtime, Blob ) {
return Html5Runtime.register( 'Blob', {
slice: function( start, end ) {
var blob = this.owner.source,
slice = blob.slice || blob.webkitSlice || blob.mozSlice;
blob = slice.call( blob, start, end );
return new Blob( this.getRuid(), blob );
}
});
});
/**
* @fileOverview FilePaste
*/
define('runtime/html5/dnd',[
'base',
'runtime/html5/runtime',
'lib/file'
], function( Base, Html5Runtime, File ) {
var $ = Base.$,
prefix = 'webuploader-dnd-';
return Html5Runtime.register( 'DragAndDrop', {
init: function() {
var elem = this.elem = this.options.container;
this.dragEnterHandler = Base.bindFn( this._dragEnterHandler, this );
this.dragOverHandler = Base.bindFn( this._dragOverHandler, this );
this.dragLeaveHandler = Base.bindFn( this._dragLeaveHandler, this );
this.dropHandler = Base.bindFn( this._dropHandler, this );
this.dndOver = false;
elem.on( 'dragenter', this.dragEnterHandler );
elem.on( 'dragover', this.dragOverHandler );
elem.on( 'dragleave', this.dragLeaveHandler );
elem.on( 'drop', this.dropHandler );
if ( this.options.disableGlobalDnd ) {
$( document ).on( 'dragover', this.dragOverHandler );
$( document ).on( 'drop', this.dropHandler );
}
},
_dragEnterHandler: function( e ) {
var me = this,
denied = me._denied || false,
items;
e = e.originalEvent || e;
if ( !me.dndOver ) {
me.dndOver = true;
// 注意只有 chrome 支持。
items = e.dataTransfer.items;
if ( items && items.length ) {
me._denied = denied = !me.trigger( 'accept', items );
}
me.elem.addClass( prefix + 'over' );
me.elem[ denied ? 'addClass' :
'removeClass' ]( prefix + 'denied' );
}
e.dataTransfer.dropEffect = denied ? 'none' : 'copy';
return false;
},
_dragOverHandler: function( e ) {
// 只处理框内的。
var parentElem = this.elem.parent().get( 0 );
if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) {
return false;
}
clearTimeout( this._leaveTimer );
this._dragEnterHandler.call( this, e );
return false;
},
_dragLeaveHandler: function() {
var me = this,
handler;
handler = function() {
me.dndOver = false;
me.elem.removeClass( prefix + 'over ' + prefix + 'denied' );
};
clearTimeout( me._leaveTimer );
me._leaveTimer = setTimeout( handler, 100 );
return false;
},
_dropHandler: function( e ) {
var me = this,
ruid = me.getRuid(),
parentElem = me.elem.parent().get( 0 ),
dataTransfer, data;
// 只处理框内的。
if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) {
return false;
}
e = e.originalEvent || e;
dataTransfer = e.dataTransfer;
// 如果是页面内拖拽,还不能处理,不阻止事件。
// 此处 ie11 下会报参数错误,
try {
data = dataTransfer.getData('text/html');
} catch( err ) {
}
me.dndOver = false;
me.elem.removeClass( prefix + 'over' );
if ( !dataTransfer || data ) {
return;
}
me._getTansferFiles( dataTransfer, function( results ) {
me.trigger( 'drop', $.map( results, function( file ) {
return new File( ruid, file );
}) );
});
return false;
},
// 如果传入 callback 则去查看文件夹,否则只管当前文件夹。
_getTansferFiles: function( dataTransfer, callback ) {
var results = [],
promises = [],
items, files, file, item, i, len, canAccessFolder;
items = dataTransfer.items;
files = dataTransfer.files;
canAccessFolder = !!(items && items[ 0 ].webkitGetAsEntry);
for ( i = 0, len = files.length; i < len; i++ ) {
file = files[ i ];
item = items && items[ i ];
if ( canAccessFolder && item.webkitGetAsEntry().isDirectory ) {
promises.push( this._traverseDirectoryTree(
item.webkitGetAsEntry(), results ) );
} else {
results.push( file );
}
}
Base.when.apply( Base, promises ).done(function() {
if ( !results.length ) {
return;
}
callback( results );
});
},
_traverseDirectoryTree: function( entry, results ) {
var deferred = Base.Deferred(),
me = this;
if ( entry.isFile ) {
entry.file(function( file ) {
results.push( file );
deferred.resolve();
});
} else if ( entry.isDirectory ) {
entry.createReader().readEntries(function( entries ) {
var len = entries.length,
promises = [],
arr = [], // 为了保证顺序。
i;
for ( i = 0; i < len; i++ ) {
promises.push( me._traverseDirectoryTree(
entries[ i ], arr ) );
}
Base.when.apply( Base, promises ).then(function() {
results.push.apply( results, arr );
deferred.resolve();
}, deferred.reject );
});
}
return deferred.promise();
},
destroy: function() {
var elem = this.elem;
// 还没 init 就调用 destroy
if (!elem) {
return;
}
elem.off( 'dragenter', this.dragEnterHandler );
elem.off( 'dragover', this.dragOverHandler );
elem.off( 'dragleave', this.dragLeaveHandler );
elem.off( 'drop', this.dropHandler );
if ( this.options.disableGlobalDnd ) {
$( document ).off( 'dragover', this.dragOverHandler );
$( document ).off( 'drop', this.dropHandler );
}
}
});
});
/**
* @fileOverview FilePaste
*/
define('runtime/html5/filepaste',[
'base',
'runtime/html5/runtime',
'lib/file'
], function( Base, Html5Runtime, File ) {
return Html5Runtime.register( 'FilePaste', {
init: function() {
var opts = this.options,
elem = this.elem = opts.container,
accept = '.*',
arr, i, len, item;
// accetp的mimeTypes中生成匹配正则。
if ( opts.accept ) {
arr = [];
for ( i = 0, len = opts.accept.length; i < len; i++ ) {
item = opts.accept[ i ].mimeTypes;
item && arr.push( item );
}
if ( arr.length ) {
accept = arr.join(',');
accept = accept.replace( /,/g, '|' ).replace( /\*/g, '.*' );
}
}
this.accept = accept = new RegExp( accept, 'i' );
this.hander = Base.bindFn( this._pasteHander, this );
elem.on( 'paste', this.hander );
},
_pasteHander: function( e ) {
var allowed = [],
ruid = this.getRuid(),
items, item, blob, i, len;
e = e.originalEvent || e;
items = e.clipboardData.items;
for ( i = 0, len = items.length; i < len; i++ ) {
item = items[ i ];
if ( item.kind !== 'file' || !(blob = item.getAsFile()) ) {
continue;
}
allowed.push( new File( ruid, blob ) );
}
if ( allowed.length ) {
// 不阻止非文件粘贴(文字粘贴)的事件冒泡
e.preventDefault();
e.stopPropagation();
this.trigger( 'paste', allowed );
}
},
destroy: function() {
this.elem.off( 'paste', this.hander );
}
});
});
/**
* @fileOverview FilePicker
*/
define('runtime/html5/filepicker',[
'base',
'runtime/html5/runtime'
], function( Base, Html5Runtime ) {
var $ = Base.$;
return Html5Runtime.register( 'FilePicker', {
init: function() {
var container = this.getRuntime().getContainer(),
me = this,
owner = me.owner,
opts = me.options,
label = this.label = $( document.createElement('label') ),
input = this.input = $( document.createElement('input') ),
arr, i, len, mouseHandler, changeHandler;
input.attr( 'type', 'file' );
input.attr( 'capture', 'camera');
input.attr( 'name', opts.name );
input.addClass('webuploader-element-invisible');
label.on( 'click', function(e) {
input.trigger('click');
e.stopPropagation();
owner.trigger('dialogopen');
});
label.css({
opacity: 0,
width: '100%',
height: '100%',
display: 'block',
cursor: 'pointer',
background: '#ffffff'
});
if ( opts.multiple ) {
input.attr( 'multiple', 'multiple' );
}
// @todo Firefox不支持单独指定后缀
if ( opts.accept && opts.accept.length > 0 ) {
arr = [];
for ( i = 0, len = opts.accept.length; i < len; i++ ) {
arr.push( opts.accept[ i ].mimeTypes );
}
input.attr( 'accept', arr.join(',') );
}
container.append( input );
container.append( label );
mouseHandler = function( e ) {
owner.trigger( e.type );
};
changeHandler = function( e ) {
var clone;
// 解决chrome 56 第二次打开文件选择器,然后点击取消,依然会触发change事件的问题
if (e.target.files.length === 0){
return false;
}
// 第一次上传图片后,第二次再点击弹出文件选择器窗,等待
me.files = e.target.files;
// reset input
clone = this.cloneNode( true );
clone.value = null;
this.parentNode.replaceChild( clone, this );
input.off();
input = $( clone ).on( 'change', changeHandler )
.on( 'mouseenter mouseleave', mouseHandler );
owner.trigger('change');
}
input.on( 'change', changeHandler);
label.on( 'mouseenter mouseleave', mouseHandler );
},
getFiles: function() {
return this.files;
},
destroy: function() {
this.input.off();
this.label.off();
}
});
});
/**
* Terms:
*
* Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
* @fileOverview Image控件
*/
define('runtime/html5/util',[
'base'
], function( Base ) {
var urlAPI = window.createObjectURL && window ||
window.URL && URL.revokeObjectURL && URL ||
window.webkitURL,
createObjectURL = Base.noop,
revokeObjectURL = createObjectURL;
if ( urlAPI ) {
// 更安全的方式调用,比如android里面就能把context改成其他的对象。
createObjectURL = function() {
return urlAPI.createObjectURL.apply( urlAPI, arguments );
};
revokeObjectURL = function() {
return urlAPI.revokeObjectURL.apply( urlAPI, arguments );
};
}
return {
createObjectURL: createObjectURL,
revokeObjectURL: revokeObjectURL,
dataURL2Blob: function( dataURI ) {
var byteStr, intArray, ab, i, mimetype, parts;
parts = dataURI.split(',');
if ( ~parts[ 0 ].indexOf('base64') ) {
byteStr = atob( parts[ 1 ] );
} else {
byteStr = decodeURIComponent( parts[ 1 ] );
}
ab = new ArrayBuffer( byteStr.length );
intArray = new Uint8Array( ab );
for ( i = 0; i < byteStr.length; i++ ) {
intArray[ i ] = byteStr.charCodeAt( i );
}
mimetype = parts[ 0 ].split(':')[ 1 ].split(';')[ 0 ];
return this.arrayBufferToBlob( ab, mimetype );
},
dataURL2ArrayBuffer: function( dataURI ) {
var byteStr, intArray, i, parts;
parts = dataURI.split(',');
if ( ~parts[ 0 ].indexOf('base64') ) {
byteStr = atob( parts[ 1 ] );
} else {
byteStr = decodeURIComponent( parts[ 1 ] );
}
intArray = new Uint8Array( byteStr.length );
for ( i = 0; i < byteStr.length; i++ ) {
intArray[ i ] = byteStr.charCodeAt( i );
}
return intArray.buffer;
},
arrayBufferToBlob: function( buffer, type ) {
var builder = window.BlobBuilder || window.WebKitBlobBuilder,
bb;
// android不支持直接new Blob, 只能借助blobbuilder.
if ( builder ) {
bb = new builder();
bb.append( buffer );
return bb.getBlob( type );
}
return new Blob([ buffer ], type ? { type: type } : {} );
},
// 抽出来主要是为了解决android下面canvas.toDataUrl不支持jpeg.
// 你得到的结果是png.
canvasToDataUrl: function( canvas, type, quality ) {
return canvas.toDataURL( type, quality / 100 );
},
// imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
parseMeta: function( blob, callback ) {
callback( false, {});
},
// imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
updateImageHead: function( data ) {
return data;
}
};
});
/**
* Terms:
*
* Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
* @fileOverview Image控件
*/
define('runtime/html5/imagemeta',[
'runtime/html5/util'
], function( Util ) {
var api;
api = {
parsers: {
0xffe1: []
},
maxMetaDataSize: 262144,
parse: function( blob, cb ) {
var me = this,
fr = new FileReader();
fr.onload = function() {
cb( false, me._parse( this.result ) );
fr = fr.onload = fr.onerror = null;
};
fr.onerror = function( e ) {
cb( e.message );
fr = fr.onload = fr.onerror = null;
};
blob = blob.slice( 0, me.maxMetaDataSize );
fr.readAsArrayBuffer( blob.getSource() );
},
_parse: function( buffer, noParse ) {
if ( buffer.byteLength < 6 ) {
return;
}
var dataview = new DataView( buffer ),
offset = 2,
maxOffset = dataview.byteLength - 4,
headLength = offset,
ret = {},
markerBytes, markerLength, parsers, i;
if ( dataview.getUint16( 0 ) === 0xffd8 ) {
while ( offset < maxOffset ) {
markerBytes = dataview.getUint16( offset );
if ( markerBytes >= 0xffe0 && markerBytes <= 0xffef ||
markerBytes === 0xfffe ) {
markerLength = dataview.getUint16( offset + 2 ) + 2;
if ( offset + markerLength > dataview.byteLength ) {
break;
}
parsers = api.parsers[ markerBytes ];
if ( !noParse && parsers ) {
for ( i = 0; i < parsers.length; i += 1 ) {
parsers[ i ].call( api, dataview, offset,
markerLength, ret );
}
}
offset += markerLength;
headLength = offset;
} else {
break;
}
}
if ( headLength > 6 ) {
if ( buffer.slice ) {
ret.imageHead = buffer.slice( 2, headLength );
} else {
// Workaround for IE10, which does not yet
// support ArrayBuffer.slice:
ret.imageHead = new Uint8Array( buffer )
.subarray( 2, headLength );
}
}
}
return ret;
},
updateImageHead: function( buffer, head ) {
var data = this._parse( buffer, true ),
buf1, buf2, bodyoffset;
bodyoffset = 2;
if ( data.imageHead ) {
bodyoffset = 2 + data.imageHead.byteLength;
}
if ( buffer.slice ) {
buf2 = buffer.slice( bodyoffset );
} else {
buf2 = new Uint8Array( buffer ).subarray( bodyoffset );
}
buf1 = new Uint8Array( head.byteLength + 2 + buf2.byteLength );
buf1[ 0 ] = 0xFF;
buf1[ 1 ] = 0xD8;
buf1.set( new Uint8Array( head ), 2 );
buf1.set( new Uint8Array( buf2 ), head.byteLength + 2 );
return buf1.buffer;
}
};
Util.parseMeta = function() {
return api.parse.apply( api, arguments );
};
Util.updateImageHead = function() {
return api.updateImageHead.apply( api, arguments );
};
return api;
});
/**
* 代码来自于:https://github.com/blueimp/JavaScript-Load-Image
* 暂时项目中只用了orientation.
*
* 去除了 Exif Sub IFD Pointer, GPS Info IFD Pointer, Exif Thumbnail.
* @fileOverview EXIF解析
*/
// Sample
// ====================================
// Make : Apple
// Model : iPhone 4S
// Orientation : 1
// XResolution : 72 [72/1]
// YResolution : 72 [72/1]
// ResolutionUnit : 2
// Software : QuickTime 7.7.1
// DateTime : 2013:09:01 22:53:55
// ExifIFDPointer : 190
// ExposureTime : 0.058823529411764705 [1/17]
// FNumber : 2.4 [12/5]
// ExposureProgram : Normal program
// ISOSpeedRatings : 800
// ExifVersion : 0220
// DateTimeOriginal : 2013:09:01 22:52:51
// DateTimeDigitized : 2013:09:01 22:52:51
// ComponentsConfiguration : YCbCr
// ShutterSpeedValue : 4.058893515764426
// ApertureValue : 2.5260688216892597 [4845/1918]
// BrightnessValue : -0.3126686601998395
// MeteringMode : Pattern
// Flash : Flash did not fire, compulsory flash mode
// FocalLength : 4.28 [107/25]
// SubjectArea : [4 values]
// FlashpixVersion : 0100
// ColorSpace : 1
// PixelXDimension : 2448
// PixelYDimension : 3264
// SensingMethod : One-chip color area sensor
// ExposureMode : 0
// WhiteBalance : Auto white balance
// FocalLengthIn35mmFilm : 35
// SceneCaptureType : Standard
define('runtime/html5/imagemeta/exif',[
'base',
'runtime/html5/imagemeta'
], function( Base, ImageMeta ) {
var EXIF = {};
EXIF.ExifMap = function() {
return this;
};
EXIF.ExifMap.prototype.map = {
'Orientation': 0x0112
};
EXIF.ExifMap.prototype.get = function( id ) {
return this[ id ] || this[ this.map[ id ] ];
};
EXIF.exifTagTypes = {
// byte, 8-bit unsigned int:
1: {
getValue: function( dataView, dataOffset ) {
return dataView.getUint8( dataOffset );
},
size: 1
},
// ascii, 8-bit byte:
2: {
getValue: function( dataView, dataOffset ) {
return String.fromCharCode( dataView.getUint8( dataOffset ) );
},
size: 1,
ascii: true
},
// short, 16 bit int:
3: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getUint16( dataOffset, littleEndian );
},
size: 2
},
// long, 32 bit int:
4: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getUint32( dataOffset, littleEndian );
},
size: 4
},
// rational = two long values,
// first is numerator, second is denominator:
5: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getUint32( dataOffset, littleEndian ) /
dataView.getUint32( dataOffset + 4, littleEndian );
},
size: 8
},
// slong, 32 bit signed int:
9: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getInt32( dataOffset, littleEndian );
},
size: 4
},
// srational, two slongs, first is numerator, second is denominator:
10: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getInt32( dataOffset, littleEndian ) /
dataView.getInt32( dataOffset + 4, littleEndian );
},
size: 8
}
};
// undefined, 8-bit byte, value depending on field:
EXIF.exifTagTypes[ 7 ] = EXIF.exifTagTypes[ 1 ];
EXIF.getExifValue = function( dataView, tiffOffset, offset, type, length,
littleEndian ) {
var tagType = EXIF.exifTagTypes[ type ],
tagSize, dataOffset, values, i, str, c;
if ( !tagType ) {
Base.log('Invalid Exif data: Invalid tag type.');
return;
}
tagSize = tagType.size * length;
// Determine if the value is contained in the dataOffset bytes,
// or if the value at the dataOffset is a pointer to the actual data:
dataOffset = tagSize > 4 ? tiffOffset + dataView.getUint32( offset + 8,
littleEndian ) : (offset + 8);
if ( dataOffset + tagSize > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid data offset.');
return;
}
if ( length === 1 ) {
return tagType.getValue( dataView, dataOffset, littleEndian );
}
values = [];
for ( i = 0; i < length; i += 1 ) {
values[ i ] = tagType.getValue( dataView,
dataOffset + i * tagType.size, littleEndian );
}
if ( tagType.ascii ) {
str = '';
// Concatenate the chars:
for ( i = 0; i < values.length; i += 1 ) {
c = values[ i ];
// Ignore the terminating NULL byte(s):
if ( c === '\u0000' ) {
break;
}
str += c;
}
return str;
}
return values;
};
EXIF.parseExifTag = function( dataView, tiffOffset, offset, littleEndian,
data ) {
var tag = dataView.getUint16( offset, littleEndian );
data.exif[ tag ] = EXIF.getExifValue( dataView, tiffOffset, offset,
dataView.getUint16( offset + 2, littleEndian ), // tag type
dataView.getUint32( offset + 4, littleEndian ), // tag length
littleEndian );
};
EXIF.parseExifTags = function( dataView, tiffOffset, dirOffset,
littleEndian, data ) {
var tagsNumber, dirEndOffset, i;
if ( dirOffset + 6 > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid directory offset.');
return;
}
tagsNumber = dataView.getUint16( dirOffset, littleEndian );
dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
if ( dirEndOffset + 4 > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid directory size.');
return;
}
for ( i = 0; i < tagsNumber; i += 1 ) {
this.parseExifTag( dataView, tiffOffset,
dirOffset + 2 + 12 * i, // tag offset
littleEndian, data );
}
// Return the offset to the next directory:
return dataView.getUint32( dirEndOffset, littleEndian );
};
// EXIF.getExifThumbnail = function(dataView, offset, length) {
// var hexData,
// i,
// b;
// if (!length || offset + length > dataView.byteLength) {
// Base.log('Invalid Exif data: Invalid thumbnail data.');
// return;
// }
// hexData = [];
// for (i = 0; i < length; i += 1) {
// b = dataView.getUint8(offset + i);
// hexData.push((b < 16 ? '0' : '') + b.toString(16));
// }
// return 'data:image/jpeg,%' + hexData.join('%');
// };
EXIF.parseExifData = function( dataView, offset, length, data ) {
var tiffOffset = offset + 10,
littleEndian, dirOffset;
// Check for the ASCII code for "Exif" (0x45786966):
if ( dataView.getUint32( offset + 4 ) !== 0x45786966 ) {
// No Exif data, might be XMP data instead
return;
}
if ( tiffOffset + 8 > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid segment size.');
return;
}
// Check for the two null bytes:
if ( dataView.getUint16( offset + 8 ) !== 0x0000 ) {
Base.log('Invalid Exif data: Missing byte alignment offset.');
return;
}
// Check the byte alignment:
switch ( dataView.getUint16( tiffOffset ) ) {
case 0x4949:
littleEndian = true;
break;
case 0x4D4D:
littleEndian = false;
break;
default:
Base.log('Invalid Exif data: Invalid byte alignment marker.');
return;
}
// Check for the TIFF tag marker (0x002A):
if ( dataView.getUint16( tiffOffset + 2, littleEndian ) !== 0x002A ) {
Base.log('Invalid Exif data: Missing TIFF marker.');
return;
}
// Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
dirOffset = dataView.getUint32( tiffOffset + 4, littleEndian );
// Create the exif object to store the tags:
data.exif = new EXIF.ExifMap();
// Parse the tags of the main image directory and retrieve the
// offset to the next directory, usually the thumbnail directory:
dirOffset = EXIF.parseExifTags( dataView, tiffOffset,
tiffOffset + dirOffset, littleEndian, data );
// 尝试读取缩略图
// if ( dirOffset ) {
// thumbnailData = {exif: {}};
// dirOffset = EXIF.parseExifTags(
// dataView,
// tiffOffset,
// tiffOffset + dirOffset,
// littleEndian,
// thumbnailData
// );
// // Check for JPEG Thumbnail offset:
// if (thumbnailData.exif[0x0201]) {
// data.exif.Thumbnail = EXIF.getExifThumbnail(
// dataView,
// tiffOffset + thumbnailData.exif[0x0201],
// thumbnailData.exif[0x0202] // Thumbnail data length
// );
// }
// }
};
ImageMeta.parsers[ 0xffe1 ].push( EXIF.parseExifData );
return EXIF;
});
/**
* @fileOverview Image
*/
define('runtime/html5/image',[
'base',
'runtime/html5/runtime',
'runtime/html5/util'
], function( Base, Html5Runtime, Util ) {
var BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D';
return Html5Runtime.register( 'Image', {
// flag: 标记是否被修改过。
modified: false,
init: function() {
var me = this,
img = new Image();
img.onload = function() {
me._info = {
type: me.type,
width: this.width,
height: this.height
};
//debugger;
// 读取meta信息。
if ( !me._metas && 'image/jpeg' === me.type ) {
Util.parseMeta( me._blob, function( error, ret ) {
me._metas = ret;
me.owner.trigger('load');
});
} else {
me.owner.trigger('load');
}
};
img.onerror = function() {
me.owner.trigger('error');
};
me._img = img;
},
loadFromBlob: function( blob ) {
var me = this,
img = me._img;
me._blob = blob;
me.type = blob.type;
img.src = Util.createObjectURL( blob.getSource() );
me.owner.once( 'load', function() {
Util.revokeObjectURL( img.src );
});
},
resize: function( width, height ) {
var canvas = this._canvas ||
(this._canvas = document.createElement('canvas'));
this._resize( this._img, canvas, width, height );
this._blob = null; // 没用了,可以删掉了。
this.modified = true;
this.owner.trigger( 'complete', 'resize' );
},
crop: function( x, y, w, h, s ) {
var cvs = this._canvas ||
(this._canvas = document.createElement('canvas')),
opts = this.options,
img = this._img,
iw = img.naturalWidth,
ih = img.naturalHeight,
orientation = this.getOrientation();
s = s || 1;
// todo 解决 orientation 的问题。
// values that require 90 degree rotation
// if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) {
// switch ( orientation ) {
// case 6:
// tmp = x;
// x = y;
// y = iw * s - tmp - w;
// console.log(ih * s, tmp, w)
// break;
// }
// (w ^= h, h ^= w, w ^= h);
// }
cvs.width = w;
cvs.height = h;
opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation );
this._renderImageToCanvas( cvs, img, -x, -y, iw * s, ih * s );
this._blob = null; // 没用了,可以删掉了。
this.modified = true;
this.owner.trigger( 'complete', 'crop' );
},
getAsBlob: function( type ) {
var blob = this._blob,
opts = this.options,
canvas;
type = type || this.type;
// blob需要重新生成。
if ( this.modified || this.type !== type ) {
canvas = this._canvas;
if ( type === 'image/jpeg' ) {
blob = Util.canvasToDataUrl( canvas, type, opts.quality );
if ( opts.preserveHeaders && this._metas &&
this._metas.imageHead ) {
blob = Util.dataURL2ArrayBuffer( blob );
blob = Util.updateImageHead( blob,
this._metas.imageHead );
blob = Util.arrayBufferToBlob( blob, type );
return blob;
}
} else {
blob = Util.canvasToDataUrl( canvas, type );
}
blob = Util.dataURL2Blob( blob );
}
return blob;
},
getAsDataUrl: function( type ) {
var opts = this.options;
type = type || this.type;
if ( type === 'image/jpeg' ) {
return Util.canvasToDataUrl( this._canvas, type, opts.quality );
} else {
return this._canvas.toDataURL( type );
}
},
getOrientation: function() {
return this._metas && this._metas.exif &&
this._metas.exif.get('Orientation') || 1;
},
info: function( val ) {
// setter
if ( val ) {
this._info = val;
return this;
}
// getter
return this._info;
},
meta: function( val ) {
// setter
if ( val ) {
this._metas = val;
return this;
}
// getter
return this._metas;
},
destroy: function() {
var canvas = this._canvas;
this._img.onload = null;
if ( canvas ) {
canvas.getContext('2d')
.clearRect( 0, 0, canvas.width, canvas.height );
canvas.width = canvas.height = 0;
this._canvas = null;
}
// 释放内存。非常重要,否则释放不了image的内存。
this._img.src = BLANK;
this._img = this._blob = null;
},
_resize: function( img, cvs, width, height ) {
var opts = this.options,
naturalWidth = img.width,
naturalHeight = img.height,
orientation = this.getOrientation(),
scale, w, h, x, y;
// values that require 90 degree rotation
if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) {
// 交换width, height的值。
width ^= height;
height ^= width;
width ^= height;
}
scale = Math[ opts.crop ? 'max' : 'min' ]( width / naturalWidth,
height / naturalHeight );
// 不允许放大。
opts.allowMagnify || (scale = Math.min( 1, scale ));
w = naturalWidth * scale;
h = naturalHeight * scale;
if ( opts.crop ) {
cvs.width = width;
cvs.height = height;
} else {
cvs.width = w;
cvs.height = h;
}
x = (cvs.width - w) / 2;
y = (cvs.height - h) / 2;
opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation );
this._renderImageToCanvas( cvs, img, x, y, w, h );
},
_rotate2Orientaion: function( canvas, orientation ) {
var width = canvas.width,
height = canvas.height,
ctx = canvas.getContext('2d');
switch ( orientation ) {
case 5:
case 6:
case 7:
case 8:
canvas.width = height;
canvas.height = width;
break;
}
switch ( orientation ) {
case 2: // horizontal flip
ctx.translate( width, 0 );
ctx.scale( -1, 1 );
break;
case 3: // 180 rotate left
ctx.translate( width, height );
ctx.rotate( Math.PI );
break;
case 4: // vertical flip
ctx.translate( 0, height );
ctx.scale( 1, -1 );
break;
case 5: // vertical flip + 90 rotate right
ctx.rotate( 0.5 * Math.PI );
ctx.scale( 1, -1 );
break;
case 6: // 90 rotate right
ctx.rotate( 0.5 * Math.PI );
ctx.translate( 0, -height );
break;
case 7: // horizontal flip + 90 rotate right
ctx.rotate( 0.5 * Math.PI );
ctx.translate( width, -height );
ctx.scale( -1, 1 );
break;
case 8: // 90 rotate left
ctx.rotate( -0.5 * Math.PI );
ctx.translate( -width, 0 );
break;
}
},
// https://github.com/stomita/ios-imagefile-megapixel/
// blob/master/src/megapix-image.js
_renderImageToCanvas: (function() {
// 如果不是ios, 不需要这么复杂!
if ( !Base.os.ios ) {
return function( canvas ) {
var args = Base.slice( arguments, 1 ),
ctx = canvas.getContext('2d');
ctx.drawImage.apply( ctx, args );
};
}
/**
* Detecting vertical squash in loaded image.
* Fixes a bug which squash image vertically while drawing into
* canvas for some images.
*/
function detectVerticalSquash( img, iw, ih ) {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
sy = 0,
ey = ih,
py = ih,
data, alpha, ratio;
canvas.width = 1;
canvas.height = ih;
ctx.drawImage( img, 0, 0 );
data = ctx.getImageData( 0, 0, 1, ih ).data;
// search image edge pixel position in case
// it is squashed vertically.
while ( py > sy ) {
alpha = data[ (py - 1) * 4 + 3 ];
if ( alpha === 0 ) {
ey = py;
} else {
sy = py;
}
py = (ey + sy) >> 1;
}
ratio = (py / ih);
return (ratio === 0) ? 1 : ratio;
}
// fix ie7 bug
// http://stackoverflow.com/questions/11929099/
// html5-canvas-drawimage-ratio-bug-ios
if ( Base.os.ios >= 7 ) {
return function( canvas, img, x, y, w, h ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
vertSquashRatio = detectVerticalSquash( img, iw, ih );
return canvas.getContext('2d').drawImage( img, 0, 0,
iw * vertSquashRatio, ih * vertSquashRatio,
x, y, w, h );
};
}
/**
* Detect subsampling in loaded image.
* In iOS, larger images than 2M pixels may be
* subsampled in rendering.
*/
function detectSubsampling( img ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
canvas, ctx;
// subsampling may happen overmegapixel image
if ( iw * ih > 1024 * 1024 ) {
canvas = document.createElement('canvas');
canvas.width = canvas.height = 1;
ctx = canvas.getContext('2d');
ctx.drawImage( img, -iw + 1, 0 );
// subsampled image becomes half smaller in rendering size.
// check alpha channel value to confirm image is covering
// edge pixel or not. if alpha value is 0
// image is not covering, hence subsampled.
return ctx.getImageData( 0, 0, 1, 1 ).data[ 3 ] === 0;
} else {
return false;
}
}
return function( canvas, img, x, y, width, height ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
ctx = canvas.getContext('2d'),
subsampled = detectSubsampling( img ),
doSquash = this.type === 'image/jpeg',
d = 1024,
sy = 0,
dy = 0,
tmpCanvas, tmpCtx, vertSquashRatio, dw, dh, sx, dx;
if ( subsampled ) {
iw /= 2;
ih /= 2;
}
ctx.save();
tmpCanvas = document.createElement('canvas');
tmpCanvas.width = tmpCanvas.height = d;
tmpCtx = tmpCanvas.getContext('2d');
vertSquashRatio = doSquash ?
detectVerticalSquash( img, iw, ih ) : 1;
dw = Math.ceil( d * width / iw );
dh = Math.ceil( d * height / ih / vertSquashRatio );
while ( sy < ih ) {
sx = 0;
dx = 0;
while ( sx < iw ) {
tmpCtx.clearRect( 0, 0, d, d );
tmpCtx.drawImage( img, -sx, -sy );
ctx.drawImage( tmpCanvas, 0, 0, d, d,
x + dx, y + dy, dw, dh );
sx += d;
dx += dw;
}
sy += d;
dy += dh;
}
ctx.restore();
tmpCanvas = tmpCtx = null;
};
})()
});
});
/**
* @fileOverview Transport
* @todo 支持chunked传输,优势:
* 可以将大文件分成小块,挨个传输,可以提高大文件成功率,当失败的时候,也只需要重传那小部分,
* 而不需要重头再传一次。另外断点续传也需要用chunked方式。
*/
define('runtime/html5/transport',[
'base',
'runtime/html5/runtime'
], function( Base, Html5Runtime ) {
var noop = Base.noop,
$ = Base.$;
return Html5Runtime.register( 'Transport', {
init: function() {
this._status = 0;
this._response = null;
},
send: function() {
var owner = this.owner,
opts = this.options,
xhr = this._initAjax(),
blob = owner._blob,
server = opts.server,
formData, binary, fr;
if ( opts.sendAsBinary ) {
server += opts.attachInfoToQuery !== false ? ((/\?/.test( server ) ? '&' : '?') +
$.param( owner._formData )) : '';
binary = blob.getSource();
} else {
formData = new FormData();
$.each( owner._formData, function( k, v ) {
formData.append( k, v );
});
formData.append( opts.fileVal, blob.getSource(),
opts.filename || owner._formData.name || '' );
}
if ( opts.withCredentials && 'withCredentials' in xhr ) {
xhr.open( opts.method, server, true );
xhr.withCredentials = true;
} else {
xhr.open( opts.method, server );
}
this._setRequestHeader( xhr, opts.headers );
if ( binary ) {
// 强制设置成 content-type 为文件流。
xhr.overrideMimeType &&
xhr.overrideMimeType('application/octet-stream');
// android直接发送blob会导致服务端接收到的是空文件。
// bug详情。
// https://code.google.com/p/android/issues/detail?id=39882
// 所以先用fileReader读取出来再通过arraybuffer的方式发送。
if ( Base.os.android ) {
fr = new FileReader();
fr.onload = function() {
xhr.send( this.result );
fr = fr.onload = null;
};
fr.readAsArrayBuffer( binary );
} else {
xhr.send( binary );
}
} else {
xhr.send( formData );
}
},
getResponse: function() {
return this._response;
},
getResponseAsJson: function() {
return this._parseJson( this._response );
},
getResponseHeaders: function() {
return this._headers;
},
getStatus: function() {
return this._status;
},
abort: function() {
var xhr = this._xhr;
if ( xhr ) {
xhr.upload.onprogress = noop;
xhr.onreadystatechange = noop;
xhr.abort();
this._xhr = xhr = null;
}
},
destroy: function() {
this.abort();
},
_parseHeader: function(raw) {
var ret = {};
raw && raw.replace(/^([^\:]+):(.*)$/mg, function(_, key, value) {
ret[key.trim()] = value.trim();
});
return ret;
},
_initAjax: function() {
var me = this,
xhr = new XMLHttpRequest(),
opts = this.options;
if ( opts.withCredentials && !('withCredentials' in xhr) &&
typeof XDomainRequest !== 'undefined' ) {
xhr = new XDomainRequest();
}
xhr.upload.onprogress = function( e ) {
var percentage = 0;
if ( e.lengthComputable ) {
percentage = e.loaded / e.total;
}
return me.trigger( 'progress', percentage );
};
xhr.onreadystatechange = function() {
if ( xhr.readyState !== 4 ) {
return;
}
xhr.upload.onprogress = noop;
xhr.onreadystatechange = noop;
me._xhr = null;
me._status = xhr.status;
var separator = '|', // 分隔符
// 拼接的状态,在 widgets/upload.js 会有代码用到这个分隔符
status = separator + xhr.status +
separator + xhr.statusText;
if ( xhr.status >= 200 && xhr.status < 300 ) {
me._response = xhr.responseText;
me._headers = me._parseHeader(xhr.getAllResponseHeaders());
return me.trigger('load');
} else if ( xhr.status >= 500 && xhr.status < 600 ) {
me._response = xhr.responseText;
me._headers = me._parseHeader(xhr.getAllResponseHeaders());
return me.trigger( 'error', 'server' + status );
}
return me.trigger( 'error', me._status ? 'http' + status : 'abort' );
};
me._xhr = xhr;
return xhr;
},
_setRequestHeader: function( xhr, headers ) {
$.each( headers, function( key, val ) {
xhr.setRequestHeader( key, val );
});
},
_parseJson: function( str ) {
var json;
try {
json = JSON.parse( str );
} catch ( ex ) {
json = {};
}
return json;
}
});
});
/**
* @fileOverview 只有html5实现的文件版本。
*/
define('preset/html5only',[
'base',
// widgets
'widgets/filednd',
'widgets/filepaste',
'widgets/filepicker',
'widgets/image',
'widgets/queue',
'widgets/runtime',
'widgets/upload',
'widgets/validator',
// runtimes
// html5
'runtime/html5/blob',
'runtime/html5/dnd',
'runtime/html5/filepaste',
'runtime/html5/filepicker',
'runtime/html5/imagemeta/exif',
'runtime/html5/image',
'runtime/html5/transport'
], function( Base ) {
return Base;
});
define('webuploader',[
'preset/html5only'
], function( preset ) {
return preset;
});
return require('webuploader');
});
================================================
FILE: dist/webuploader.html5only.js
================================================
/*! WebUploader 0.1.8-alpha */
/**
* @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
* @require "jquery"
* @require "zepto"
*/
define('dollar-third',[],function() {
var req = window.require;
var $ = window.__dollar ||
window.jQuery ||
window.Zepto ||
req('jquery') ||
req('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.8-alpha',
/**
* @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 错误信息
*/
define('lib/dnd',[
'base',
'mediator',
'runtime/client'
], function( Base, Mediator, RuntimeClent ) {
var $ = Base.$;
function DragAndDrop( opts ) {
opts = this.options = $.extend({}, DragAndDrop.options, opts );
opts.container = $( opts.container );
if ( !opts.container.length ) {
return;
}
RuntimeClent.call( this, 'DragAndDrop' );
}
DragAndDrop.options = {
accept: null,
disableGlobalDnd: false
};
Base.inherits( RuntimeClent, {
constructor: DragAndDrop,
init: function() {
var me = this;
me.connectRuntime( me.options, function() {
me.exec('init');
me.trigger('ready');
});
}
});
Mediator.installTo( DragAndDrop.prototype );
return DragAndDrop;
});
/**
* @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 DragAndDrop Widget。
*/
define('widgets/filednd',[
'base',
'uploader',
'lib/dnd',
'widgets/widget'
], function( Base, Uploader, Dnd ) {
var $ = Base.$;
Uploader.options.dnd = '';
/**
* @property {Selector} [dnd=undefined] 指定Drag And Drop拖拽的容器,如果不指定,则不启动。
* @namespace options
* @for Uploader
*/
/**
* @property {Selector} [disableGlobalDnd=false] 是否禁掉整个页面的拖拽功能,如果不禁用,图片拖进来的时候会默认被浏览器打开。
* @namespace options
* @for Uploader
*/
/**
* @event dndAccept
* @param {DataTransferItemList} items DataTransferItem
* @description 阻止此事件可以拒绝某些类型的文件拖入进来。目前只有 chrome 提供这样的 API,且只能通过 mime-type 验证。
* @for Uploader
*/
return Uploader.register({
name: 'dnd',
init: function( opts ) {
if ( !opts.dnd ||
this.request('predict-runtime-type') !== 'html5' ) {
return;
}
var me = this,
deferred = Base.Deferred(),
options = $.extend({}, {
disableGlobalDnd: opts.disableGlobalDnd,
container: opts.dnd,
accept: opts.accept
}),
dnd;
this.dnd = dnd = new Dnd( options );
dnd.once( 'ready', deferred.resolve );
dnd.on( 'drop', function( files ) {
me.request( 'add-file', [ files ]);
});
// 检测文件是否全部允许添加。
dnd.on( 'accept', function( items ) {
return me.owner.trigger( 'dndAccept', items );
});
dnd.init();
return deferred.promise();
},
destroy: function() {
this.dnd && this.dnd.destroy();
}
});
});
/**
* @fileOverview 错误信息
*/
define('lib/filepaste',[
'base',
'mediator',
'runtime/client'
], function( Base, Mediator, RuntimeClent ) {
var $ = Base.$;
function FilePaste( opts ) {
opts = this.options = $.extend({}, opts );
opts.container = $( opts.container || document.body );
RuntimeClent.call( this, 'FilePaste' );
}
Base.inherits( RuntimeClent, {
constructor: FilePaste,
init: function() {
var me = this;
me.connectRuntime( me.options, function() {
me.exec('init');
me.trigger('ready');
});
}
});
Mediator.installTo( FilePaste.prototype );
return FilePaste;
});
/**
* @fileOverview 组件基类。
*/
define('widgets/filepaste',[
'base',
'uploader',
'lib/filepaste',
'widgets/widget'
], function( Base, Uploader, FilePaste ) {
var $ = Base.$;
/**
* @property {Selector} [paste=undefined] 指定监听paste事件的容器,如果不指定,不启用此功能。此功能为通过粘贴来添加截屏的图片。建议设置为`document.body`.
* @namespace options
* @for Uploader
*/
return Uploader.register({
name: 'paste',
init: function( opts ) {
if ( !opts.paste ||
this.request('predict-runtime-type') !== 'html5' ) {
return;
}
var me = this,
deferred = Base.Deferred(),
options = $.extend({}, {
container: opts.paste,
accept: opts.accept
}),
paste;
this.paste = paste = new FilePaste( options );
paste.once( 'ready', deferred.resolve );
paste.on( 'paste', function( files ) {
me.owner.request( 'add-file', [ files ]);
});
paste.init();
return deferred.promise();
},
destroy: function() {
this.paste && this.paste.destroy();
}
});
});
/**
* @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 ||
file.lastModified && new Date(file.lastModified).toLocaleString() ||
(new Date()).toLocaleString();
Blob.apply( this, arguments );
}
return Base.inherits( Blob, File );
});
/**
* @fileOverview 错误信息
*/
define('lib/filepicker',[
'base',
'runtime/client',
'lib/file'
], function( Base, RuntimeClient, 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 );
RuntimeClient.call( this, 'FilePicker', true );
}
FilePicker.options = {
button: null,
container: null,
label: null,
innerHTML: null,
multiple: true,
accept: null,
name: 'file',
style: 'webuploader-pick' //pick element class attribute, default is "webuploader-pick"
};
Base.inherits( RuntimeClient, {
constructor: FilePicker,
init: function() {
var me = this,
opts = me.options,
button = opts.button,
style = opts.style;
if (style)
button.addClass('webuploader-pick');
me.on( 'all', function( type ) {
var files;
switch ( type ) {
case 'mouseenter':
if (style)
button.addClass('webuploader-pick-hover');
break;
case 'mouseleave':
if (style)
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(),
*/
width = button[0] && button[0].offsetWidth || button.outerWidth() || button.width(),
height = button[0] && button[0].offsetHeight || 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/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 {Array} [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.on('dialogopen', function() {
me.owner.trigger('dialogOpen', picker.button);
});
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.getAsDataUrl( opts.type ) );
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` 被移除的文件数。
* * `numOfInterrupt` 被中断的文件数。
* @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 ];
this._delFile(file);
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 );
});
}
},
_delFile : function(file){
for(var i = this._queue.length - 1 ; i >= 0 ; i-- ){
if(this._queue[i] == file){
this._queue.splice(i,1);
break;
}
}
},
_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 );
});
if ( files.length ) {
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();
},
getResponseHeaders: function() {
return this.exec('getResponseHeaders');
},
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 {Number} [chunkRetryDelay=1000]
* @namespace options
* @for Uploader
* @description 开启重试后,设置重试延时时间, 单位毫秒。默认1000毫秒,即1秒.
*/
chunkRetryDelay: 1000,
/**
* @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) {
file.setStatus( Status.QUEUED );
$.each( me.pool, function( _, v ) {
// 之前暂停过。
if (v.file !== file) {
return;
}
v.transport && v.transport.send();
file.setStatus( Status.PROGRESS );
});
} else if (file.getStatus() !== Status.PROGRESS) {
file.setStatus( Status.QUEUED );
}
} else {
$.each( me.request( 'get-files', [ Status.INITED ] ), function() {
this.setStatus( Status.QUEUED );
});
}
if ( me.runing ) {
me.owner.trigger('startUpload', file);// 开始上传或暂停恢复的,trigger event
return Base.nextTick( me.__tick );
}
me.runing = true;
var files = [];
// 如果有暂停的,则续传
file || $.each( me.pool, function( _, v ) {
var file = v.file;
if ( file.getStatus() === Status.INTERRUPT ) {
me._trigged = false;
files.push(file);
if (v.waiting) {
return;
}
// 文件 prepare 完后,如果暂停了,这个时候只会把文件插入 pool, 而不会创建 tranport,
v.transport ? v.transport.send() : me._doSend(v);
}
});
$.each(files, function() {
this.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) {
v.transport && v.transport.abort();
if (interrupt) {
me._putback(v);
me._popBlock(v);
}
}
});
me.owner.trigger('stopUpload', file);// 暂停,trigger event
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 );
},
/**
* 判断`Uploader`是否正在上传中。
* @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.remaning++;
block.file.remaning++;
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, 每个分片发送之前可能要做些异步的事情。
block.waiting = promise = me.request( 'before-send', block, function() {
delete block.waiting;
// 有可能文件已经上传出错了,所以不需要再传输了。
if ( file.getStatus() === Status.PROGRESS ) {
me._doSend( block );
} else if (block.file.getStatus() !== Status.INTERRUPT) {
me._popBlock(block);
}
Base.nextTick(me.__tick);
});
// 如果为fail了,则跳过此分片。
promise.fail(function() {
delete block.waiting;
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 = $.extend({}, me.options, block.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();
ret._headers = tr.getResponseHeaders();
block.response = ret;
fn = function( value ) {
reject = value;
};
// 服务端响应了,不代表成功了,询问是否响应正确。
if ( !owner.trigger( 'uploadAccept', block, ret, fn ) ) {
reject = reject || 'server';
}
return reject;
};
// 尝试重试,然后广播文件上传出错。
tr.on( 'error', function( type, flag ) {
// 在 runtime/html5/transport.js 上为 type 加上了状态码,形式:type|status|text(如:http-403-Forbidden)
// 这里把状态码解释出来,并还原后面代码所依赖的 type 变量
var typeArr = type.split( '|' ), status, statusText;
type = typeArr[0];
status = parseFloat( typeArr[1] ),
statusText = typeArr[2];
block.retried = block.retried || 0;
// 自动重试
if ( block.chunks > 1 && ~'http,abort,server'.indexOf( type.replace( /-.*/, '' ) ) &&
block.retried < opts.chunkRetry ) {
block.retried++;
me.retryTimer = setTimeout(function() {
tr.send();
}, opts.chunkRetryDelay || 1000);
} else {
// http status 500 ~ 600
if ( !flag && type === 'server' ) {
type = requestAccept( type );
}
file.setStatus( Status.ERROR, type );
owner.trigger( 'uploadError', file, type, status, statusText );
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 );
},
destroy: function() {
clearTimeout(this.retryTimer);
}
});
});
/**
* @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 ) {
// 增加beforeFileQueuedCheckfileNumLimit验证,主要为了再次加载时(已存在历史文件)验证数量是否超过设置项
if (!this.trigger('beforeFileQueuedCheckfileNumLimit', file,count)) {
return false;
}
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 Html5Runtime
*/
define('runtime/html5/runtime',[
'base',
'runtime/runtime',
'runtime/compbase'
], function( Base, Runtime, CompBase ) {
var type = 'html5',
components = {};
function Html5Runtime() {
var pool = {},
me = this,
destroy = this.destroy;
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;
if ( components[ comp ] ) {
instance = pool[ uid ] = pool[ uid ] ||
new components[ comp ]( client, me );
if ( instance[ fn ] ) {
return instance[ fn ].apply( instance, args );
}
}
};
me.destroy = function() {
// @todo 删除池子中的所有实例
return destroy && destroy.apply( this, arguments );
};
}
Base.inherits( Runtime, {
constructor: Html5Runtime,
// 不需要连接其他程序,直接执行callback
init: function() {
var me = this;
setTimeout(function() {
me.trigger('ready');
}, 1 );
}
});
// 注册Components
Html5Runtime.register = function( name, component ) {
var klass = components[ name ] = Base.inherits( CompBase, component );
return klass;
};
// 注册html5运行时。
// 只有在支持的前提下注册。
if ( window.Blob && window.FileReader && window.DataView ) {
Runtime.addRuntime( type, Html5Runtime );
}
return Html5Runtime;
});
/**
* @fileOverview Blob Html实现
*/
define('runtime/html5/blob',[
'runtime/html5/runtime',
'lib/blob'
], function( Html5Runtime, Blob ) {
return Html5Runtime.register( 'Blob', {
slice: function( start, end ) {
var blob = this.owner.source,
slice = blob.slice || blob.webkitSlice || blob.mozSlice;
blob = slice.call( blob, start, end );
return new Blob( this.getRuid(), blob );
}
});
});
/**
* @fileOverview FilePaste
*/
define('runtime/html5/dnd',[
'base',
'runtime/html5/runtime',
'lib/file'
], function( Base, Html5Runtime, File ) {
var $ = Base.$,
prefix = 'webuploader-dnd-';
return Html5Runtime.register( 'DragAndDrop', {
init: function() {
var elem = this.elem = this.options.container;
this.dragEnterHandler = Base.bindFn( this._dragEnterHandler, this );
this.dragOverHandler = Base.bindFn( this._dragOverHandler, this );
this.dragLeaveHandler = Base.bindFn( this._dragLeaveHandler, this );
this.dropHandler = Base.bindFn( this._dropHandler, this );
this.dndOver = false;
elem.on( 'dragenter', this.dragEnterHandler );
elem.on( 'dragover', this.dragOverHandler );
elem.on( 'dragleave', this.dragLeaveHandler );
elem.on( 'drop', this.dropHandler );
if ( this.options.disableGlobalDnd ) {
$( document ).on( 'dragover', this.dragOverHandler );
$( document ).on( 'drop', this.dropHandler );
}
},
_dragEnterHandler: function( e ) {
var me = this,
denied = me._denied || false,
items;
e = e.originalEvent || e;
if ( !me.dndOver ) {
me.dndOver = true;
// 注意只有 chrome 支持。
items = e.dataTransfer.items;
if ( items && items.length ) {
me._denied = denied = !me.trigger( 'accept', items );
}
me.elem.addClass( prefix + 'over' );
me.elem[ denied ? 'addClass' :
'removeClass' ]( prefix + 'denied' );
}
e.dataTransfer.dropEffect = denied ? 'none' : 'copy';
return false;
},
_dragOverHandler: function( e ) {
// 只处理框内的。
var parentElem = this.elem.parent().get( 0 );
if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) {
return false;
}
clearTimeout( this._leaveTimer );
this._dragEnterHandler.call( this, e );
return false;
},
_dragLeaveHandler: function() {
var me = this,
handler;
handler = function() {
me.dndOver = false;
me.elem.removeClass( prefix + 'over ' + prefix + 'denied' );
};
clearTimeout( me._leaveTimer );
me._leaveTimer = setTimeout( handler, 100 );
return false;
},
_dropHandler: function( e ) {
var me = this,
ruid = me.getRuid(),
parentElem = me.elem.parent().get( 0 ),
dataTransfer, data;
// 只处理框内的。
if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) {
return false;
}
e = e.originalEvent || e;
dataTransfer = e.dataTransfer;
// 如果是页面内拖拽,还不能处理,不阻止事件。
// 此处 ie11 下会报参数错误,
try {
data = dataTransfer.getData('text/html');
} catch( err ) {
}
me.dndOver = false;
me.elem.removeClass( prefix + 'over' );
if ( !dataTransfer || data ) {
return;
}
me._getTansferFiles( dataTransfer, function( results ) {
me.trigger( 'drop', $.map( results, function( file ) {
return new File( ruid, file );
}) );
});
return false;
},
// 如果传入 callback 则去查看文件夹,否则只管当前文件夹。
_getTansferFiles: function( dataTransfer, callback ) {
var results = [],
promises = [],
items, files, file, item, i, len, canAccessFolder;
items = dataTransfer.items;
files = dataTransfer.files;
canAccessFolder = !!(items && items[ 0 ].webkitGetAsEntry);
for ( i = 0, len = files.length; i < len; i++ ) {
file = files[ i ];
item = items && items[ i ];
if ( canAccessFolder && item.webkitGetAsEntry().isDirectory ) {
promises.push( this._traverseDirectoryTree(
item.webkitGetAsEntry(), results ) );
} else {
results.push( file );
}
}
Base.when.apply( Base, promises ).done(function() {
if ( !results.length ) {
return;
}
callback( results );
});
},
_traverseDirectoryTree: function( entry, results ) {
var deferred = Base.Deferred(),
me = this;
if ( entry.isFile ) {
entry.file(function( file ) {
results.push( file );
deferred.resolve();
});
} else if ( entry.isDirectory ) {
entry.createReader().readEntries(function( entries ) {
var len = entries.length,
promises = [],
arr = [], // 为了保证顺序。
i;
for ( i = 0; i < len; i++ ) {
promises.push( me._traverseDirectoryTree(
entries[ i ], arr ) );
}
Base.when.apply( Base, promises ).then(function() {
results.push.apply( results, arr );
deferred.resolve();
}, deferred.reject );
});
}
return deferred.promise();
},
destroy: function() {
var elem = this.elem;
// 还没 init 就调用 destroy
if (!elem) {
return;
}
elem.off( 'dragenter', this.dragEnterHandler );
elem.off( 'dragover', this.dragOverHandler );
elem.off( 'dragleave', this.dragLeaveHandler );
elem.off( 'drop', this.dropHandler );
if ( this.options.disableGlobalDnd ) {
$( document ).off( 'dragover', this.dragOverHandler );
$( document ).off( 'drop', this.dropHandler );
}
}
});
});
/**
* @fileOverview FilePaste
*/
define('runtime/html5/filepaste',[
'base',
'runtime/html5/runtime',
'lib/file'
], function( Base, Html5Runtime, File ) {
return Html5Runtime.register( 'FilePaste', {
init: function() {
var opts = this.options,
elem = this.elem = opts.container,
accept = '.*',
arr, i, len, item;
// accetp的mimeTypes中生成匹配正则。
if ( opts.accept ) {
arr = [];
for ( i = 0, len = opts.accept.length; i < len; i++ ) {
item = opts.accept[ i ].mimeTypes;
item && arr.push( item );
}
if ( arr.length ) {
accept = arr.join(',');
accept = accept.replace( /,/g, '|' ).replace( /\*/g, '.*' );
}
}
this.accept = accept = new RegExp( accept, 'i' );
this.hander = Base.bindFn( this._pasteHander, this );
elem.on( 'paste', this.hander );
},
_pasteHander: function( e ) {
var allowed = [],
ruid = this.getRuid(),
items, item, blob, i, len;
e = e.originalEvent || e;
items = e.clipboardData.items;
for ( i = 0, len = items.length; i < len; i++ ) {
item = items[ i ];
if ( item.kind !== 'file' || !(blob = item.getAsFile()) ) {
continue;
}
allowed.push( new File( ruid, blob ) );
}
if ( allowed.length ) {
// 不阻止非文件粘贴(文字粘贴)的事件冒泡
e.preventDefault();
e.stopPropagation();
this.trigger( 'paste', allowed );
}
},
destroy: function() {
this.elem.off( 'paste', this.hander );
}
});
});
/**
* @fileOverview FilePicker
*/
define('runtime/html5/filepicker',[
'base',
'runtime/html5/runtime'
], function( Base, Html5Runtime ) {
var $ = Base.$;
return Html5Runtime.register( 'FilePicker', {
init: function() {
var container = this.getRuntime().getContainer(),
me = this,
owner = me.owner,
opts = me.options,
label = this.label = $( document.createElement('label') ),
input = this.input = $( document.createElement('input') ),
arr, i, len, mouseHandler, changeHandler;
input.attr( 'type', 'file' );
input.attr( 'capture', 'camera');
input.attr( 'name', opts.name );
input.addClass('webuploader-element-invisible');
label.on( 'click', function(e) {
input.trigger('click');
e.stopPropagation();
owner.trigger('dialogopen');
});
label.css({
opacity: 0,
width: '100%',
height: '100%',
display: 'block',
cursor: 'pointer',
background: '#ffffff'
});
if ( opts.multiple ) {
input.attr( 'multiple', 'multiple' );
}
// @todo Firefox不支持单独指定后缀
if ( opts.accept && opts.accept.length > 0 ) {
arr = [];
for ( i = 0, len = opts.accept.length; i < len; i++ ) {
arr.push( opts.accept[ i ].mimeTypes );
}
input.attr( 'accept', arr.join(',') );
}
container.append( input );
container.append( label );
mouseHandler = function( e ) {
owner.trigger( e.type );
};
changeHandler = function( e ) {
var clone;
// 解决chrome 56 第二次打开文件选择器,然后点击取消,依然会触发change事件的问题
if (e.target.files.length === 0){
return false;
}
// 第一次上传图片后,第二次再点击弹出文件选择器窗,等待
me.files = e.target.files;
// reset input
clone = this.cloneNode( true );
clone.value = null;
this.parentNode.replaceChild( clone, this );
input.off();
input = $( clone ).on( 'change', changeHandler )
.on( 'mouseenter mouseleave', mouseHandler );
owner.trigger('change');
}
input.on( 'change', changeHandler);
label.on( 'mouseenter mouseleave', mouseHandler );
},
getFiles: function() {
return this.files;
},
destroy: function() {
this.input.off();
this.label.off();
}
});
});
/**
* Terms:
*
* Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
* @fileOverview Image控件
*/
define('runtime/html5/util',[
'base'
], function( Base ) {
var urlAPI = window.createObjectURL && window ||
window.URL && URL.revokeObjectURL && URL ||
window.webkitURL,
createObjectURL = Base.noop,
revokeObjectURL = createObjectURL;
if ( urlAPI ) {
// 更安全的方式调用,比如android里面就能把context改成其他的对象。
createObjectURL = function() {
return urlAPI.createObjectURL.apply( urlAPI, arguments );
};
revokeObjectURL = function() {
return urlAPI.revokeObjectURL.apply( urlAPI, arguments );
};
}
return {
createObjectURL: createObjectURL,
revokeObjectURL: revokeObjectURL,
dataURL2Blob: function( dataURI ) {
var byteStr, intArray, ab, i, mimetype, parts;
parts = dataURI.split(',');
if ( ~parts[ 0 ].indexOf('base64') ) {
byteStr = atob( parts[ 1 ] );
} else {
byteStr = decodeURIComponent( parts[ 1 ] );
}
ab = new ArrayBuffer( byteStr.length );
intArray = new Uint8Array( ab );
for ( i = 0; i < byteStr.length; i++ ) {
intArray[ i ] = byteStr.charCodeAt( i );
}
mimetype = parts[ 0 ].split(':')[ 1 ].split(';')[ 0 ];
return this.arrayBufferToBlob( ab, mimetype );
},
dataURL2ArrayBuffer: function( dataURI ) {
var byteStr, intArray, i, parts;
parts = dataURI.split(',');
if ( ~parts[ 0 ].indexOf('base64') ) {
byteStr = atob( parts[ 1 ] );
} else {
byteStr = decodeURIComponent( parts[ 1 ] );
}
intArray = new Uint8Array( byteStr.length );
for ( i = 0; i < byteStr.length; i++ ) {
intArray[ i ] = byteStr.charCodeAt( i );
}
return intArray.buffer;
},
arrayBufferToBlob: function( buffer, type ) {
var builder = window.BlobBuilder || window.WebKitBlobBuilder,
bb;
// android不支持直接new Blob, 只能借助blobbuilder.
if ( builder ) {
bb = new builder();
bb.append( buffer );
return bb.getBlob( type );
}
return new Blob([ buffer ], type ? { type: type } : {} );
},
// 抽出来主要是为了解决android下面canvas.toDataUrl不支持jpeg.
// 你得到的结果是png.
canvasToDataUrl: function( canvas, type, quality ) {
return canvas.toDataURL( type, quality / 100 );
},
// imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
parseMeta: function( blob, callback ) {
callback( false, {});
},
// imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
updateImageHead: function( data ) {
return data;
}
};
});
/**
* Terms:
*
* Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
* @fileOverview Image控件
*/
define('runtime/html5/imagemeta',[
'runtime/html5/util'
], function( Util ) {
var api;
api = {
parsers: {
0xffe1: []
},
maxMetaDataSize: 262144,
parse: function( blob, cb ) {
var me = this,
fr = new FileReader();
fr.onload = function() {
cb( false, me._parse( this.result ) );
fr = fr.onload = fr.onerror = null;
};
fr.onerror = function( e ) {
cb( e.message );
fr = fr.onload = fr.onerror = null;
};
blob = blob.slice( 0, me.maxMetaDataSize );
fr.readAsArrayBuffer( blob.getSource() );
},
_parse: function( buffer, noParse ) {
if ( buffer.byteLength < 6 ) {
return;
}
var dataview = new DataView( buffer ),
offset = 2,
maxOffset = dataview.byteLength - 4,
headLength = offset,
ret = {},
markerBytes, markerLength, parsers, i;
if ( dataview.getUint16( 0 ) === 0xffd8 ) {
while ( offset < maxOffset ) {
markerBytes = dataview.getUint16( offset );
if ( markerBytes >= 0xffe0 && markerBytes <= 0xffef ||
markerBytes === 0xfffe ) {
markerLength = dataview.getUint16( offset + 2 ) + 2;
if ( offset + markerLength > dataview.byteLength ) {
break;
}
parsers = api.parsers[ markerBytes ];
if ( !noParse && parsers ) {
for ( i = 0; i < parsers.length; i += 1 ) {
parsers[ i ].call( api, dataview, offset,
markerLength, ret );
}
}
offset += markerLength;
headLength = offset;
} else {
break;
}
}
if ( headLength > 6 ) {
if ( buffer.slice ) {
ret.imageHead = buffer.slice( 2, headLength );
} else {
// Workaround for IE10, which does not yet
// support ArrayBuffer.slice:
ret.imageHead = new Uint8Array( buffer )
.subarray( 2, headLength );
}
}
}
return ret;
},
updateImageHead: function( buffer, head ) {
var data = this._parse( buffer, true ),
buf1, buf2, bodyoffset;
bodyoffset = 2;
if ( data.imageHead ) {
bodyoffset = 2 + data.imageHead.byteLength;
}
if ( buffer.slice ) {
buf2 = buffer.slice( bodyoffset );
} else {
buf2 = new Uint8Array( buffer ).subarray( bodyoffset );
}
buf1 = new Uint8Array( head.byteLength + 2 + buf2.byteLength );
buf1[ 0 ] = 0xFF;
buf1[ 1 ] = 0xD8;
buf1.set( new Uint8Array( head ), 2 );
buf1.set( new Uint8Array( buf2 ), head.byteLength + 2 );
return buf1.buffer;
}
};
Util.parseMeta = function() {
return api.parse.apply( api, arguments );
};
Util.updateImageHead = function() {
return api.updateImageHead.apply( api, arguments );
};
return api;
});
/**
* 代码来自于:https://github.com/blueimp/JavaScript-Load-Image
* 暂时项目中只用了orientation.
*
* 去除了 Exif Sub IFD Pointer, GPS Info IFD Pointer, Exif Thumbnail.
* @fileOverview EXIF解析
*/
// Sample
// ====================================
// Make : Apple
// Model : iPhone 4S
// Orientation : 1
// XResolution : 72 [72/1]
// YResolution : 72 [72/1]
// ResolutionUnit : 2
// Software : QuickTime 7.7.1
// DateTime : 2013:09:01 22:53:55
// ExifIFDPointer : 190
// ExposureTime : 0.058823529411764705 [1/17]
// FNumber : 2.4 [12/5]
// ExposureProgram : Normal program
// ISOSpeedRatings : 800
// ExifVersion : 0220
// DateTimeOriginal : 2013:09:01 22:52:51
// DateTimeDigitized : 2013:09:01 22:52:51
// ComponentsConfiguration : YCbCr
// ShutterSpeedValue : 4.058893515764426
// ApertureValue : 2.5260688216892597 [4845/1918]
// BrightnessValue : -0.3126686601998395
// MeteringMode : Pattern
// Flash : Flash did not fire, compulsory flash mode
// FocalLength : 4.28 [107/25]
// SubjectArea : [4 values]
// FlashpixVersion : 0100
// ColorSpace : 1
// PixelXDimension : 2448
// PixelYDimension : 3264
// SensingMethod : One-chip color area sensor
// ExposureMode : 0
// WhiteBalance : Auto white balance
// FocalLengthIn35mmFilm : 35
// SceneCaptureType : Standard
define('runtime/html5/imagemeta/exif',[
'base',
'runtime/html5/imagemeta'
], function( Base, ImageMeta ) {
var EXIF = {};
EXIF.ExifMap = function() {
return this;
};
EXIF.ExifMap.prototype.map = {
'Orientation': 0x0112
};
EXIF.ExifMap.prototype.get = function( id ) {
return this[ id ] || this[ this.map[ id ] ];
};
EXIF.exifTagTypes = {
// byte, 8-bit unsigned int:
1: {
getValue: function( dataView, dataOffset ) {
return dataView.getUint8( dataOffset );
},
size: 1
},
// ascii, 8-bit byte:
2: {
getValue: function( dataView, dataOffset ) {
return String.fromCharCode( dataView.getUint8( dataOffset ) );
},
size: 1,
ascii: true
},
// short, 16 bit int:
3: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getUint16( dataOffset, littleEndian );
},
size: 2
},
// long, 32 bit int:
4: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getUint32( dataOffset, littleEndian );
},
size: 4
},
// rational = two long values,
// first is numerator, second is denominator:
5: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getUint32( dataOffset, littleEndian ) /
dataView.getUint32( dataOffset + 4, littleEndian );
},
size: 8
},
// slong, 32 bit signed int:
9: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getInt32( dataOffset, littleEndian );
},
size: 4
},
// srational, two slongs, first is numerator, second is denominator:
10: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getInt32( dataOffset, littleEndian ) /
dataView.getInt32( dataOffset + 4, littleEndian );
},
size: 8
}
};
// undefined, 8-bit byte, value depending on field:
EXIF.exifTagTypes[ 7 ] = EXIF.exifTagTypes[ 1 ];
EXIF.getExifValue = function( dataView, tiffOffset, offset, type, length,
littleEndian ) {
var tagType = EXIF.exifTagTypes[ type ],
tagSize, dataOffset, values, i, str, c;
if ( !tagType ) {
Base.log('Invalid Exif data: Invalid tag type.');
return;
}
tagSize = tagType.size * length;
// Determine if the value is contained in the dataOffset bytes,
// or if the value at the dataOffset is a pointer to the actual data:
dataOffset = tagSize > 4 ? tiffOffset + dataView.getUint32( offset + 8,
littleEndian ) : (offset + 8);
if ( dataOffset + tagSize > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid data offset.');
return;
}
if ( length === 1 ) {
return tagType.getValue( dataView, dataOffset, littleEndian );
}
values = [];
for ( i = 0; i < length; i += 1 ) {
values[ i ] = tagType.getValue( dataView,
dataOffset + i * tagType.size, littleEndian );
}
if ( tagType.ascii ) {
str = '';
// Concatenate the chars:
for ( i = 0; i < values.length; i += 1 ) {
c = values[ i ];
// Ignore the terminating NULL byte(s):
if ( c === '\u0000' ) {
break;
}
str += c;
}
return str;
}
return values;
};
EXIF.parseExifTag = function( dataView, tiffOffset, offset, littleEndian,
data ) {
var tag = dataView.getUint16( offset, littleEndian );
data.exif[ tag ] = EXIF.getExifValue( dataView, tiffOffset, offset,
dataView.getUint16( offset + 2, littleEndian ), // tag type
dataView.getUint32( offset + 4, littleEndian ), // tag length
littleEndian );
};
EXIF.parseExifTags = function( dataView, tiffOffset, dirOffset,
littleEndian, data ) {
var tagsNumber, dirEndOffset, i;
if ( dirOffset + 6 > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid directory offset.');
return;
}
tagsNumber = dataView.getUint16( dirOffset, littleEndian );
dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
if ( dirEndOffset + 4 > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid directory size.');
return;
}
for ( i = 0; i < tagsNumber; i += 1 ) {
this.parseExifTag( dataView, tiffOffset,
dirOffset + 2 + 12 * i, // tag offset
littleEndian, data );
}
// Return the offset to the next directory:
return dataView.getUint32( dirEndOffset, littleEndian );
};
// EXIF.getExifThumbnail = function(dataView, offset, length) {
// var hexData,
// i,
// b;
// if (!length || offset + length > dataView.byteLength) {
// Base.log('Invalid Exif data: Invalid thumbnail data.');
// return;
// }
// hexData = [];
// for (i = 0; i < length; i += 1) {
// b = dataView.getUint8(offset + i);
// hexData.push((b < 16 ? '0' : '') + b.toString(16));
// }
// return 'data:image/jpeg,%' + hexData.join('%');
// };
EXIF.parseExifData = function( dataView, offset, length, data ) {
var tiffOffset = offset + 10,
littleEndian, dirOffset;
// Check for the ASCII code for "Exif" (0x45786966):
if ( dataView.getUint32( offset + 4 ) !== 0x45786966 ) {
// No Exif data, might be XMP data instead
return;
}
if ( tiffOffset + 8 > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid segment size.');
return;
}
// Check for the two null bytes:
if ( dataView.getUint16( offset + 8 ) !== 0x0000 ) {
Base.log('Invalid Exif data: Missing byte alignment offset.');
return;
}
// Check the byte alignment:
switch ( dataView.getUint16( tiffOffset ) ) {
case 0x4949:
littleEndian = true;
break;
case 0x4D4D:
littleEndian = false;
break;
default:
Base.log('Invalid Exif data: Invalid byte alignment marker.');
return;
}
// Check for the TIFF tag marker (0x002A):
if ( dataView.getUint16( tiffOffset + 2, littleEndian ) !== 0x002A ) {
Base.log('Invalid Exif data: Missing TIFF marker.');
return;
}
// Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
dirOffset = dataView.getUint32( tiffOffset + 4, littleEndian );
// Create the exif object to store the tags:
data.exif = new EXIF.ExifMap();
// Parse the tags of the main image directory and retrieve the
// offset to the next directory, usually the thumbnail directory:
dirOffset = EXIF.parseExifTags( dataView, tiffOffset,
tiffOffset + dirOffset, littleEndian, data );
// 尝试读取缩略图
// if ( dirOffset ) {
// thumbnailData = {exif: {}};
// dirOffset = EXIF.parseExifTags(
// dataView,
// tiffOffset,
// tiffOffset + dirOffset,
// littleEndian,
// thumbnailData
// );
// // Check for JPEG Thumbnail offset:
// if (thumbnailData.exif[0x0201]) {
// data.exif.Thumbnail = EXIF.getExifThumbnail(
// dataView,
// tiffOffset + thumbnailData.exif[0x0201],
// thumbnailData.exif[0x0202] // Thumbnail data length
// );
// }
// }
};
ImageMeta.parsers[ 0xffe1 ].push( EXIF.parseExifData );
return EXIF;
});
/**
* @fileOverview Image
*/
define('runtime/html5/image',[
'base',
'runtime/html5/runtime',
'runtime/html5/util'
], function( Base, Html5Runtime, Util ) {
var BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D';
return Html5Runtime.register( 'Image', {
// flag: 标记是否被修改过。
modified: false,
init: function() {
var me = this,
img = new Image();
img.onload = function() {
me._info = {
type: me.type,
width: this.width,
height: this.height
};
//debugger;
// 读取meta信息。
if ( !me._metas && 'image/jpeg' === me.type ) {
Util.parseMeta( me._blob, function( error, ret ) {
me._metas = ret;
me.owner.trigger('load');
});
} else {
me.owner.trigger('load');
}
};
img.onerror = function() {
me.owner.trigger('error');
};
me._img = img;
},
loadFromBlob: function( blob ) {
var me = this,
img = me._img;
me._blob = blob;
me.type = blob.type;
img.src = Util.createObjectURL( blob.getSource() );
me.owner.once( 'load', function() {
Util.revokeObjectURL( img.src );
});
},
resize: function( width, height ) {
var canvas = this._canvas ||
(this._canvas = document.createElement('canvas'));
this._resize( this._img, canvas, width, height );
this._blob = null; // 没用了,可以删掉了。
this.modified = true;
this.owner.trigger( 'complete', 'resize' );
},
crop: function( x, y, w, h, s ) {
var cvs = this._canvas ||
(this._canvas = document.createElement('canvas')),
opts = this.options,
img = this._img,
iw = img.naturalWidth,
ih = img.naturalHeight,
orientation = this.getOrientation();
s = s || 1;
// todo 解决 orientation 的问题。
// values that require 90 degree rotation
// if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) {
// switch ( orientation ) {
// case 6:
// tmp = x;
// x = y;
// y = iw * s - tmp - w;
// console.log(ih * s, tmp, w)
// break;
// }
// (w ^= h, h ^= w, w ^= h);
// }
cvs.width = w;
cvs.height = h;
opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation );
this._renderImageToCanvas( cvs, img, -x, -y, iw * s, ih * s );
this._blob = null; // 没用了,可以删掉了。
this.modified = true;
this.owner.trigger( 'complete', 'crop' );
},
getAsBlob: function( type ) {
var blob = this._blob,
opts = this.options,
canvas;
type = type || this.type;
// blob需要重新生成。
if ( this.modified || this.type !== type ) {
canvas = this._canvas;
if ( type === 'image/jpeg' ) {
blob = Util.canvasToDataUrl( canvas, type, opts.quality );
if ( opts.preserveHeaders && this._metas &&
this._metas.imageHead ) {
blob = Util.dataURL2ArrayBuffer( blob );
blob = Util.updateImageHead( blob,
this._metas.imageHead );
blob = Util.arrayBufferToBlob( blob, type );
return blob;
}
} else {
blob = Util.canvasToDataUrl( canvas, type );
}
blob = Util.dataURL2Blob( blob );
}
return blob;
},
getAsDataUrl: function( type ) {
var opts = this.options;
type = type || this.type;
if ( type === 'image/jpeg' ) {
return Util.canvasToDataUrl( this._canvas, type, opts.quality );
} else {
return this._canvas.toDataURL( type );
}
},
getOrientation: function() {
return this._metas && this._metas.exif &&
this._metas.exif.get('Orientation') || 1;
},
info: function( val ) {
// setter
if ( val ) {
this._info = val;
return this;
}
// getter
return this._info;
},
meta: function( val ) {
// setter
if ( val ) {
this._metas = val;
return this;
}
// getter
return this._metas;
},
destroy: function() {
var canvas = this._canvas;
this._img.onload = null;
if ( canvas ) {
canvas.getContext('2d')
.clearRect( 0, 0, canvas.width, canvas.height );
canvas.width = canvas.height = 0;
this._canvas = null;
}
// 释放内存。非常重要,否则释放不了image的内存。
this._img.src = BLANK;
this._img = this._blob = null;
},
_resize: function( img, cvs, width, height ) {
var opts = this.options,
naturalWidth = img.width,
naturalHeight = img.height,
orientation = this.getOrientation(),
scale, w, h, x, y;
// values that require 90 degree rotation
if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) {
// 交换width, height的值。
width ^= height;
height ^= width;
width ^= height;
}
scale = Math[ opts.crop ? 'max' : 'min' ]( width / naturalWidth,
height / naturalHeight );
// 不允许放大。
opts.allowMagnify || (scale = Math.min( 1, scale ));
w = naturalWidth * scale;
h = naturalHeight * scale;
if ( opts.crop ) {
cvs.width = width;
cvs.height = height;
} else {
cvs.width = w;
cvs.height = h;
}
x = (cvs.width - w) / 2;
y = (cvs.height - h) / 2;
opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation );
this._renderImageToCanvas( cvs, img, x, y, w, h );
},
_rotate2Orientaion: function( canvas, orientation ) {
var width = canvas.width,
height = canvas.height,
ctx = canvas.getContext('2d');
switch ( orientation ) {
case 5:
case 6:
case 7:
case 8:
canvas.width = height;
canvas.height = width;
break;
}
switch ( orientation ) {
case 2: // horizontal flip
ctx.translate( width, 0 );
ctx.scale( -1, 1 );
break;
case 3: // 180 rotate left
ctx.translate( width, height );
ctx.rotate( Math.PI );
break;
case 4: // vertical flip
ctx.translate( 0, height );
ctx.scale( 1, -1 );
break;
case 5: // vertical flip + 90 rotate right
ctx.rotate( 0.5 * Math.PI );
ctx.scale( 1, -1 );
break;
case 6: // 90 rotate right
ctx.rotate( 0.5 * Math.PI );
ctx.translate( 0, -height );
break;
case 7: // horizontal flip + 90 rotate right
ctx.rotate( 0.5 * Math.PI );
ctx.translate( width, -height );
ctx.scale( -1, 1 );
break;
case 8: // 90 rotate left
ctx.rotate( -0.5 * Math.PI );
ctx.translate( -width, 0 );
break;
}
},
// https://github.com/stomita/ios-imagefile-megapixel/
// blob/master/src/megapix-image.js
_renderImageToCanvas: (function() {
// 如果不是ios, 不需要这么复杂!
if ( !Base.os.ios ) {
return function( canvas ) {
var args = Base.slice( arguments, 1 ),
ctx = canvas.getContext('2d');
ctx.drawImage.apply( ctx, args );
};
}
/**
* Detecting vertical squash in loaded image.
* Fixes a bug which squash image vertically while drawing into
* canvas for some images.
*/
function detectVerticalSquash( img, iw, ih ) {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
sy = 0,
ey = ih,
py = ih,
data, alpha, ratio;
canvas.width = 1;
canvas.height = ih;
ctx.drawImage( img, 0, 0 );
data = ctx.getImageData( 0, 0, 1, ih ).data;
// search image edge pixel position in case
// it is squashed vertically.
while ( py > sy ) {
alpha = data[ (py - 1) * 4 + 3 ];
if ( alpha === 0 ) {
ey = py;
} else {
sy = py;
}
py = (ey + sy) >> 1;
}
ratio = (py / ih);
return (ratio === 0) ? 1 : ratio;
}
// fix ie7 bug
// http://stackoverflow.com/questions/11929099/
// html5-canvas-drawimage-ratio-bug-ios
if ( Base.os.ios >= 7 ) {
return function( canvas, img, x, y, w, h ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
vertSquashRatio = detectVerticalSquash( img, iw, ih );
return canvas.getContext('2d').drawImage( img, 0, 0,
iw * vertSquashRatio, ih * vertSquashRatio,
x, y, w, h );
};
}
/**
* Detect subsampling in loaded image.
* In iOS, larger images than 2M pixels may be
* subsampled in rendering.
*/
function detectSubsampling( img ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
canvas, ctx;
// subsampling may happen overmegapixel image
if ( iw * ih > 1024 * 1024 ) {
canvas = document.createElement('canvas');
canvas.width = canvas.height = 1;
ctx = canvas.getContext('2d');
ctx.drawImage( img, -iw + 1, 0 );
// subsampled image becomes half smaller in rendering size.
// check alpha channel value to confirm image is covering
// edge pixel or not. if alpha value is 0
// image is not covering, hence subsampled.
return ctx.getImageData( 0, 0, 1, 1 ).data[ 3 ] === 0;
} else {
return false;
}
}
return function( canvas, img, x, y, width, height ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
ctx = canvas.getContext('2d'),
subsampled = detectSubsampling( img ),
doSquash = this.type === 'image/jpeg',
d = 1024,
sy = 0,
dy = 0,
tmpCanvas, tmpCtx, vertSquashRatio, dw, dh, sx, dx;
if ( subsampled ) {
iw /= 2;
ih /= 2;
}
ctx.save();
tmpCanvas = document.createElement('canvas');
tmpCanvas.width = tmpCanvas.height = d;
tmpCtx = tmpCanvas.getContext('2d');
vertSquashRatio = doSquash ?
detectVerticalSquash( img, iw, ih ) : 1;
dw = Math.ceil( d * width / iw );
dh = Math.ceil( d * height / ih / vertSquashRatio );
while ( sy < ih ) {
sx = 0;
dx = 0;
while ( sx < iw ) {
tmpCtx.clearRect( 0, 0, d, d );
tmpCtx.drawImage( img, -sx, -sy );
ctx.drawImage( tmpCanvas, 0, 0, d, d,
x + dx, y + dy, dw, dh );
sx += d;
dx += dw;
}
sy += d;
dy += dh;
}
ctx.restore();
tmpCanvas = tmpCtx = null;
};
})()
});
});
/**
* @fileOverview Transport
* @todo 支持chunked传输,优势:
* 可以将大文件分成小块,挨个传输,可以提高大文件成功率,当失败的时候,也只需要重传那小部分,
* 而不需要重头再传一次。另外断点续传也需要用chunked方式。
*/
define('runtime/html5/transport',[
'base',
'runtime/html5/runtime'
], function( Base, Html5Runtime ) {
var noop = Base.noop,
$ = Base.$;
return Html5Runtime.register( 'Transport', {
init: function() {
this._status = 0;
this._response = null;
},
send: function() {
var owner = this.owner,
opts = this.options,
xhr = this._initAjax(),
blob = owner._blob,
server = opts.server,
formData, binary, fr;
if ( opts.sendAsBinary ) {
server += opts.attachInfoToQuery !== false ? ((/\?/.test( server ) ? '&' : '?') +
$.param( owner._formData )) : '';
binary = blob.getSource();
} else {
formData = new FormData();
$.each( owner._formData, function( k, v ) {
formData.append( k, v );
});
formData.append( opts.fileVal, blob.getSource(),
opts.filename || owner._formData.name || '' );
}
if ( opts.withCredentials && 'withCredentials' in xhr ) {
xhr.open( opts.method, server, true );
xhr.withCredentials = true;
} else {
xhr.open( opts.method, server );
}
this._setRequestHeader( xhr, opts.headers );
if ( binary ) {
// 强制设置成 content-type 为文件流。
xhr.overrideMimeType &&
xhr.overrideMimeType('application/octet-stream');
// android直接发送blob会导致服务端接收到的是空文件。
// bug详情。
// https://code.google.com/p/android/issues/detail?id=39882
// 所以先用fileReader读取出来再通过arraybuffer的方式发送。
if ( Base.os.android ) {
fr = new FileReader();
fr.onload = function() {
xhr.send( this.result );
fr = fr.onload = null;
};
fr.readAsArrayBuffer( binary );
} else {
xhr.send( binary );
}
} else {
xhr.send( formData );
}
},
getResponse: function() {
return this._response;
},
getResponseAsJson: function() {
return this._parseJson( this._response );
},
getResponseHeaders: function() {
return this._headers;
},
getStatus: function() {
return this._status;
},
abort: function() {
var xhr = this._xhr;
if ( xhr ) {
xhr.upload.onprogress = noop;
xhr.onreadystatechange = noop;
xhr.abort();
this._xhr = xhr = null;
}
},
destroy: function() {
this.abort();
},
_parseHeader: function(raw) {
var ret = {};
raw && raw.replace(/^([^\:]+):(.*)$/mg, function(_, key, value) {
ret[key.trim()] = value.trim();
});
return ret;
},
_initAjax: function() {
var me = this,
xhr = new XMLHttpRequest(),
opts = this.options;
if ( opts.withCredentials && !('withCredentials' in xhr) &&
typeof XDomainRequest !== 'undefined' ) {
xhr = new XDomainRequest();
}
xhr.upload.onprogress = function( e ) {
var percentage = 0;
if ( e.lengthComputable ) {
percentage = e.loaded / e.total;
}
return me.trigger( 'progress', percentage );
};
xhr.onreadystatechange = function() {
if ( xhr.readyState !== 4 ) {
return;
}
xhr.upload.onprogress = noop;
xhr.onreadystatechange = noop;
me._xhr = null;
me._status = xhr.status;
var separator = '|', // 分隔符
// 拼接的状态,在 widgets/upload.js 会有代码用到这个分隔符
status = separator + xhr.status +
separator + xhr.statusText;
if ( xhr.status >= 200 && xhr.status < 300 ) {
me._response = xhr.responseText;
me._headers = me._parseHeader(xhr.getAllResponseHeaders());
return me.trigger('load');
} else if ( xhr.status >= 500 && xhr.status < 600 ) {
me._response = xhr.responseText;
me._headers = me._parseHeader(xhr.getAllResponseHeaders());
return me.trigger( 'error', 'server' + status );
}
return me.trigger( 'error', me._status ? 'http' + status : 'abort' );
};
me._xhr = xhr;
return xhr;
},
_setRequestHeader: function( xhr, headers ) {
$.each( headers, function( key, val ) {
xhr.setRequestHeader( key, val );
});
},
_parseJson: function( str ) {
var json;
try {
json = JSON.parse( str );
} catch ( ex ) {
json = {};
}
return json;
}
});
});
/**
* @fileOverview 只有html5实现的文件版本。
*/
define('preset/html5only',[
'base',
// widgets
'widgets/filednd',
'widgets/filepaste',
'widgets/filepicker',
'widgets/image',
'widgets/queue',
'widgets/runtime',
'widgets/upload',
'widgets/validator',
// runtimes
// html5
'runtime/html5/blob',
'runtime/html5/dnd',
'runtime/html5/filepaste',
'runtime/html5/filepicker',
'runtime/html5/imagemeta/exif',
'runtime/html5/image',
'runtime/html5/transport'
], function( Base ) {
return Base;
});
define('webuploader',[
'preset/html5only'
], function( preset ) {
return preset;
});
return require('webuploader');
});
================================================
FILE: dist/webuploader.js
================================================
/*! WebUploader 0.1.8-alpha */
/**
* @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
* @require "jquery"
* @require "zepto"
*/
define('dollar-third',[],function() {
var req = window.require;
var $ = window.__dollar ||
window.jQuery ||
window.Zepto ||
req('jquery') ||
req('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.8-alpha',
/**
* @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 错误信息
*/
define('lib/dnd',[
'base',
'mediator',
'runtime/client'
], function( Base, Mediator, RuntimeClent ) {
var $ = Base.$;
function DragAndDrop( opts ) {
opts = this.options = $.extend({}, DragAndDrop.options, opts );
opts.container = $( opts.container );
if ( !opts.container.length ) {
return;
}
RuntimeClent.call( this, 'DragAndDrop' );
}
DragAndDrop.options = {
accept: null,
disableGlobalDnd: false
};
Base.inherits( RuntimeClent, {
constructor: DragAndDrop,
init: function() {
var me = this;
me.connectRuntime( me.options, function() {
me.exec('init');
me.trigger('ready');
});
}
});
Mediator.installTo( DragAndDrop.prototype );
return DragAndDrop;
});
/**
* @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 DragAndDrop Widget。
*/
define('widgets/filednd',[
'base',
'uploader',
'lib/dnd',
'widgets/widget'
], function( Base, Uploader, Dnd ) {
var $ = Base.$;
Uploader.options.dnd = '';
/**
* @property {Selector} [dnd=undefined] 指定Drag And Drop拖拽的容器,如果不指定,则不启动。
* @namespace options
* @for Uploader
*/
/**
* @property {Selector} [disableGlobalDnd=false] 是否禁掉整个页面的拖拽功能,如果不禁用,图片拖进来的时候会默认被浏览器打开。
* @namespace options
* @for Uploader
*/
/**
* @event dndAccept
* @param {DataTransferItemList} items DataTransferItem
* @description 阻止此事件可以拒绝某些类型的文件拖入进来。目前只有 chrome 提供这样的 API,且只能通过 mime-type 验证。
* @for Uploader
*/
return Uploader.register({
name: 'dnd',
init: function( opts ) {
if ( !opts.dnd ||
this.request('predict-runtime-type') !== 'html5' ) {
return;
}
var me = this,
deferred = Base.Deferred(),
options = $.extend({}, {
disableGlobalDnd: opts.disableGlobalDnd,
container: opts.dnd,
accept: opts.accept
}),
dnd;
this.dnd = dnd = new Dnd( options );
dnd.once( 'ready', deferred.resolve );
dnd.on( 'drop', function( files ) {
me.request( 'add-file', [ files ]);
});
// 检测文件是否全部允许添加。
dnd.on( 'accept', function( items ) {
return me.owner.trigger( 'dndAccept', items );
});
dnd.init();
return deferred.promise();
},
destroy: function() {
this.dnd && this.dnd.destroy();
}
});
});
/**
* @fileOverview 错误信息
*/
define('lib/filepaste',[
'base',
'mediator',
'runtime/client'
], function( Base, Mediator, RuntimeClent ) {
var $ = Base.$;
function FilePaste( opts ) {
opts = this.options = $.extend({}, opts );
opts.container = $( opts.container || document.body );
RuntimeClent.call( this, 'FilePaste' );
}
Base.inherits( RuntimeClent, {
constructor: FilePaste,
init: function() {
var me = this;
me.connectRuntime( me.options, function() {
me.exec('init');
me.trigger('ready');
});
}
});
Mediator.installTo( FilePaste.prototype );
return FilePaste;
});
/**
* @fileOverview 组件基类。
*/
define('widgets/filepaste',[
'base',
'uploader',
'lib/filepaste',
'widgets/widget'
], function( Base, Uploader, FilePaste ) {
var $ = Base.$;
/**
* @property {Selector} [paste=undefined] 指定监听paste事件的容器,如果不指定,不启用此功能。此功能为通过粘贴来添加截屏的图片。建议设置为`document.body`.
* @namespace options
* @for Uploader
*/
return Uploader.register({
name: 'paste',
init: function( opts ) {
if ( !opts.paste ||
this.request('predict-runtime-type') !== 'html5' ) {
return;
}
var me = this,
deferred = Base.Deferred(),
options = $.extend({}, {
container: opts.paste,
accept: opts.accept
}),
paste;
this.paste = paste = new FilePaste( options );
paste.once( 'ready', deferred.resolve );
paste.on( 'paste', function( files ) {
me.owner.request( 'add-file', [ files ]);
});
paste.init();
return deferred.promise();
},
destroy: function() {
this.paste && this.paste.destroy();
}
});
});
/**
* @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 ||
file.lastModified && new Date(file.lastModified).toLocaleString() ||
(new Date()).toLocaleString();
Blob.apply( this, arguments );
}
return Base.inherits( Blob, File );
});
/**
* @fileOverview 错误信息
*/
define('lib/filepicker',[
'base',
'runtime/client',
'lib/file'
], function( Base, RuntimeClient, 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 );
RuntimeClient.call( this, 'FilePicker', true );
}
FilePicker.options = {
button: null,
container: null,
label: null,
innerHTML: null,
multiple: true,
accept: null,
name: 'file',
style: 'webuploader-pick' //pick element class attribute, default is "webuploader-pick"
};
Base.inherits( RuntimeClient, {
constructor: FilePicker,
init: function() {
var me = this,
opts = me.options,
button = opts.button,
style = opts.style;
if (style)
button.addClass('webuploader-pick');
me.on( 'all', function( type ) {
var files;
switch ( type ) {
case 'mouseenter':
if (style)
button.addClass('webuploader-pick-hover');
break;
case 'mouseleave':
if (style)
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(),
*/
width = button[0] && button[0].offsetWidth || button.outerWidth() || button.width(),
height = button[0] && button[0].offsetHeight || 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/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 {Array} [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.on('dialogopen', function() {
me.owner.trigger('dialogOpen', picker.button);
});
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.getAsDataUrl( opts.type ) );
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` 被移除的文件数。
* * `numOfInterrupt` 被中断的文件数。
* @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 ];
this._delFile(file);
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 );
});
}
},
_delFile : function(file){
for(var i = this._queue.length - 1 ; i >= 0 ; i-- ){
if(this._queue[i] == file){
this._queue.splice(i,1);
break;
}
}
},
_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 );
});
if ( files.length ) {
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();
},
getResponseHeaders: function() {
return this.exec('getResponseHeaders');
},
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 {Number} [chunkRetryDelay=1000]
* @namespace options
* @for Uploader
* @description 开启重试后,设置重试延时时间, 单位毫秒。默认1000毫秒,即1秒.
*/
chunkRetryDelay: 1000,
/**
* @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) {
file.setStatus( Status.QUEUED );
$.each( me.pool, function( _, v ) {
// 之前暂停过。
if (v.file !== file) {
return;
}
v.transport && v.transport.send();
file.setStatus( Status.PROGRESS );
});
} else if (file.getStatus() !== Status.PROGRESS) {
file.setStatus( Status.QUEUED );
}
} else {
$.each( me.request( 'get-files', [ Status.INITED ] ), function() {
this.setStatus( Status.QUEUED );
});
}
if ( me.runing ) {
me.owner.trigger('startUpload', file);// 开始上传或暂停恢复的,trigger event
return Base.nextTick( me.__tick );
}
me.runing = true;
var files = [];
// 如果有暂停的,则续传
file || $.each( me.pool, function( _, v ) {
var file = v.file;
if ( file.getStatus() === Status.INTERRUPT ) {
me._trigged = false;
files.push(file);
if (v.waiting) {
return;
}
// 文件 prepare 完后,如果暂停了,这个时候只会把文件插入 pool, 而不会创建 tranport,
v.transport ? v.transport.send() : me._doSend(v);
}
});
$.each(files, function() {
this.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) {
v.transport && v.transport.abort();
if (interrupt) {
me._putback(v);
me._popBlock(v);
}
}
});
me.owner.trigger('stopUpload', file);// 暂停,trigger event
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 );
},
/**
* 判断`Uploader`是否正在上传中。
* @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.remaning++;
block.file.remaning++;
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, 每个分片发送之前可能要做些异步的事情。
block.waiting = promise = me.request( 'before-send', block, function() {
delete block.waiting;
// 有可能文件已经上传出错了,所以不需要再传输了。
if ( file.getStatus() === Status.PROGRESS ) {
me._doSend( block );
} else if (block.file.getStatus() !== Status.INTERRUPT) {
me._popBlock(block);
}
Base.nextTick(me.__tick);
});
// 如果为fail了,则跳过此分片。
promise.fail(function() {
delete block.waiting;
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 = $.extend({}, me.options, block.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();
ret._headers = tr.getResponseHeaders();
block.response = ret;
fn = function( value ) {
reject = value;
};
// 服务端响应了,不代表成功了,询问是否响应正确。
if ( !owner.trigger( 'uploadAccept', block, ret, fn ) ) {
reject = reject || 'server';
}
return reject;
};
// 尝试重试,然后广播文件上传出错。
tr.on( 'error', function( type, flag ) {
// 在 runtime/html5/transport.js 上为 type 加上了状态码,形式:type|status|text(如:http-403-Forbidden)
// 这里把状态码解释出来,并还原后面代码所依赖的 type 变量
var typeArr = type.split( '|' ), status, statusText;
type = typeArr[0];
status = parseFloat( typeArr[1] ),
statusText = typeArr[2];
block.retried = block.retried || 0;
// 自动重试
if ( block.chunks > 1 && ~'http,abort,server'.indexOf( type.replace( /-.*/, '' ) ) &&
block.retried < opts.chunkRetry ) {
block.retried++;
me.retryTimer = setTimeout(function() {
tr.send();
}, opts.chunkRetryDelay || 1000);
} else {
// http status 500 ~ 600
if ( !flag && type === 'server' ) {
type = requestAccept( type );
}
file.setStatus( Status.ERROR, type );
owner.trigger( 'uploadError', file, type, status, statusText );
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 );
},
destroy: function() {
clearTimeout(this.retryTimer);
}
});
});
/**
* @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 ) {
// 增加beforeFileQueuedCheckfileNumLimit验证,主要为了再次加载时(已存在历史文件)验证数量是否超过设置项
if (!this.trigger('beforeFileQueuedCheckfileNumLimit', file,count)) {
return false;
}
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 Md5
*/
define('lib/md5',[
'runtime/client',
'mediator'
], function( RuntimeClient, Mediator ) {
function Md5() {
RuntimeClient.call( this, 'Md5' );
}
// 让 Md5 具备事件功能。
Mediator.installTo( Md5.prototype );
Md5.prototype.loadFromBlob = function( blob ) {
var me = this;
if ( me.getRuid() ) {
me.disconnectRuntime();
}
// 连接到blob归属的同一个runtime.
me.connectRuntime( blob.ruid, function() {
me.exec('init');
me.exec( 'loadFromBlob', blob );
});
};
Md5.prototype.getResult = function() {
return this.exec('getResult');
};
return Md5;
});
/**
* @fileOverview 图片操作, 负责预览图片和上传前压缩图片
*/
define('widgets/md5',[
'base',
'uploader',
'lib/md5',
'lib/blob',
'widgets/widget'
], function( Base, Uploader, Md5, Blob ) {
return Uploader.register({
name: 'md5',
/**
* 计算文件 md5 值,返回一个 promise 对象,可以监听 progress 进度。
*
*
* @method md5File
* @grammar md5File( file[, start[, end]] ) => promise
* @for Uploader
* @example
*
* uploader.on( 'fileQueued', function( file ) {
* var $li = ...;
*
* uploader.md5File( file )
*
* // 及时显示进度
* .progress(function(percentage) {
* console.log('Percentage:', percentage);
* })
*
* // 完成
* .then(function(val) {
* console.log('md5 result:', val);
* });
*
* });
*/
md5File: function( file, start, end ) {
var md5 = new Md5(),
deferred = Base.Deferred(),
blob = (file instanceof Blob) ? file :
this.request( 'get-file', file ).source;
md5.on( 'progress load', function( e ) {
e = e || {};
deferred.notify( e.total ? e.loaded / e.total : 1 );
});
md5.on( 'complete', function() {
deferred.resolve( md5.getResult() );
});
md5.on( 'error', function( reason ) {
deferred.reject( reason );
});
if ( arguments.length > 1 ) {
start = start || 0;
end = end || 0;
start < 0 && (start = blob.size + start);
end < 0 && (end = blob.size + end);
end = Math.min( end, blob.size );
blob = blob.slice( start, end );
}
md5.loadFromBlob( blob );
return deferred.promise();
}
});
});
/**
* @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 Html5Runtime
*/
define('runtime/html5/runtime',[
'base',
'runtime/runtime',
'runtime/compbase'
], function( Base, Runtime, CompBase ) {
var type = 'html5',
components = {};
function Html5Runtime() {
var pool = {},
me = this,
destroy = this.destroy;
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;
if ( components[ comp ] ) {
instance = pool[ uid ] = pool[ uid ] ||
new components[ comp ]( client, me );
if ( instance[ fn ] ) {
return instance[ fn ].apply( instance, args );
}
}
};
me.destroy = function() {
// @todo 删除池子中的所有实例
return destroy && destroy.apply( this, arguments );
};
}
Base.inherits( Runtime, {
constructor: Html5Runtime,
// 不需要连接其他程序,直接执行callback
init: function() {
var me = this;
setTimeout(function() {
me.trigger('ready');
}, 1 );
}
});
// 注册Components
Html5Runtime.register = function( name, component ) {
var klass = components[ name ] = Base.inherits( CompBase, component );
return klass;
};
// 注册html5运行时。
// 只有在支持的前提下注册。
if ( window.Blob && window.FileReader && window.DataView ) {
Runtime.addRuntime( type, Html5Runtime );
}
return Html5Runtime;
});
/**
* @fileOverview Blob Html实现
*/
define('runtime/html5/blob',[
'runtime/html5/runtime',
'lib/blob'
], function( Html5Runtime, Blob ) {
return Html5Runtime.register( 'Blob', {
slice: function( start, end ) {
var blob = this.owner.source,
slice = blob.slice || blob.webkitSlice || blob.mozSlice;
blob = slice.call( blob, start, end );
return new Blob( this.getRuid(), blob );
}
});
});
/**
* @fileOverview FilePaste
*/
define('runtime/html5/dnd',[
'base',
'runtime/html5/runtime',
'lib/file'
], function( Base, Html5Runtime, File ) {
var $ = Base.$,
prefix = 'webuploader-dnd-';
return Html5Runtime.register( 'DragAndDrop', {
init: function() {
var elem = this.elem = this.options.container;
this.dragEnterHandler = Base.bindFn( this._dragEnterHandler, this );
this.dragOverHandler = Base.bindFn( this._dragOverHandler, this );
this.dragLeaveHandler = Base.bindFn( this._dragLeaveHandler, this );
this.dropHandler = Base.bindFn( this._dropHandler, this );
this.dndOver = false;
elem.on( 'dragenter', this.dragEnterHandler );
elem.on( 'dragover', this.dragOverHandler );
elem.on( 'dragleave', this.dragLeaveHandler );
elem.on( 'drop', this.dropHandler );
if ( this.options.disableGlobalDnd ) {
$( document ).on( 'dragover', this.dragOverHandler );
$( document ).on( 'drop', this.dropHandler );
}
},
_dragEnterHandler: function( e ) {
var me = this,
denied = me._denied || false,
items;
e = e.originalEvent || e;
if ( !me.dndOver ) {
me.dndOver = true;
// 注意只有 chrome 支持。
items = e.dataTransfer.items;
if ( items && items.length ) {
me._denied = denied = !me.trigger( 'accept', items );
}
me.elem.addClass( prefix + 'over' );
me.elem[ denied ? 'addClass' :
'removeClass' ]( prefix + 'denied' );
}
e.dataTransfer.dropEffect = denied ? 'none' : 'copy';
return false;
},
_dragOverHandler: function( e ) {
// 只处理框内的。
var parentElem = this.elem.parent().get( 0 );
if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) {
return false;
}
clearTimeout( this._leaveTimer );
this._dragEnterHandler.call( this, e );
return false;
},
_dragLeaveHandler: function() {
var me = this,
handler;
handler = function() {
me.dndOver = false;
me.elem.removeClass( prefix + 'over ' + prefix + 'denied' );
};
clearTimeout( me._leaveTimer );
me._leaveTimer = setTimeout( handler, 100 );
return false;
},
_dropHandler: function( e ) {
var me = this,
ruid = me.getRuid(),
parentElem = me.elem.parent().get( 0 ),
dataTransfer, data;
// 只处理框内的。
if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) {
return false;
}
e = e.originalEvent || e;
dataTransfer = e.dataTransfer;
// 如果是页面内拖拽,还不能处理,不阻止事件。
// 此处 ie11 下会报参数错误,
try {
data = dataTransfer.getData('text/html');
} catch( err ) {
}
me.dndOver = false;
me.elem.removeClass( prefix + 'over' );
if ( !dataTransfer || data ) {
return;
}
me._getTansferFiles( dataTransfer, function( results ) {
me.trigger( 'drop', $.map( results, function( file ) {
return new File( ruid, file );
}) );
});
return false;
},
// 如果传入 callback 则去查看文件夹,否则只管当前文件夹。
_getTansferFiles: function( dataTransfer, callback ) {
var results = [],
promises = [],
items, files, file, item, i, len, canAccessFolder;
items = dataTransfer.items;
files = dataTransfer.files;
canAccessFolder = !!(items && items[ 0 ].webkitGetAsEntry);
for ( i = 0, len = files.length; i < len; i++ ) {
file = files[ i ];
item = items && items[ i ];
if ( canAccessFolder && item.webkitGetAsEntry().isDirectory ) {
promises.push( this._traverseDirectoryTree(
item.webkitGetAsEntry(), results ) );
} else {
results.push( file );
}
}
Base.when.apply( Base, promises ).done(function() {
if ( !results.length ) {
return;
}
callback( results );
});
},
_traverseDirectoryTree: function( entry, results ) {
var deferred = Base.Deferred(),
me = this;
if ( entry.isFile ) {
entry.file(function( file ) {
results.push( file );
deferred.resolve();
});
} else if ( entry.isDirectory ) {
entry.createReader().readEntries(function( entries ) {
var len = entries.length,
promises = [],
arr = [], // 为了保证顺序。
i;
for ( i = 0; i < len; i++ ) {
promises.push( me._traverseDirectoryTree(
entries[ i ], arr ) );
}
Base.when.apply( Base, promises ).then(function() {
results.push.apply( results, arr );
deferred.resolve();
}, deferred.reject );
});
}
return deferred.promise();
},
destroy: function() {
var elem = this.elem;
// 还没 init 就调用 destroy
if (!elem) {
return;
}
elem.off( 'dragenter', this.dragEnterHandler );
elem.off( 'dragover', this.dragOverHandler );
elem.off( 'dragleave', this.dragLeaveHandler );
elem.off( 'drop', this.dropHandler );
if ( this.options.disableGlobalDnd ) {
$( document ).off( 'dragover', this.dragOverHandler );
$( document ).off( 'drop', this.dropHandler );
}
}
});
});
/**
* @fileOverview FilePaste
*/
define('runtime/html5/filepaste',[
'base',
'runtime/html5/runtime',
'lib/file'
], function( Base, Html5Runtime, File ) {
return Html5Runtime.register( 'FilePaste', {
init: function() {
var opts = this.options,
elem = this.elem = opts.container,
accept = '.*',
arr, i, len, item;
// accetp的mimeTypes中生成匹配正则。
if ( opts.accept ) {
arr = [];
for ( i = 0, len = opts.accept.length; i < len; i++ ) {
item = opts.accept[ i ].mimeTypes;
item && arr.push( item );
}
if ( arr.length ) {
accept = arr.join(',');
accept = accept.replace( /,/g, '|' ).replace( /\*/g, '.*' );
}
}
this.accept = accept = new RegExp( accept, 'i' );
this.hander = Base.bindFn( this._pasteHander, this );
elem.on( 'paste', this.hander );
},
_pasteHander: function( e ) {
var allowed = [],
ruid = this.getRuid(),
items, item, blob, i, len;
e = e.originalEvent || e;
items = e.clipboardData.items;
for ( i = 0, len = items.length; i < len; i++ ) {
item = items[ i ];
if ( item.kind !== 'file' || !(blob = item.getAsFile()) ) {
continue;
}
allowed.push( new File( ruid, blob ) );
}
if ( allowed.length ) {
// 不阻止非文件粘贴(文字粘贴)的事件冒泡
e.preventDefault();
e.stopPropagation();
this.trigger( 'paste', allowed );
}
},
destroy: function() {
this.elem.off( 'paste', this.hander );
}
});
});
/**
* @fileOverview FilePicker
*/
define('runtime/html5/filepicker',[
'base',
'runtime/html5/runtime'
], function( Base, Html5Runtime ) {
var $ = Base.$;
return Html5Runtime.register( 'FilePicker', {
init: function() {
var container = this.getRuntime().getContainer(),
me = this,
owner = me.owner,
opts = me.options,
label = this.label = $( document.createElement('label') ),
input = this.input = $( document.createElement('input') ),
arr, i, len, mouseHandler, changeHandler;
input.attr( 'type', 'file' );
input.attr( 'capture', 'camera');
input.attr( 'name', opts.name );
input.addClass('webuploader-element-invisible');
label.on( 'click', function(e) {
input.trigger('click');
e.stopPropagation();
owner.trigger('dialogopen');
});
label.css({
opacity: 0,
width: '100%',
height: '100%',
display: 'block',
cursor: 'pointer',
background: '#ffffff'
});
if ( opts.multiple ) {
input.attr( 'multiple', 'multiple' );
}
// @todo Firefox不支持单独指定后缀
if ( opts.accept && opts.accept.length > 0 ) {
arr = [];
for ( i = 0, len = opts.accept.length; i < len; i++ ) {
arr.push( opts.accept[ i ].mimeTypes );
}
input.attr( 'accept', arr.join(',') );
}
container.append( input );
container.append( label );
mouseHandler = function( e ) {
owner.trigger( e.type );
};
changeHandler = function( e ) {
var clone;
// 解决chrome 56 第二次打开文件选择器,然后点击取消,依然会触发change事件的问题
if (e.target.files.length === 0){
return false;
}
// 第一次上传图片后,第二次再点击弹出文件选择器窗,等待
me.files = e.target.files;
// reset input
clone = this.cloneNode( true );
clone.value = null;
this.parentNode.replaceChild( clone, this );
input.off();
input = $( clone ).on( 'change', changeHandler )
.on( 'mouseenter mouseleave', mouseHandler );
owner.trigger('change');
}
input.on( 'change', changeHandler);
label.on( 'mouseenter mouseleave', mouseHandler );
},
getFiles: function() {
return this.files;
},
destroy: function() {
this.input.off();
this.label.off();
}
});
});
/**
* Terms:
*
* Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
* @fileOverview Image控件
*/
define('runtime/html5/util',[
'base'
], function( Base ) {
var urlAPI = window.createObjectURL && window ||
window.URL && URL.revokeObjectURL && URL ||
window.webkitURL,
createObjectURL = Base.noop,
revokeObjectURL = createObjectURL;
if ( urlAPI ) {
// 更安全的方式调用,比如android里面就能把context改成其他的对象。
createObjectURL = function() {
return urlAPI.createObjectURL.apply( urlAPI, arguments );
};
revokeObjectURL = function() {
return urlAPI.revokeObjectURL.apply( urlAPI, arguments );
};
}
return {
createObjectURL: createObjectURL,
revokeObjectURL: revokeObjectURL,
dataURL2Blob: function( dataURI ) {
var byteStr, intArray, ab, i, mimetype, parts;
parts = dataURI.split(',');
if ( ~parts[ 0 ].indexOf('base64') ) {
byteStr = atob( parts[ 1 ] );
} else {
byteStr = decodeURIComponent( parts[ 1 ] );
}
ab = new ArrayBuffer( byteStr.length );
intArray = new Uint8Array( ab );
for ( i = 0; i < byteStr.length; i++ ) {
intArray[ i ] = byteStr.charCodeAt( i );
}
mimetype = parts[ 0 ].split(':')[ 1 ].split(';')[ 0 ];
return this.arrayBufferToBlob( ab, mimetype );
},
dataURL2ArrayBuffer: function( dataURI ) {
var byteStr, intArray, i, parts;
parts = dataURI.split(',');
if ( ~parts[ 0 ].indexOf('base64') ) {
byteStr = atob( parts[ 1 ] );
} else {
byteStr = decodeURIComponent( parts[ 1 ] );
}
intArray = new Uint8Array( byteStr.length );
for ( i = 0; i < byteStr.length; i++ ) {
intArray[ i ] = byteStr.charCodeAt( i );
}
return intArray.buffer;
},
arrayBufferToBlob: function( buffer, type ) {
var builder = window.BlobBuilder || window.WebKitBlobBuilder,
bb;
// android不支持直接new Blob, 只能借助blobbuilder.
if ( builder ) {
bb = new builder();
bb.append( buffer );
return bb.getBlob( type );
}
return new Blob([ buffer ], type ? { type: type } : {} );
},
// 抽出来主要是为了解决android下面canvas.toDataUrl不支持jpeg.
// 你得到的结果是png.
canvasToDataUrl: function( canvas, type, quality ) {
return canvas.toDataURL( type, quality / 100 );
},
// imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
parseMeta: function( blob, callback ) {
callback( false, {});
},
// imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
updateImageHead: function( data ) {
return data;
}
};
});
/**
* Terms:
*
* Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
* @fileOverview Image控件
*/
define('runtime/html5/imagemeta',[
'runtime/html5/util'
], function( Util ) {
var api;
api = {
parsers: {
0xffe1: []
},
maxMetaDataSize: 262144,
parse: function( blob, cb ) {
var me = this,
fr = new FileReader();
fr.onload = function() {
cb( false, me._parse( this.result ) );
fr = fr.onload = fr.onerror = null;
};
fr.onerror = function( e ) {
cb( e.message );
fr = fr.onload = fr.onerror = null;
};
blob = blob.slice( 0, me.maxMetaDataSize );
fr.readAsArrayBuffer( blob.getSource() );
},
_parse: function( buffer, noParse ) {
if ( buffer.byteLength < 6 ) {
return;
}
var dataview = new DataView( buffer ),
offset = 2,
maxOffset = dataview.byteLength - 4,
headLength = offset,
ret = {},
markerBytes, markerLength, parsers, i;
if ( dataview.getUint16( 0 ) === 0xffd8 ) {
while ( offset < maxOffset ) {
markerBytes = dataview.getUint16( offset );
if ( markerBytes >= 0xffe0 && markerBytes <= 0xffef ||
markerBytes === 0xfffe ) {
markerLength = dataview.getUint16( offset + 2 ) + 2;
if ( offset + markerLength > dataview.byteLength ) {
break;
}
parsers = api.parsers[ markerBytes ];
if ( !noParse && parsers ) {
for ( i = 0; i < parsers.length; i += 1 ) {
parsers[ i ].call( api, dataview, offset,
markerLength, ret );
}
}
offset += markerLength;
headLength = offset;
} else {
break;
}
}
if ( headLength > 6 ) {
if ( buffer.slice ) {
ret.imageHead = buffer.slice( 2, headLength );
} else {
// Workaround for IE10, which does not yet
// support ArrayBuffer.slice:
ret.imageHead = new Uint8Array( buffer )
.subarray( 2, headLength );
}
}
}
return ret;
},
updateImageHead: function( buffer, head ) {
var data = this._parse( buffer, true ),
buf1, buf2, bodyoffset;
bodyoffset = 2;
if ( data.imageHead ) {
bodyoffset = 2 + data.imageHead.byteLength;
}
if ( buffer.slice ) {
buf2 = buffer.slice( bodyoffset );
} else {
buf2 = new Uint8Array( buffer ).subarray( bodyoffset );
}
buf1 = new Uint8Array( head.byteLength + 2 + buf2.byteLength );
buf1[ 0 ] = 0xFF;
buf1[ 1 ] = 0xD8;
buf1.set( new Uint8Array( head ), 2 );
buf1.set( new Uint8Array( buf2 ), head.byteLength + 2 );
return buf1.buffer;
}
};
Util.parseMeta = function() {
return api.parse.apply( api, arguments );
};
Util.updateImageHead = function() {
return api.updateImageHead.apply( api, arguments );
};
return api;
});
/**
* 代码来自于:https://github.com/blueimp/JavaScript-Load-Image
* 暂时项目中只用了orientation.
*
* 去除了 Exif Sub IFD Pointer, GPS Info IFD Pointer, Exif Thumbnail.
* @fileOverview EXIF解析
*/
// Sample
// ====================================
// Make : Apple
// Model : iPhone 4S
// Orientation : 1
// XResolution : 72 [72/1]
// YResolution : 72 [72/1]
// ResolutionUnit : 2
// Software : QuickTime 7.7.1
// DateTime : 2013:09:01 22:53:55
// ExifIFDPointer : 190
// ExposureTime : 0.058823529411764705 [1/17]
// FNumber : 2.4 [12/5]
// ExposureProgram : Normal program
// ISOSpeedRatings : 800
// ExifVersion : 0220
// DateTimeOriginal : 2013:09:01 22:52:51
// DateTimeDigitized : 2013:09:01 22:52:51
// ComponentsConfiguration : YCbCr
// ShutterSpeedValue : 4.058893515764426
// ApertureValue : 2.5260688216892597 [4845/1918]
// BrightnessValue : -0.3126686601998395
// MeteringMode : Pattern
// Flash : Flash did not fire, compulsory flash mode
// FocalLength : 4.28 [107/25]
// SubjectArea : [4 values]
// FlashpixVersion : 0100
// ColorSpace : 1
// PixelXDimension : 2448
// PixelYDimension : 3264
// SensingMethod : One-chip color area sensor
// ExposureMode : 0
// WhiteBalance : Auto white balance
// FocalLengthIn35mmFilm : 35
// SceneCaptureType : Standard
define('runtime/html5/imagemeta/exif',[
'base',
'runtime/html5/imagemeta'
], function( Base, ImageMeta ) {
var EXIF = {};
EXIF.ExifMap = function() {
return this;
};
EXIF.ExifMap.prototype.map = {
'Orientation': 0x0112
};
EXIF.ExifMap.prototype.get = function( id ) {
return this[ id ] || this[ this.map[ id ] ];
};
EXIF.exifTagTypes = {
// byte, 8-bit unsigned int:
1: {
getValue: function( dataView, dataOffset ) {
return dataView.getUint8( dataOffset );
},
size: 1
},
// ascii, 8-bit byte:
2: {
getValue: function( dataView, dataOffset ) {
return String.fromCharCode( dataView.getUint8( dataOffset ) );
},
size: 1,
ascii: true
},
// short, 16 bit int:
3: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getUint16( dataOffset, littleEndian );
},
size: 2
},
// long, 32 bit int:
4: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getUint32( dataOffset, littleEndian );
},
size: 4
},
// rational = two long values,
// first is numerator, second is denominator:
5: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getUint32( dataOffset, littleEndian ) /
dataView.getUint32( dataOffset + 4, littleEndian );
},
size: 8
},
// slong, 32 bit signed int:
9: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getInt32( dataOffset, littleEndian );
},
size: 4
},
// srational, two slongs, first is numerator, second is denominator:
10: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getInt32( dataOffset, littleEndian ) /
dataView.getInt32( dataOffset + 4, littleEndian );
},
size: 8
}
};
// undefined, 8-bit byte, value depending on field:
EXIF.exifTagTypes[ 7 ] = EXIF.exifTagTypes[ 1 ];
EXIF.getExifValue = function( dataView, tiffOffset, offset, type, length,
littleEndian ) {
var tagType = EXIF.exifTagTypes[ type ],
tagSize, dataOffset, values, i, str, c;
if ( !tagType ) {
Base.log('Invalid Exif data: Invalid tag type.');
return;
}
tagSize = tagType.size * length;
// Determine if the value is contained in the dataOffset bytes,
// or if the value at the dataOffset is a pointer to the actual data:
dataOffset = tagSize > 4 ? tiffOffset + dataView.getUint32( offset + 8,
littleEndian ) : (offset + 8);
if ( dataOffset + tagSize > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid data offset.');
return;
}
if ( length === 1 ) {
return tagType.getValue( dataView, dataOffset, littleEndian );
}
values = [];
for ( i = 0; i < length; i += 1 ) {
values[ i ] = tagType.getValue( dataView,
dataOffset + i * tagType.size, littleEndian );
}
if ( tagType.ascii ) {
str = '';
// Concatenate the chars:
for ( i = 0; i < values.length; i += 1 ) {
c = values[ i ];
// Ignore the terminating NULL byte(s):
if ( c === '\u0000' ) {
break;
}
str += c;
}
return str;
}
return values;
};
EXIF.parseExifTag = function( dataView, tiffOffset, offset, littleEndian,
data ) {
var tag = dataView.getUint16( offset, littleEndian );
data.exif[ tag ] = EXIF.getExifValue( dataView, tiffOffset, offset,
dataView.getUint16( offset + 2, littleEndian ), // tag type
dataView.getUint32( offset + 4, littleEndian ), // tag length
littleEndian );
};
EXIF.parseExifTags = function( dataView, tiffOffset, dirOffset,
littleEndian, data ) {
var tagsNumber, dirEndOffset, i;
if ( dirOffset + 6 > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid directory offset.');
return;
}
tagsNumber = dataView.getUint16( dirOffset, littleEndian );
dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
if ( dirEndOffset + 4 > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid directory size.');
return;
}
for ( i = 0; i < tagsNumber; i += 1 ) {
this.parseExifTag( dataView, tiffOffset,
dirOffset + 2 + 12 * i, // tag offset
littleEndian, data );
}
// Return the offset to the next directory:
return dataView.getUint32( dirEndOffset, littleEndian );
};
// EXIF.getExifThumbnail = function(dataView, offset, length) {
// var hexData,
// i,
// b;
// if (!length || offset + length > dataView.byteLength) {
// Base.log('Invalid Exif data: Invalid thumbnail data.');
// return;
// }
// hexData = [];
// for (i = 0; i < length; i += 1) {
// b = dataView.getUint8(offset + i);
// hexData.push((b < 16 ? '0' : '') + b.toString(16));
// }
// return 'data:image/jpeg,%' + hexData.join('%');
// };
EXIF.parseExifData = function( dataView, offset, length, data ) {
var tiffOffset = offset + 10,
littleEndian, dirOffset;
// Check for the ASCII code for "Exif" (0x45786966):
if ( dataView.getUint32( offset + 4 ) !== 0x45786966 ) {
// No Exif data, might be XMP data instead
return;
}
if ( tiffOffset + 8 > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid segment size.');
return;
}
// Check for the two null bytes:
if ( dataView.getUint16( offset + 8 ) !== 0x0000 ) {
Base.log('Invalid Exif data: Missing byte alignment offset.');
return;
}
// Check the byte alignment:
switch ( dataView.getUint16( tiffOffset ) ) {
case 0x4949:
littleEndian = true;
break;
case 0x4D4D:
littleEndian = false;
break;
default:
Base.log('Invalid Exif data: Invalid byte alignment marker.');
return;
}
// Check for the TIFF tag marker (0x002A):
if ( dataView.getUint16( tiffOffset + 2, littleEndian ) !== 0x002A ) {
Base.log('Invalid Exif data: Missing TIFF marker.');
return;
}
// Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
dirOffset = dataView.getUint32( tiffOffset + 4, littleEndian );
// Create the exif object to store the tags:
data.exif = new EXIF.ExifMap();
// Parse the tags of the main image directory and retrieve the
// offset to the next directory, usually the thumbnail directory:
dirOffset = EXIF.parseExifTags( dataView, tiffOffset,
tiffOffset + dirOffset, littleEndian, data );
// 尝试读取缩略图
// if ( dirOffset ) {
// thumbnailData = {exif: {}};
// dirOffset = EXIF.parseExifTags(
// dataView,
// tiffOffset,
// tiffOffset + dirOffset,
// littleEndian,
// thumbnailData
// );
// // Check for JPEG Thumbnail offset:
// if (thumbnailData.exif[0x0201]) {
// data.exif.Thumbnail = EXIF.getExifThumbnail(
// dataView,
// tiffOffset + thumbnailData.exif[0x0201],
// thumbnailData.exif[0x0202] // Thumbnail data length
// );
// }
// }
};
ImageMeta.parsers[ 0xffe1 ].push( EXIF.parseExifData );
return EXIF;
});
/**
* 这个方式性能不行,但是可以解决android里面的toDataUrl的bug
* android里面toDataUrl('image/jpege')得到的结果却是png.
*
* 所以这里没辙,只能借助这个工具
* @fileOverview jpeg encoder
*/
define('runtime/html5/jpegencoder',[], function( require, exports, module ) {
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009
Basic GUI blocking jpeg encoder
*/
function JPEGEncoder(quality) {
var self = this;
var fround = Math.round;
var ffloor = Math.floor;
var YTable = new Array(64);
var UVTable = new Array(64);
var fdtbl_Y = new Array(64);
var fdtbl_UV = new Array(64);
var YDC_HT;
var UVDC_HT;
var YAC_HT;
var UVAC_HT;
var bitcode = new Array(65535);
var category = new Array(65535);
var outputfDCTQuant = new Array(64);
var DU = new Array(64);
var byteout = [];
var bytenew = 0;
var bytepos = 7;
var YDU = new Array(64);
var UDU = new Array(64);
var VDU = new Array(64);
var clt = new Array(256);
var RGB_YUV_TABLE = new Array(2048);
var currentQuality;
var ZigZag = [
0, 1, 5, 6,14,15,27,28,
2, 4, 7,13,16,26,29,42,
3, 8,12,17,25,30,41,43,
9,11,18,24,31,40,44,53,
10,19,23,32,39,45,52,54,
20,22,33,38,46,51,55,60,
21,34,37,47,50,56,59,61,
35,36,48,49,57,58,62,63
];
var std_dc_luminance_nrcodes = [0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0];
var std_dc_luminance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
var std_ac_luminance_nrcodes = [0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d];
var std_ac_luminance_values = [
0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,
0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,
0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,
0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,
0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,
0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,
0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,
0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,
0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,
0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,
0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,
0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,
0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,
0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,
0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,
0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,
0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,
0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,
0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
0xf9,0xfa
];
var std_dc_chrominance_nrcodes = [0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0];
var std_dc_chrominance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
var std_ac_chrominance_nrcodes = [0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77];
var std_ac_chrominance_values = [
0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,
0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,
0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,
0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,
0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,
0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,
0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,
0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,
0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,
0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,
0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,
0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,
0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,
0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,
0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,
0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,
0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,
0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,
0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
0xf9,0xfa
];
function initQuantTables(sf){
var YQT = [
16, 11, 10, 16, 24, 40, 51, 61,
12, 12, 14, 19, 26, 58, 60, 55,
14, 13, 16, 24, 40, 57, 69, 56,
14, 17, 22, 29, 51, 87, 80, 62,
18, 22, 37, 56, 68,109,103, 77,
24, 35, 55, 64, 81,104,113, 92,
49, 64, 78, 87,103,121,120,101,
72, 92, 95, 98,112,100,103, 99
];
for (var i = 0; i < 64; i++) {
var t = ffloor((YQT[i]*sf+50)/100);
if (t < 1) {
t = 1;
} else if (t > 255) {
t = 255;
}
YTable[ZigZag[i]] = t;
}
var UVQT = [
17, 18, 24, 47, 99, 99, 99, 99,
18, 21, 26, 66, 99, 99, 99, 99,
24, 26, 56, 99, 99, 99, 99, 99,
47, 66, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99
];
for (var j = 0; j < 64; j++) {
var u = ffloor((UVQT[j]*sf+50)/100);
if (u < 1) {
u = 1;
} else if (u > 255) {
u = 255;
}
UVTable[ZigZag[j]] = u;
}
var aasf = [
1.0, 1.387039845, 1.306562965, 1.175875602,
1.0, 0.785694958, 0.541196100, 0.275899379
];
var k = 0;
for (var row = 0; row < 8; row++)
{
for (var col = 0; col < 8; col++)
{
fdtbl_Y[k] = (1.0 / (YTable [ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
fdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
k++;
}
}
}
function computeHuffmanTbl(nrcodes, std_table){
var codevalue = 0;
var pos_in_table = 0;
var HT = new Array();
for (var k = 1; k <= 16; k++) {
for (var j = 1; j <= nrcodes[k]; j++) {
HT[std_table[pos_in_table]] = [];
HT[std_table[pos_in_table]][0] = codevalue;
HT[std_table[pos_in_table]][1] = k;
pos_in_table++;
codevalue++;
}
codevalue*=2;
}
return HT;
}
function initHuffmanTbl()
{
YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values);
UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values);
YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values);
UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values);
}
function initCategoryNumber()
{
var nrlower = 1;
var nrupper = 2;
for (var cat = 1; cat <= 15; cat++) {
//Positive numbers
for (var nr = nrlower; nr>0] = 38470 * i;
RGB_YUV_TABLE[(i+ 512)>>0] = 7471 * i + 0x8000;
RGB_YUV_TABLE[(i+ 768)>>0] = -11059 * i;
RGB_YUV_TABLE[(i+1024)>>0] = -21709 * i;
RGB_YUV_TABLE[(i+1280)>>0] = 32768 * i + 0x807FFF;
RGB_YUV_TABLE[(i+1536)>>0] = -27439 * i;
RGB_YUV_TABLE[(i+1792)>>0] = - 5329 * i;
}
}
// IO functions
function writeBits(bs)
{
var value = bs[0];
var posval = bs[1]-1;
while ( posval >= 0 ) {
if (value & (1 << posval) ) {
bytenew |= (1 << bytepos);
}
posval--;
bytepos--;
if (bytepos < 0) {
if (bytenew == 0xFF) {
writeByte(0xFF);
writeByte(0);
}
else {
writeByte(bytenew);
}
bytepos=7;
bytenew=0;
}
}
}
function writeByte(value)
{
byteout.push(clt[value]); // write char directly instead of converting later
}
function writeWord(value)
{
writeByte((value>>8)&0xFF);
writeByte((value )&0xFF);
}
// DCT & quantization core
function fDCTQuant(data, fdtbl)
{
var d0, d1, d2, d3, d4, d5, d6, d7;
/* Pass 1: process rows. */
var dataOff=0;
var i;
var I8 = 8;
var I64 = 64;
for (i=0; i 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0);
//outputfDCTQuant[i] = fround(fDCTQuant);
}
return outputfDCTQuant;
}
function writeAPP0()
{
writeWord(0xFFE0); // marker
writeWord(16); // length
writeByte(0x4A); // J
writeByte(0x46); // F
writeByte(0x49); // I
writeByte(0x46); // F
writeByte(0); // = "JFIF",'\0'
writeByte(1); // versionhi
writeByte(1); // versionlo
writeByte(0); // xyunits
writeWord(1); // xdensity
writeWord(1); // ydensity
writeByte(0); // thumbnwidth
writeByte(0); // thumbnheight
}
function writeSOF0(width, height)
{
writeWord(0xFFC0); // marker
writeWord(17); // length, truecolor YUV JPG
writeByte(8); // precision
writeWord(height);
writeWord(width);
writeByte(3); // nrofcomponents
writeByte(1); // IdY
writeByte(0x11); // HVY
writeByte(0); // QTY
writeByte(2); // IdU
writeByte(0x11); // HVU
writeByte(1); // QTU
writeByte(3); // IdV
writeByte(0x11); // HVV
writeByte(1); // QTV
}
function writeDQT()
{
writeWord(0xFFDB); // marker
writeWord(132); // length
writeByte(0);
for (var i=0; i<64; i++) {
writeByte(YTable[i]);
}
writeByte(1);
for (var j=0; j<64; j++) {
writeByte(UVTable[j]);
}
}
function writeDHT()
{
writeWord(0xFFC4); // marker
writeWord(0x01A2); // length
writeByte(0); // HTYDCinfo
for (var i=0; i<16; i++) {
writeByte(std_dc_luminance_nrcodes[i+1]);
}
for (var j=0; j<=11; j++) {
writeByte(std_dc_luminance_values[j]);
}
writeByte(0x10); // HTYACinfo
for (var k=0; k<16; k++) {
writeByte(std_ac_luminance_nrcodes[k+1]);
}
for (var l=0; l<=161; l++) {
writeByte(std_ac_luminance_values[l]);
}
writeByte(1); // HTUDCinfo
for (var m=0; m<16; m++) {
writeByte(std_dc_chrominance_nrcodes[m+1]);
}
for (var n=0; n<=11; n++) {
writeByte(std_dc_chrominance_values[n]);
}
writeByte(0x11); // HTUACinfo
for (var o=0; o<16; o++) {
writeByte(std_ac_chrominance_nrcodes[o+1]);
}
for (var p=0; p<=161; p++) {
writeByte(std_ac_chrominance_values[p]);
}
}
function writeSOS()
{
writeWord(0xFFDA); // marker
writeWord(12); // length
writeByte(3); // nrofcomponents
writeByte(1); // IdY
writeByte(0); // HTY
writeByte(2); // IdU
writeByte(0x11); // HTU
writeByte(3); // IdV
writeByte(0x11); // HTV
writeByte(0); // Ss
writeByte(0x3f); // Se
writeByte(0); // Bf
}
function processDU(CDU, fdtbl, DC, HTDC, HTAC){
var EOB = HTAC[0x00];
var M16zeroes = HTAC[0xF0];
var pos;
var I16 = 16;
var I63 = 63;
var I64 = 64;
var DU_DCT = fDCTQuant(CDU, fdtbl);
//ZigZag reorder
for (var j=0;j0)&&(DU[end0pos]==0); end0pos--) {};
//end0pos = first element in reverse order !=0
if ( end0pos == 0) {
writeBits(EOB);
return DC;
}
var i = 1;
var lng;
while ( i <= end0pos ) {
var startpos = i;
for (; (DU[i]==0) && (i<=end0pos); ++i) {}
var nrzeroes = i-startpos;
if ( nrzeroes >= I16 ) {
lng = nrzeroes>>4;
for (var nrmarker=1; nrmarker <= lng; ++nrmarker)
writeBits(M16zeroes);
nrzeroes = nrzeroes&0xF;
}
pos = 32767+DU[i];
writeBits(HTAC[(nrzeroes<<4)+category[pos]]);
writeBits(bitcode[pos]);
i++;
}
if ( end0pos != I63 ) {
writeBits(EOB);
}
return DC;
}
function initCharLookupTable(){
var sfcc = String.fromCharCode;
for(var i=0; i < 256; i++){ ///// ACHTUNG // 255
clt[i] = sfcc(i);
}
}
this.encode = function(image,quality) // image data object
{
// var time_start = new Date().getTime();
if(quality) setQuality(quality);
// Initialize bit writer
byteout = new Array();
bytenew=0;
bytepos=7;
// Add JPEG headers
writeWord(0xFFD8); // SOI
writeAPP0();
writeDQT();
writeSOF0(image.width,image.height);
writeDHT();
writeSOS();
// Encode 8x8 macroblocks
var DCY=0;
var DCU=0;
var DCV=0;
bytenew=0;
bytepos=7;
this.encode.displayName = "_encode_";
var imageData = image.data;
var width = image.width;
var height = image.height;
var quadWidth = width*4;
var tripleWidth = width*3;
var x, y = 0;
var r, g, b;
var start,p, col,row,pos;
while(y < height){
x = 0;
while(x < quadWidth){
start = quadWidth * y + x;
p = start;
col = -1;
row = 0;
for(pos=0; pos < 64; pos++){
row = pos >> 3;// /8
col = ( pos & 7 ) * 4; // %8
p = start + ( row * quadWidth ) + col;
if(y+row >= height){ // padding bottom
p-= (quadWidth*(y+1+row-height));
}
if(x+col >= quadWidth){ // padding right
p-= ((x+col) - quadWidth +4)
}
r = imageData[ p++ ];
g = imageData[ p++ ];
b = imageData[ p++ ];
/* // calculate YUV values dynamically
YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80
UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));
VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));
*/
// use lookup table (slightly faster)
YDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256)>>0] + RGB_YUV_TABLE[(b + 512)>>0]) >> 16)-128;
UDU[pos] = ((RGB_YUV_TABLE[(r + 768)>>0] + RGB_YUV_TABLE[(g + 1024)>>0] + RGB_YUV_TABLE[(b + 1280)>>0]) >> 16)-128;
VDU[pos] = ((RGB_YUV_TABLE[(r + 1280)>>0] + RGB_YUV_TABLE[(g + 1536)>>0] + RGB_YUV_TABLE[(b + 1792)>>0]) >> 16)-128;
}
DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
x+=32;
}
y+=8;
}
////////////////////////////////////////////////////////////////
// Do the bit alignment of the EOI marker
if ( bytepos >= 0 ) {
var fillbits = [];
fillbits[1] = bytepos+1;
fillbits[0] = (1<<(bytepos+1))-1;
writeBits(fillbits);
}
writeWord(0xFFD9); //EOI
var jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join(''));
byteout = [];
// benchmarking
// var duration = new Date().getTime() - time_start;
// console.log('Encoding time: '+ currentQuality + 'ms');
//
return jpegDataUri
}
function setQuality(quality){
if (quality <= 0) {
quality = 1;
}
if (quality > 100) {
quality = 100;
}
if(currentQuality == quality) return // don't recalc if unchanged
var sf = 0;
if (quality < 50) {
sf = Math.floor(5000 / quality);
} else {
sf = Math.floor(200 - quality*2);
}
initQuantTables(sf);
currentQuality = quality;
// console.log('Quality set to: '+quality +'%');
}
function init(){
// var time_start = new Date().getTime();
if(!quality) quality = 50;
// Create tables
initCharLookupTable()
initHuffmanTbl();
initCategoryNumber();
initRGBYUVTable();
setQuality(quality);
// var duration = new Date().getTime() - time_start;
// console.log('Initialization '+ duration + 'ms');
}
init();
};
JPEGEncoder.encode = function( data, quality ) {
var encoder = new JPEGEncoder( quality );
return encoder.encode( data );
}
return JPEGEncoder;
});
/**
* @fileOverview Fix android canvas.toDataUrl bug.
*/
define('runtime/html5/androidpatch',[
'runtime/html5/util',
'runtime/html5/jpegencoder',
'base'
], function( Util, encoder, Base ) {
var origin = Util.canvasToDataUrl,
supportJpeg;
Util.canvasToDataUrl = function( canvas, type, quality ) {
var ctx, w, h, fragement, parts;
// 非android手机直接跳过。
if ( !Base.os.android ) {
return origin.apply( null, arguments );
}
// 检测是否canvas支持jpeg导出,根据数据格式来判断。
// JPEG 前两位分别是:255, 216
if ( type === 'image/jpeg' && typeof supportJpeg === 'undefined' ) {
fragement = origin.apply( null, arguments );
parts = fragement.split(',');
if ( ~parts[ 0 ].indexOf('base64') ) {
fragement = atob( parts[ 1 ] );
} else {
fragement = decodeURIComponent( parts[ 1 ] );
}
fragement = fragement.substring( 0, 2 );
supportJpeg = fragement.charCodeAt( 0 ) === 255 &&
fragement.charCodeAt( 1 ) === 216;
}
// 只有在android环境下才修复
if ( type === 'image/jpeg' && !supportJpeg ) {
w = canvas.width;
h = canvas.height;
ctx = canvas.getContext('2d');
return encoder.encode( ctx.getImageData( 0, 0, w, h ), quality );
}
return origin.apply( null, arguments );
};
});
/**
* @fileOverview Image
*/
define('runtime/html5/image',[
'base',
'runtime/html5/runtime',
'runtime/html5/util'
], function( Base, Html5Runtime, Util ) {
var BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D';
return Html5Runtime.register( 'Image', {
// flag: 标记是否被修改过。
modified: false,
init: function() {
var me = this,
img = new Image();
img.onload = function() {
me._info = {
type: me.type,
width: this.width,
height: this.height
};
//debugger;
// 读取meta信息。
if ( !me._metas && 'image/jpeg' === me.type ) {
Util.parseMeta( me._blob, function( error, ret ) {
me._metas = ret;
me.owner.trigger('load');
});
} else {
me.owner.trigger('load');
}
};
img.onerror = function() {
me.owner.trigger('error');
};
me._img = img;
},
loadFromBlob: function( blob ) {
var me = this,
img = me._img;
me._blob = blob;
me.type = blob.type;
img.src = Util.createObjectURL( blob.getSource() );
me.owner.once( 'load', function() {
Util.revokeObjectURL( img.src );
});
},
resize: function( width, height ) {
var canvas = this._canvas ||
(this._canvas = document.createElement('canvas'));
this._resize( this._img, canvas, width, height );
this._blob = null; // 没用了,可以删掉了。
this.modified = true;
this.owner.trigger( 'complete', 'resize' );
},
crop: function( x, y, w, h, s ) {
var cvs = this._canvas ||
(this._canvas = document.createElement('canvas')),
opts = this.options,
img = this._img,
iw = img.naturalWidth,
ih = img.naturalHeight,
orientation = this.getOrientation();
s = s || 1;
// todo 解决 orientation 的问题。
// values that require 90 degree rotation
// if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) {
// switch ( orientation ) {
// case 6:
// tmp = x;
// x = y;
// y = iw * s - tmp - w;
// console.log(ih * s, tmp, w)
// break;
// }
// (w ^= h, h ^= w, w ^= h);
// }
cvs.width = w;
cvs.height = h;
opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation );
this._renderImageToCanvas( cvs, img, -x, -y, iw * s, ih * s );
this._blob = null; // 没用了,可以删掉了。
this.modified = true;
this.owner.trigger( 'complete', 'crop' );
},
getAsBlob: function( type ) {
var blob = this._blob,
opts = this.options,
canvas;
type = type || this.type;
// blob需要重新生成。
if ( this.modified || this.type !== type ) {
canvas = this._canvas;
if ( type === 'image/jpeg' ) {
blob = Util.canvasToDataUrl( canvas, type, opts.quality );
if ( opts.preserveHeaders && this._metas &&
this._metas.imageHead ) {
blob = Util.dataURL2ArrayBuffer( blob );
blob = Util.updateImageHead( blob,
this._metas.imageHead );
blob = Util.arrayBufferToBlob( blob, type );
return blob;
}
} else {
blob = Util.canvasToDataUrl( canvas, type );
}
blob = Util.dataURL2Blob( blob );
}
return blob;
},
getAsDataUrl: function( type ) {
var opts = this.options;
type = type || this.type;
if ( type === 'image/jpeg' ) {
return Util.canvasToDataUrl( this._canvas, type, opts.quality );
} else {
return this._canvas.toDataURL( type );
}
},
getOrientation: function() {
return this._metas && this._metas.exif &&
this._metas.exif.get('Orientation') || 1;
},
info: function( val ) {
// setter
if ( val ) {
this._info = val;
return this;
}
// getter
return this._info;
},
meta: function( val ) {
// setter
if ( val ) {
this._metas = val;
return this;
}
// getter
return this._metas;
},
destroy: function() {
var canvas = this._canvas;
this._img.onload = null;
if ( canvas ) {
canvas.getContext('2d')
.clearRect( 0, 0, canvas.width, canvas.height );
canvas.width = canvas.height = 0;
this._canvas = null;
}
// 释放内存。非常重要,否则释放不了image的内存。
this._img.src = BLANK;
this._img = this._blob = null;
},
_resize: function( img, cvs, width, height ) {
var opts = this.options,
naturalWidth = img.width,
naturalHeight = img.height,
orientation = this.getOrientation(),
scale, w, h, x, y;
// values that require 90 degree rotation
if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) {
// 交换width, height的值。
width ^= height;
height ^= width;
width ^= height;
}
scale = Math[ opts.crop ? 'max' : 'min' ]( width / naturalWidth,
height / naturalHeight );
// 不允许放大。
opts.allowMagnify || (scale = Math.min( 1, scale ));
w = naturalWidth * scale;
h = naturalHeight * scale;
if ( opts.crop ) {
cvs.width = width;
cvs.height = height;
} else {
cvs.width = w;
cvs.height = h;
}
x = (cvs.width - w) / 2;
y = (cvs.height - h) / 2;
opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation );
this._renderImageToCanvas( cvs, img, x, y, w, h );
},
_rotate2Orientaion: function( canvas, orientation ) {
var width = canvas.width,
height = canvas.height,
ctx = canvas.getContext('2d');
switch ( orientation ) {
case 5:
case 6:
case 7:
case 8:
canvas.width = height;
canvas.height = width;
break;
}
switch ( orientation ) {
case 2: // horizontal flip
ctx.translate( width, 0 );
ctx.scale( -1, 1 );
break;
case 3: // 180 rotate left
ctx.translate( width, height );
ctx.rotate( Math.PI );
break;
case 4: // vertical flip
ctx.translate( 0, height );
ctx.scale( 1, -1 );
break;
case 5: // vertical flip + 90 rotate right
ctx.rotate( 0.5 * Math.PI );
ctx.scale( 1, -1 );
break;
case 6: // 90 rotate right
ctx.rotate( 0.5 * Math.PI );
ctx.translate( 0, -height );
break;
case 7: // horizontal flip + 90 rotate right
ctx.rotate( 0.5 * Math.PI );
ctx.translate( width, -height );
ctx.scale( -1, 1 );
break;
case 8: // 90 rotate left
ctx.rotate( -0.5 * Math.PI );
ctx.translate( -width, 0 );
break;
}
},
// https://github.com/stomita/ios-imagefile-megapixel/
// blob/master/src/megapix-image.js
_renderImageToCanvas: (function() {
// 如果不是ios, 不需要这么复杂!
if ( !Base.os.ios ) {
return function( canvas ) {
var args = Base.slice( arguments, 1 ),
ctx = canvas.getContext('2d');
ctx.drawImage.apply( ctx, args );
};
}
/**
* Detecting vertical squash in loaded image.
* Fixes a bug which squash image vertically while drawing into
* canvas for some images.
*/
function detectVerticalSquash( img, iw, ih ) {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
sy = 0,
ey = ih,
py = ih,
data, alpha, ratio;
canvas.width = 1;
canvas.height = ih;
ctx.drawImage( img, 0, 0 );
data = ctx.getImageData( 0, 0, 1, ih ).data;
// search image edge pixel position in case
// it is squashed vertically.
while ( py > sy ) {
alpha = data[ (py - 1) * 4 + 3 ];
if ( alpha === 0 ) {
ey = py;
} else {
sy = py;
}
py = (ey + sy) >> 1;
}
ratio = (py / ih);
return (ratio === 0) ? 1 : ratio;
}
// fix ie7 bug
// http://stackoverflow.com/questions/11929099/
// html5-canvas-drawimage-ratio-bug-ios
if ( Base.os.ios >= 7 ) {
return function( canvas, img, x, y, w, h ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
vertSquashRatio = detectVerticalSquash( img, iw, ih );
return canvas.getContext('2d').drawImage( img, 0, 0,
iw * vertSquashRatio, ih * vertSquashRatio,
x, y, w, h );
};
}
/**
* Detect subsampling in loaded image.
* In iOS, larger images than 2M pixels may be
* subsampled in rendering.
*/
function detectSubsampling( img ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
canvas, ctx;
// subsampling may happen overmegapixel image
if ( iw * ih > 1024 * 1024 ) {
canvas = document.createElement('canvas');
canvas.width = canvas.height = 1;
ctx = canvas.getContext('2d');
ctx.drawImage( img, -iw + 1, 0 );
// subsampled image becomes half smaller in rendering size.
// check alpha channel value to confirm image is covering
// edge pixel or not. if alpha value is 0
// image is not covering, hence subsampled.
return ctx.getImageData( 0, 0, 1, 1 ).data[ 3 ] === 0;
} else {
return false;
}
}
return function( canvas, img, x, y, width, height ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
ctx = canvas.getContext('2d'),
subsampled = detectSubsampling( img ),
doSquash = this.type === 'image/jpeg',
d = 1024,
sy = 0,
dy = 0,
tmpCanvas, tmpCtx, vertSquashRatio, dw, dh, sx, dx;
if ( subsampled ) {
iw /= 2;
ih /= 2;
}
ctx.save();
tmpCanvas = document.createElement('canvas');
tmpCanvas.width = tmpCanvas.height = d;
tmpCtx = tmpCanvas.getContext('2d');
vertSquashRatio = doSquash ?
detectVerticalSquash( img, iw, ih ) : 1;
dw = Math.ceil( d * width / iw );
dh = Math.ceil( d * height / ih / vertSquashRatio );
while ( sy < ih ) {
sx = 0;
dx = 0;
while ( sx < iw ) {
tmpCtx.clearRect( 0, 0, d, d );
tmpCtx.drawImage( img, -sx, -sy );
ctx.drawImage( tmpCanvas, 0, 0, d, d,
x + dx, y + dy, dw, dh );
sx += d;
dx += dw;
}
sy += d;
dy += dh;
}
ctx.restore();
tmpCanvas = tmpCtx = null;
};
})()
});
});
/**
* @fileOverview Transport
* @todo 支持chunked传输,优势:
* 可以将大文件分成小块,挨个传输,可以提高大文件成功率,当失败的时候,也只需要重传那小部分,
* 而不需要重头再传一次。另外断点续传也需要用chunked方式。
*/
define('runtime/html5/transport',[
'base',
'runtime/html5/runtime'
], function( Base, Html5Runtime ) {
var noop = Base.noop,
$ = Base.$;
return Html5Runtime.register( 'Transport', {
init: function() {
this._status = 0;
this._response = null;
},
send: function() {
var owner = this.owner,
opts = this.options,
xhr = this._initAjax(),
blob = owner._blob,
server = opts.server,
formData, binary, fr;
if ( opts.sendAsBinary ) {
server += opts.attachInfoToQuery !== false ? ((/\?/.test( server ) ? '&' : '?') +
$.param( owner._formData )) : '';
binary = blob.getSource();
} else {
formData = new FormData();
$.each( owner._formData, function( k, v ) {
formData.append( k, v );
});
formData.append( opts.fileVal, blob.getSource(),
opts.filename || owner._formData.name || '' );
}
if ( opts.withCredentials && 'withCredentials' in xhr ) {
xhr.open( opts.method, server, true );
xhr.withCredentials = true;
} else {
xhr.open( opts.method, server );
}
this._setRequestHeader( xhr, opts.headers );
if ( binary ) {
// 强制设置成 content-type 为文件流。
xhr.overrideMimeType &&
xhr.overrideMimeType('application/octet-stream');
// android直接发送blob会导致服务端接收到的是空文件。
// bug详情。
// https://code.google.com/p/android/issues/detail?id=39882
// 所以先用fileReader读取出来再通过arraybuffer的方式发送。
if ( Base.os.android ) {
fr = new FileReader();
fr.onload = function() {
xhr.send( this.result );
fr = fr.onload = null;
};
fr.readAsArrayBuffer( binary );
} else {
xhr.send( binary );
}
} else {
xhr.send( formData );
}
},
getResponse: function() {
return this._response;
},
getResponseAsJson: function() {
return this._parseJson( this._response );
},
getResponseHeaders: function() {
return this._headers;
},
getStatus: function() {
return this._status;
},
abort: function() {
var xhr = this._xhr;
if ( xhr ) {
xhr.upload.onprogress = noop;
xhr.onreadystatechange = noop;
xhr.abort();
this._xhr = xhr = null;
}
},
destroy: function() {
this.abort();
},
_parseHeader: function(raw) {
var ret = {};
raw && raw.replace(/^([^\:]+):(.*)$/mg, function(_, key, value) {
ret[key.trim()] = value.trim();
});
return ret;
},
_initAjax: function() {
var me = this,
xhr = new XMLHttpRequest(),
opts = this.options;
if ( opts.withCredentials && !('withCredentials' in xhr) &&
typeof XDomainRequest !== 'undefined' ) {
xhr = new XDomainRequest();
}
xhr.upload.onprogress = function( e ) {
var percentage = 0;
if ( e.lengthComputable ) {
percentage = e.loaded / e.total;
}
return me.trigger( 'progress', percentage );
};
xhr.onreadystatechange = function() {
if ( xhr.readyState !== 4 ) {
return;
}
xhr.upload.onprogress = noop;
xhr.onreadystatechange = noop;
me._xhr = null;
me._status = xhr.status;
var separator = '|', // 分隔符
// 拼接的状态,在 widgets/upload.js 会有代码用到这个分隔符
status = separator + xhr.status +
separator + xhr.statusText;
if ( xhr.status >= 200 && xhr.status < 300 ) {
me._response = xhr.responseText;
me._headers = me._parseHeader(xhr.getAllResponseHeaders());
return me.trigger('load');
} else if ( xhr.status >= 500 && xhr.status < 600 ) {
me._response = xhr.responseText;
me._headers = me._parseHeader(xhr.getAllResponseHeaders());
return me.trigger( 'error', 'server' + status );
}
return me.trigger( 'error', me._status ? 'http' + status : 'abort' );
};
me._xhr = xhr;
return xhr;
},
_setRequestHeader: function( xhr, headers ) {
$.each( headers, function( key, val ) {
xhr.setRequestHeader( key, val );
});
},
_parseJson: function( str ) {
var json;
try {
json = JSON.parse( str );
} catch ( ex ) {
json = {};
}
return json;
}
});
});
/**
* @fileOverview Transport flash实现
*/
define('runtime/html5/md5',[
'runtime/html5/runtime'
], function( FlashRuntime ) {
/*
* Fastest md5 implementation around (JKM md5)
* Credits: Joseph Myers
*
* @see http://www.myersdaily.org/joseph/javascript/md5-text.html
* @see http://jsperf.com/md5-shootout/7
*/
/* this function is much faster,
so if possible we use it. Some IEs
are the only ones I know of that
need the idiotic second function,
generated by an if clause. */
var add32 = function (a, b) {
return (a + b) & 0xFFFFFFFF;
},
cmn = function (q, a, b, x, s, t) {
a = add32(add32(a, q), add32(x, t));
return add32((a << s) | (a >>> (32 - s)), b);
},
ff = function (a, b, c, d, x, s, t) {
return cmn((b & c) | ((~b) & d), a, b, x, s, t);
},
gg = function (a, b, c, d, x, s, t) {
return cmn((b & d) | (c & (~d)), a, b, x, s, t);
},
hh = function (a, b, c, d, x, s, t) {
return cmn(b ^ c ^ d, a, b, x, s, t);
},
ii = function (a, b, c, d, x, s, t) {
return cmn(c ^ (b | (~d)), a, b, x, s, t);
},
md5cycle = function (x, k) {
var a = x[0],
b = x[1],
c = x[2],
d = x[3];
a = ff(a, b, c, d, k[0], 7, -680876936);
d = ff(d, a, b, c, k[1], 12, -389564586);
c = ff(c, d, a, b, k[2], 17, 606105819);
b = ff(b, c, d, a, k[3], 22, -1044525330);
a = ff(a, b, c, d, k[4], 7, -176418897);
d = ff(d, a, b, c, k[5], 12, 1200080426);
c = ff(c, d, a, b, k[6], 17, -1473231341);
b = ff(b, c, d, a, k[7], 22, -45705983);
a = ff(a, b, c, d, k[8], 7, 1770035416);
d = ff(d, a, b, c, k[9], 12, -1958414417);
c = ff(c, d, a, b, k[10], 17, -42063);
b = ff(b, c, d, a, k[11], 22, -1990404162);
a = ff(a, b, c, d, k[12], 7, 1804603682);
d = ff(d, a, b, c, k[13], 12, -40341101);
c = ff(c, d, a, b, k[14], 17, -1502002290);
b = ff(b, c, d, a, k[15], 22, 1236535329);
a = gg(a, b, c, d, k[1], 5, -165796510);
d = gg(d, a, b, c, k[6], 9, -1069501632);
c = gg(c, d, a, b, k[11], 14, 643717713);
b = gg(b, c, d, a, k[0], 20, -373897302);
a = gg(a, b, c, d, k[5], 5, -701558691);
d = gg(d, a, b, c, k[10], 9, 38016083);
c = gg(c, d, a, b, k[15], 14, -660478335);
b = gg(b, c, d, a, k[4], 20, -405537848);
a = gg(a, b, c, d, k[9], 5, 568446438);
d = gg(d, a, b, c, k[14], 9, -1019803690);
c = gg(c, d, a, b, k[3], 14, -187363961);
b = gg(b, c, d, a, k[8], 20, 1163531501);
a = gg(a, b, c, d, k[13], 5, -1444681467);
d = gg(d, a, b, c, k[2], 9, -51403784);
c = gg(c, d, a, b, k[7], 14, 1735328473);
b = gg(b, c, d, a, k[12], 20, -1926607734);
a = hh(a, b, c, d, k[5], 4, -378558);
d = hh(d, a, b, c, k[8], 11, -2022574463);
c = hh(c, d, a, b, k[11], 16, 1839030562);
b = hh(b, c, d, a, k[14], 23, -35309556);
a = hh(a, b, c, d, k[1], 4, -1530992060);
d = hh(d, a, b, c, k[4], 11, 1272893353);
c = hh(c, d, a, b, k[7], 16, -155497632);
b = hh(b, c, d, a, k[10], 23, -1094730640);
a = hh(a, b, c, d, k[13], 4, 681279174);
d = hh(d, a, b, c, k[0], 11, -358537222);
c = hh(c, d, a, b, k[3], 16, -722521979);
b = hh(b, c, d, a, k[6], 23, 76029189);
a = hh(a, b, c, d, k[9], 4, -640364487);
d = hh(d, a, b, c, k[12], 11, -421815835);
c = hh(c, d, a, b, k[15], 16, 530742520);
b = hh(b, c, d, a, k[2], 23, -995338651);
a = ii(a, b, c, d, k[0], 6, -198630844);
d = ii(d, a, b, c, k[7], 10, 1126891415);
c = ii(c, d, a, b, k[14], 15, -1416354905);
b = ii(b, c, d, a, k[5], 21, -57434055);
a = ii(a, b, c, d, k[12], 6, 1700485571);
d = ii(d, a, b, c, k[3], 10, -1894986606);
c = ii(c, d, a, b, k[10], 15, -1051523);
b = ii(b, c, d, a, k[1], 21, -2054922799);
a = ii(a, b, c, d, k[8], 6, 1873313359);
d = ii(d, a, b, c, k[15], 10, -30611744);
c = ii(c, d, a, b, k[6], 15, -1560198380);
b = ii(b, c, d, a, k[13], 21, 1309151649);
a = ii(a, b, c, d, k[4], 6, -145523070);
d = ii(d, a, b, c, k[11], 10, -1120210379);
c = ii(c, d, a, b, k[2], 15, 718787259);
b = ii(b, c, d, a, k[9], 21, -343485551);
x[0] = add32(a, x[0]);
x[1] = add32(b, x[1]);
x[2] = add32(c, x[2]);
x[3] = add32(d, x[3]);
},
/* there needs to be support for Unicode here,
* unless we pretend that we can redefine the MD-5
* algorithm for multi-byte characters (perhaps
* by adding every four 16-bit characters and
* shortening the sum to 32 bits). Otherwise
* I suggest performing MD-5 as if every character
* was two bytes--e.g., 0040 0025 = @%--but then
* how will an ordinary MD-5 sum be matched?
* There is no way to standardize text to something
* like UTF-8 before transformation; speed cost is
* utterly prohibitive. The JavaScript standard
* itself needs to look at this: it should start
* providing access to strings as preformed UTF-8
* 8-bit unsigned value arrays.
*/
md5blk = function (s) {
var md5blks = [],
i; /* Andy King said do it this way. */
for (i = 0; i < 64; i += 4) {
md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
}
return md5blks;
},
md5blk_array = function (a) {
var md5blks = [],
i; /* Andy King said do it this way. */
for (i = 0; i < 64; i += 4) {
md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
}
return md5blks;
},
md51 = function (s) {
var n = s.length,
state = [1732584193, -271733879, -1732584194, 271733878],
i,
length,
tail,
tmp,
lo,
hi;
for (i = 64; i <= n; i += 64) {
md5cycle(state, md5blk(s.substring(i - 64, i)));
}
s = s.substring(i - 64);
length = s.length;
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
}
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i = 0; i < 16; i += 1) {
tail[i] = 0;
}
}
// Beware that the final length might not fit in 32 bits so we take care of that
tmp = n * 8;
tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
lo = parseInt(tmp[2], 16);
hi = parseInt(tmp[1], 16) || 0;
tail[14] = lo;
tail[15] = hi;
md5cycle(state, tail);
return state;
},
md51_array = function (a) {
var n = a.length,
state = [1732584193, -271733879, -1732584194, 271733878],
i,
length,
tail,
tmp,
lo,
hi;
for (i = 64; i <= n; i += 64) {
md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
}
// Not sure if it is a bug, however IE10 will always produce a sub array of length 1
// containing the last element of the parent array if the sub array specified starts
// beyond the length of the parent array - weird.
// https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue
a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
length = a.length;
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= a[i] << ((i % 4) << 3);
}
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i = 0; i < 16; i += 1) {
tail[i] = 0;
}
}
// Beware that the final length might not fit in 32 bits so we take care of that
tmp = n * 8;
tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
lo = parseInt(tmp[2], 16);
hi = parseInt(tmp[1], 16) || 0;
tail[14] = lo;
tail[15] = hi;
md5cycle(state, tail);
return state;
},
hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'],
rhex = function (n) {
var s = '',
j;
for (j = 0; j < 4; j += 1) {
s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
}
return s;
},
hex = function (x) {
var i;
for (i = 0; i < x.length; i += 1) {
x[i] = rhex(x[i]);
}
return x.join('');
},
md5 = function (s) {
return hex(md51(s));
},
////////////////////////////////////////////////////////////////////////////
/**
* SparkMD5 OOP implementation.
*
* Use this class to perform an incremental md5, otherwise use the
* static methods instead.
*/
SparkMD5 = function () {
// call reset to init the instance
this.reset();
};
// In some cases the fast add32 function cannot be used..
if (md5('hello') !== '5d41402abc4b2a76b9719d911017c592') {
add32 = function (x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF),
msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
};
}
/**
* Appends a string.
* A conversion will be applied if an utf8 string is detected.
*
* @param {String} str The string to be appended
*
* @return {SparkMD5} The instance itself
*/
SparkMD5.prototype.append = function (str) {
// converts the string to utf8 bytes if necessary
if (/[\u0080-\uFFFF]/.test(str)) {
str = unescape(encodeURIComponent(str));
}
// then append as binary
this.appendBinary(str);
return this;
};
/**
* Appends a binary string.
*
* @param {String} contents The binary string to be appended
*
* @return {SparkMD5} The instance itself
*/
SparkMD5.prototype.appendBinary = function (contents) {
this._buff += contents;
this._length += contents.length;
var length = this._buff.length,
i;
for (i = 64; i <= length; i += 64) {
md5cycle(this._state, md5blk(this._buff.substring(i - 64, i)));
}
this._buff = this._buff.substr(i - 64);
return this;
};
/**
* Finishes the incremental computation, reseting the internal state and
* returning the result.
* Use the raw parameter to obtain the raw result instead of the hex one.
*
* @param {Boolean} raw True to get the raw result, false to get the hex result
*
* @return {String|Array} The result
*/
SparkMD5.prototype.end = function (raw) {
var buff = this._buff,
length = buff.length,
i,
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
ret;
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
}
this._finish(tail, length);
ret = !!raw ? this._state : hex(this._state);
this.reset();
return ret;
};
/**
* Finish the final calculation based on the tail.
*
* @param {Array} tail The tail (will be modified)
* @param {Number} length The length of the remaining buffer
*/
SparkMD5.prototype._finish = function (tail, length) {
var i = length,
tmp,
lo,
hi;
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(this._state, tail);
for (i = 0; i < 16; i += 1) {
tail[i] = 0;
}
}
// Do the final computation based on the tail and length
// Beware that the final length may not fit in 32 bits so we take care of that
tmp = this._length * 8;
tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
lo = parseInt(tmp[2], 16);
hi = parseInt(tmp[1], 16) || 0;
tail[14] = lo;
tail[15] = hi;
md5cycle(this._state, tail);
};
/**
* Resets the internal state of the computation.
*
* @return {SparkMD5} The instance itself
*/
SparkMD5.prototype.reset = function () {
this._buff = "";
this._length = 0;
this._state = [1732584193, -271733879, -1732584194, 271733878];
return this;
};
/**
* Releases memory used by the incremental buffer and other aditional
* resources. If you plan to use the instance again, use reset instead.
*/
SparkMD5.prototype.destroy = function () {
delete this._state;
delete this._buff;
delete this._length;
};
/**
* Performs the md5 hash on a string.
* A conversion will be applied if utf8 string is detected.
*
* @param {String} str The string
* @param {Boolean} raw True to get the raw result, false to get the hex result
*
* @return {String|Array} The result
*/
SparkMD5.hash = function (str, raw) {
// converts the string to utf8 bytes if necessary
if (/[\u0080-\uFFFF]/.test(str)) {
str = unescape(encodeURIComponent(str));
}
var hash = md51(str);
return !!raw ? hash : hex(hash);
};
/**
* Performs the md5 hash on a binary string.
*
* @param {String} content The binary string
* @param {Boolean} raw True to get the raw result, false to get the hex result
*
* @return {String|Array} The result
*/
SparkMD5.hashBinary = function (content, raw) {
var hash = md51(content);
return !!raw ? hash : hex(hash);
};
/**
* SparkMD5 OOP implementation for array buffers.
*
* Use this class to perform an incremental md5 ONLY for array buffers.
*/
SparkMD5.ArrayBuffer = function () {
// call reset to init the instance
this.reset();
};
////////////////////////////////////////////////////////////////////////////
/**
* Appends an array buffer.
*
* @param {ArrayBuffer} arr The array to be appended
*
* @return {SparkMD5.ArrayBuffer} The instance itself
*/
SparkMD5.ArrayBuffer.prototype.append = function (arr) {
// TODO: we could avoid the concatenation here but the algorithm would be more complex
// if you find yourself needing extra performance, please make a PR.
var buff = this._concatArrayBuffer(this._buff, arr),
length = buff.length,
i;
this._length += arr.byteLength;
for (i = 64; i <= length; i += 64) {
md5cycle(this._state, md5blk_array(buff.subarray(i - 64, i)));
}
// Avoids IE10 weirdness (documented above)
this._buff = (i - 64) < length ? buff.subarray(i - 64) : new Uint8Array(0);
return this;
};
/**
* Finishes the incremental computation, reseting the internal state and
* returning the result.
* Use the raw parameter to obtain the raw result instead of the hex one.
*
* @param {Boolean} raw True to get the raw result, false to get the hex result
*
* @return {String|Array} The result
*/
SparkMD5.ArrayBuffer.prototype.end = function (raw) {
var buff = this._buff,
length = buff.length,
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
i,
ret;
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= buff[i] << ((i % 4) << 3);
}
this._finish(tail, length);
ret = !!raw ? this._state : hex(this._state);
this.reset();
return ret;
};
SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
/**
* Resets the internal state of the computation.
*
* @return {SparkMD5.ArrayBuffer} The instance itself
*/
SparkMD5.ArrayBuffer.prototype.reset = function () {
this._buff = new Uint8Array(0);
this._length = 0;
this._state = [1732584193, -271733879, -1732584194, 271733878];
return this;
};
/**
* Releases memory used by the incremental buffer and other aditional
* resources. If you plan to use the instance again, use reset instead.
*/
SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
/**
* Concats two array buffers, returning a new one.
*
* @param {ArrayBuffer} first The first array buffer
* @param {ArrayBuffer} second The second array buffer
*
* @return {ArrayBuffer} The new array buffer
*/
SparkMD5.ArrayBuffer.prototype._concatArrayBuffer = function (first, second) {
var firstLength = first.length,
result = new Uint8Array(firstLength + second.byteLength);
result.set(first);
result.set(new Uint8Array(second), firstLength);
return result;
};
/**
* Performs the md5 hash on an array buffer.
*
* @param {ArrayBuffer} arr The array buffer
* @param {Boolean} raw True to get the raw result, false to get the hex result
*
* @return {String|Array} The result
*/
SparkMD5.ArrayBuffer.hash = function (arr, raw) {
var hash = md51_array(new Uint8Array(arr));
return !!raw ? hash : hex(hash);
};
return FlashRuntime.register( 'Md5', {
init: function() {
// do nothing.
},
loadFromBlob: function( file ) {
var blob = file.getSource(),
chunkSize = 2 * 1024 * 1024,
chunks = Math.ceil( blob.size / chunkSize ),
chunk = 0,
owner = this.owner,
spark = new SparkMD5.ArrayBuffer(),
me = this,
blobSlice = blob.mozSlice || blob.webkitSlice || blob.slice,
loadNext, fr;
fr = new FileReader();
loadNext = function() {
var start, end;
start = chunk * chunkSize;
end = Math.min( start + chunkSize, blob.size );
fr.onload = function( e ) {
spark.append( e.target.result );
owner.trigger( 'progress', {
total: file.size,
loaded: end
});
};
fr.onloadend = function() {
fr.onloadend = fr.onload = null;
if ( ++chunk < chunks ) {
setTimeout( loadNext, 1 );
} else {
setTimeout(function(){
owner.trigger('load');
me.result = spark.end();
loadNext = file = blob = spark = null;
owner.trigger('complete');
}, 50 );
}
};
fr.readAsArrayBuffer( blobSlice.call( blob, start, end ) );
};
loadNext();
},
getResult: function() {
return this.result;
}
});
});
/**
* @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 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;
},
getResponseHeaders: function() {
// flash 暂不支持
return {};
},
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-'+status;
} else {
err = 'http-'+status;
}
if ( readBody ) {
me._response = xhr.exec('getResponse');
me._response = decodeURIComponent( me._response );
// flash 处理可能存在 bug, 没辙只能靠 js 了
// try {
// me._responseJson = xhr.exec('getResponseAsJson');
// } catch ( error ) {
p = function( s ) {
try {
if (window.JSON && window.JSON.parse) {
return JSON.parse(s);
}
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() {
var status = xhr.exec('getStatus'),err = status?'http-'+status:'http';
xhr.off();
me._xhr = null;
me.trigger( 'error', err );
});
me._xhr = xhr;
return xhr;
},
_setRequestHeader: function( xhr, headers ) {
$.each( headers, function( key, val ) {
xhr.exec( 'setRequestHeader', key, val );
});
}
});
});
/**
* @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( this.getRuid(), blob );
}
});
});
/**
* @fileOverview Md5 flash实现
*/
define('runtime/flash/md5',[
'runtime/flash/runtime'
], function( FlashRuntime ) {
return FlashRuntime.register( 'Md5', {
init: function() {
// do nothing.
},
loadFromBlob: function( blob ) {
return this.flashExec( 'Md5', 'loadFromBlob', blob.uid );
}
});
});
/**
* @fileOverview 完全版本。
*/
define('preset/all',[
'base',
// widgets
'widgets/filednd',
'widgets/filepaste',
'widgets/filepicker',
'widgets/image',
'widgets/queue',
'widgets/runtime',
'widgets/upload',
'widgets/validator',
'widgets/md5',
// runtimes
// html5
'runtime/html5/blob',
'runtime/html5/dnd',
'runtime/html5/filepaste',
'runtime/html5/filepicker',
'runtime/html5/imagemeta/exif',
'runtime/html5/androidpatch',
'runtime/html5/image',
'runtime/html5/transport',
'runtime/html5/md5',
// flash
'runtime/flash/filepicker',
'runtime/flash/image',
'runtime/flash/transport',
'runtime/flash/blob',
'runtime/flash/md5'
], function( Base ) {
return Base;
});
/**
* @fileOverview 日志组件,主要用来收集错误信息,可以帮助 webuploader 更好的定位问题和发展。
*
* 如果您不想要启用此功能,请在打包的时候去掉 log 模块。
*
* 或者可以在初始化的时候通过 options.disableWidgets 属性禁用。
*
* 如:
* WebUploader.create({
* ...
*
* disableWidgets: 'log',
*
* ...
* })
*/
define('widgets/log',[
'base',
'uploader',
'widgets/widget'
], function( Base, Uploader ) {
var $ = Base.$,
logUrl = ' http://static.tieba.baidu.com/tb/pms/img/st.gif??',
product = (location.hostname || location.host || 'protected').toLowerCase(),
// 只针对 baidu 内部产品用户做统计功能。
enable = product && /baidu/i.exec(product),
base;
if (!enable) {
return;
}
base = {
dv: 3,
master: 'webuploader',
online: /test/.exec(product) ? 0 : 1,
module: '',
product: product,
type: 0
};
function send(data) {
var obj = $.extend({}, base, data),
url = logUrl.replace(/^(.*)\?/, '$1' + $.param( obj )),
image = new Image();
image.src = url;
}
return Uploader.register({
name: 'log',
init: function() {
var owner = this.owner,
count = 0,
size = 0;
owner
.on('error', function(code) {
send({
type: 2,
c_error_code: code
});
})
.on('uploadError', function(file, reason) {
send({
type: 2,
c_error_code: 'UPLOAD_ERROR',
c_reason: '' + reason
});
})
.on('uploadComplete', function(file) {
count++;
size += file.size;
}).
on('uploadFinished', function() {
send({
c_count: count,
c_size: size
});
count = size = 0;
});
send({
c_usage: 1
});
}
});
});
/**
* @fileOverview Uploader上传类
*/
define('webuploader',[
'preset/all',
'widgets/log'
], function( preset ) {
return preset;
});
return require('webuploader');
});
================================================
FILE: dist/webuploader.noimage.js
================================================
/*! WebUploader 0.1.8-alpha */
/**
* @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
* @require "jquery"
* @require "zepto"
*/
define('dollar-third',[],function() {
var req = window.require;
var $ = window.__dollar ||
window.jQuery ||
window.Zepto ||
req('jquery') ||
req('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.8-alpha',
/**
* @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 错误信息
*/
define('lib/dnd',[
'base',
'mediator',
'runtime/client'
], function( Base, Mediator, RuntimeClent ) {
var $ = Base.$;
function DragAndDrop( opts ) {
opts = this.options = $.extend({}, DragAndDrop.options, opts );
opts.container = $( opts.container );
if ( !opts.container.length ) {
return;
}
RuntimeClent.call( this, 'DragAndDrop' );
}
DragAndDrop.options = {
accept: null,
disableGlobalDnd: false
};
Base.inherits( RuntimeClent, {
constructor: DragAndDrop,
init: function() {
var me = this;
me.connectRuntime( me.options, function() {
me.exec('init');
me.trigger('ready');
});
}
});
Mediator.installTo( DragAndDrop.prototype );
return DragAndDrop;
});
/**
* @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 DragAndDrop Widget。
*/
define('widgets/filednd',[
'base',
'uploader',
'lib/dnd',
'widgets/widget'
], function( Base, Uploader, Dnd ) {
var $ = Base.$;
Uploader.options.dnd = '';
/**
* @property {Selector} [dnd=undefined] 指定Drag And Drop拖拽的容器,如果不指定,则不启动。
* @namespace options
* @for Uploader
*/
/**
* @property {Selector} [disableGlobalDnd=false] 是否禁掉整个页面的拖拽功能,如果不禁用,图片拖进来的时候会默认被浏览器打开。
* @namespace options
* @for Uploader
*/
/**
* @event dndAccept
* @param {DataTransferItemList} items DataTransferItem
* @description 阻止此事件可以拒绝某些类型的文件拖入进来。目前只有 chrome 提供这样的 API,且只能通过 mime-type 验证。
* @for Uploader
*/
return Uploader.register({
name: 'dnd',
init: function( opts ) {
if ( !opts.dnd ||
this.request('predict-runtime-type') !== 'html5' ) {
return;
}
var me = this,
deferred = Base.Deferred(),
options = $.extend({}, {
disableGlobalDnd: opts.disableGlobalDnd,
container: opts.dnd,
accept: opts.accept
}),
dnd;
this.dnd = dnd = new Dnd( options );
dnd.once( 'ready', deferred.resolve );
dnd.on( 'drop', function( files ) {
me.request( 'add-file', [ files ]);
});
// 检测文件是否全部允许添加。
dnd.on( 'accept', function( items ) {
return me.owner.trigger( 'dndAccept', items );
});
dnd.init();
return deferred.promise();
},
destroy: function() {
this.dnd && this.dnd.destroy();
}
});
});
/**
* @fileOverview 错误信息
*/
define('lib/filepaste',[
'base',
'mediator',
'runtime/client'
], function( Base, Mediator, RuntimeClent ) {
var $ = Base.$;
function FilePaste( opts ) {
opts = this.options = $.extend({}, opts );
opts.container = $( opts.container || document.body );
RuntimeClent.call( this, 'FilePaste' );
}
Base.inherits( RuntimeClent, {
constructor: FilePaste,
init: function() {
var me = this;
me.connectRuntime( me.options, function() {
me.exec('init');
me.trigger('ready');
});
}
});
Mediator.installTo( FilePaste.prototype );
return FilePaste;
});
/**
* @fileOverview 组件基类。
*/
define('widgets/filepaste',[
'base',
'uploader',
'lib/filepaste',
'widgets/widget'
], function( Base, Uploader, FilePaste ) {
var $ = Base.$;
/**
* @property {Selector} [paste=undefined] 指定监听paste事件的容器,如果不指定,不启用此功能。此功能为通过粘贴来添加截屏的图片。建议设置为`document.body`.
* @namespace options
* @for Uploader
*/
return Uploader.register({
name: 'paste',
init: function( opts ) {
if ( !opts.paste ||
this.request('predict-runtime-type') !== 'html5' ) {
return;
}
var me = this,
deferred = Base.Deferred(),
options = $.extend({}, {
container: opts.paste,
accept: opts.accept
}),
paste;
this.paste = paste = new FilePaste( options );
paste.once( 'ready', deferred.resolve );
paste.on( 'paste', function( files ) {
me.owner.request( 'add-file', [ files ]);
});
paste.init();
return deferred.promise();
},
destroy: function() {
this.paste && this.paste.destroy();
}
});
});
/**
* @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 ||
file.lastModified && new Date(file.lastModified).toLocaleString() ||
(new Date()).toLocaleString();
Blob.apply( this, arguments );
}
return Base.inherits( Blob, File );
});
/**
* @fileOverview 错误信息
*/
define('lib/filepicker',[
'base',
'runtime/client',
'lib/file'
], function( Base, RuntimeClient, 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 );
RuntimeClient.call( this, 'FilePicker', true );
}
FilePicker.options = {
button: null,
container: null,
label: null,
innerHTML: null,
multiple: true,
accept: null,
name: 'file',
style: 'webuploader-pick' //pick element class attribute, default is "webuploader-pick"
};
Base.inherits( RuntimeClient, {
constructor: FilePicker,
init: function() {
var me = this,
opts = me.options,
button = opts.button,
style = opts.style;
if (style)
button.addClass('webuploader-pick');
me.on( 'all', function( type ) {
var files;
switch ( type ) {
case 'mouseenter':
if (style)
button.addClass('webuploader-pick-hover');
break;
case 'mouseleave':
if (style)
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(),
*/
width = button[0] && button[0].offsetWidth || button.outerWidth() || button.width(),
height = button[0] && button[0].offsetHeight || 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/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 {Array} [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.on('dialogopen', function() {
me.owner.trigger('dialogOpen', picker.button);
});
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 文件属性封装
*/
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` 被移除的文件数。
* * `numOfInterrupt` 被中断的文件数。
* @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 ];
this._delFile(file);
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 );
});
}
},
_delFile : function(file){
for(var i = this._queue.length - 1 ; i >= 0 ; i-- ){
if(this._queue[i] == file){
this._queue.splice(i,1);
break;
}
}
},
_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 );
});
if ( files.length ) {
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();
},
getResponseHeaders: function() {
return this.exec('getResponseHeaders');
},
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 {Number} [chunkRetryDelay=1000]
* @namespace options
* @for Uploader
* @description 开启重试后,设置重试延时时间, 单位毫秒。默认1000毫秒,即1秒.
*/
chunkRetryDelay: 1000,
/**
* @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) {
file.setStatus( Status.QUEUED );
$.each( me.pool, function( _, v ) {
// 之前暂停过。
if (v.file !== file) {
return;
}
v.transport && v.transport.send();
file.setStatus( Status.PROGRESS );
});
} else if (file.getStatus() !== Status.PROGRESS) {
file.setStatus( Status.QUEUED );
}
} else {
$.each( me.request( 'get-files', [ Status.INITED ] ), function() {
this.setStatus( Status.QUEUED );
});
}
if ( me.runing ) {
me.owner.trigger('startUpload', file);// 开始上传或暂停恢复的,trigger event
return Base.nextTick( me.__tick );
}
me.runing = true;
var files = [];
// 如果有暂停的,则续传
file || $.each( me.pool, function( _, v ) {
var file = v.file;
if ( file.getStatus() === Status.INTERRUPT ) {
me._trigged = false;
files.push(file);
if (v.waiting) {
return;
}
// 文件 prepare 完后,如果暂停了,这个时候只会把文件插入 pool, 而不会创建 tranport,
v.transport ? v.transport.send() : me._doSend(v);
}
});
$.each(files, function() {
this.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) {
v.transport && v.transport.abort();
if (interrupt) {
me._putback(v);
me._popBlock(v);
}
}
});
me.owner.trigger('stopUpload', file);// 暂停,trigger event
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 );
},
/**
* 判断`Uploader`是否正在上传中。
* @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.remaning++;
block.file.remaning++;
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, 每个分片发送之前可能要做些异步的事情。
block.waiting = promise = me.request( 'before-send', block, function() {
delete block.waiting;
// 有可能文件已经上传出错了,所以不需要再传输了。
if ( file.getStatus() === Status.PROGRESS ) {
me._doSend( block );
} else if (block.file.getStatus() !== Status.INTERRUPT) {
me._popBlock(block);
}
Base.nextTick(me.__tick);
});
// 如果为fail了,则跳过此分片。
promise.fail(function() {
delete block.waiting;
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 = $.extend({}, me.options, block.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();
ret._headers = tr.getResponseHeaders();
block.response = ret;
fn = function( value ) {
reject = value;
};
// 服务端响应了,不代表成功了,询问是否响应正确。
if ( !owner.trigger( 'uploadAccept', block, ret, fn ) ) {
reject = reject || 'server';
}
return reject;
};
// 尝试重试,然后广播文件上传出错。
tr.on( 'error', function( type, flag ) {
// 在 runtime/html5/transport.js 上为 type 加上了状态码,形式:type|status|text(如:http-403-Forbidden)
// 这里把状态码解释出来,并还原后面代码所依赖的 type 变量
var typeArr = type.split( '|' ), status, statusText;
type = typeArr[0];
status = parseFloat( typeArr[1] ),
statusText = typeArr[2];
block.retried = block.retried || 0;
// 自动重试
if ( block.chunks > 1 && ~'http,abort,server'.indexOf( type.replace( /-.*/, '' ) ) &&
block.retried < opts.chunkRetry ) {
block.retried++;
me.retryTimer = setTimeout(function() {
tr.send();
}, opts.chunkRetryDelay || 1000);
} else {
// http status 500 ~ 600
if ( !flag && type === 'server' ) {
type = requestAccept( type );
}
file.setStatus( Status.ERROR, type );
owner.trigger( 'uploadError', file, type, status, statusText );
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 );
},
destroy: function() {
clearTimeout(this.retryTimer);
}
});
});
/**
* @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 ) {
// 增加beforeFileQueuedCheckfileNumLimit验证,主要为了再次加载时(已存在历史文件)验证数量是否超过设置项
if (!this.trigger('beforeFileQueuedCheckfileNumLimit', file,count)) {
return false;
}
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 Html5Runtime
*/
define('runtime/html5/runtime',[
'base',
'runtime/runtime',
'runtime/compbase'
], function( Base, Runtime, CompBase ) {
var type = 'html5',
components = {};
function Html5Runtime() {
var pool = {},
me = this,
destroy = this.destroy;
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;
if ( components[ comp ] ) {
instance = pool[ uid ] = pool[ uid ] ||
new components[ comp ]( client, me );
if ( instance[ fn ] ) {
return instance[ fn ].apply( instance, args );
}
}
};
me.destroy = function() {
// @todo 删除池子中的所有实例
return destroy && destroy.apply( this, arguments );
};
}
Base.inherits( Runtime, {
constructor: Html5Runtime,
// 不需要连接其他程序,直接执行callback
init: function() {
var me = this;
setTimeout(function() {
me.trigger('ready');
}, 1 );
}
});
// 注册Components
Html5Runtime.register = function( name, component ) {
var klass = components[ name ] = Base.inherits( CompBase, component );
return klass;
};
// 注册html5运行时。
// 只有在支持的前提下注册。
if ( window.Blob && window.FileReader && window.DataView ) {
Runtime.addRuntime( type, Html5Runtime );
}
return Html5Runtime;
});
/**
* @fileOverview Blob Html实现
*/
define('runtime/html5/blob',[
'runtime/html5/runtime',
'lib/blob'
], function( Html5Runtime, Blob ) {
return Html5Runtime.register( 'Blob', {
slice: function( start, end ) {
var blob = this.owner.source,
slice = blob.slice || blob.webkitSlice || blob.mozSlice;
blob = slice.call( blob, start, end );
return new Blob( this.getRuid(), blob );
}
});
});
/**
* @fileOverview FilePaste
*/
define('runtime/html5/dnd',[
'base',
'runtime/html5/runtime',
'lib/file'
], function( Base, Html5Runtime, File ) {
var $ = Base.$,
prefix = 'webuploader-dnd-';
return Html5Runtime.register( 'DragAndDrop', {
init: function() {
var elem = this.elem = this.options.container;
this.dragEnterHandler = Base.bindFn( this._dragEnterHandler, this );
this.dragOverHandler = Base.bindFn( this._dragOverHandler, this );
this.dragLeaveHandler = Base.bindFn( this._dragLeaveHandler, this );
this.dropHandler = Base.bindFn( this._dropHandler, this );
this.dndOver = false;
elem.on( 'dragenter', this.dragEnterHandler );
elem.on( 'dragover', this.dragOverHandler );
elem.on( 'dragleave', this.dragLeaveHandler );
elem.on( 'drop', this.dropHandler );
if ( this.options.disableGlobalDnd ) {
$( document ).on( 'dragover', this.dragOverHandler );
$( document ).on( 'drop', this.dropHandler );
}
},
_dragEnterHandler: function( e ) {
var me = this,
denied = me._denied || false,
items;
e = e.originalEvent || e;
if ( !me.dndOver ) {
me.dndOver = true;
// 注意只有 chrome 支持。
items = e.dataTransfer.items;
if ( items && items.length ) {
me._denied = denied = !me.trigger( 'accept', items );
}
me.elem.addClass( prefix + 'over' );
me.elem[ denied ? 'addClass' :
'removeClass' ]( prefix + 'denied' );
}
e.dataTransfer.dropEffect = denied ? 'none' : 'copy';
return false;
},
_dragOverHandler: function( e ) {
// 只处理框内的。
var parentElem = this.elem.parent().get( 0 );
if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) {
return false;
}
clearTimeout( this._leaveTimer );
this._dragEnterHandler.call( this, e );
return false;
},
_dragLeaveHandler: function() {
var me = this,
handler;
handler = function() {
me.dndOver = false;
me.elem.removeClass( prefix + 'over ' + prefix + 'denied' );
};
clearTimeout( me._leaveTimer );
me._leaveTimer = setTimeout( handler, 100 );
return false;
},
_dropHandler: function( e ) {
var me = this,
ruid = me.getRuid(),
parentElem = me.elem.parent().get( 0 ),
dataTransfer, data;
// 只处理框内的。
if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) {
return false;
}
e = e.originalEvent || e;
dataTransfer = e.dataTransfer;
// 如果是页面内拖拽,还不能处理,不阻止事件。
// 此处 ie11 下会报参数错误,
try {
data = dataTransfer.getData('text/html');
} catch( err ) {
}
me.dndOver = false;
me.elem.removeClass( prefix + 'over' );
if ( !dataTransfer || data ) {
return;
}
me._getTansferFiles( dataTransfer, function( results ) {
me.trigger( 'drop', $.map( results, function( file ) {
return new File( ruid, file );
}) );
});
return false;
},
// 如果传入 callback 则去查看文件夹,否则只管当前文件夹。
_getTansferFiles: function( dataTransfer, callback ) {
var results = [],
promises = [],
items, files, file, item, i, len, canAccessFolder;
items = dataTransfer.items;
files = dataTransfer.files;
canAccessFolder = !!(items && items[ 0 ].webkitGetAsEntry);
for ( i = 0, len = files.length; i < len; i++ ) {
file = files[ i ];
item = items && items[ i ];
if ( canAccessFolder && item.webkitGetAsEntry().isDirectory ) {
promises.push( this._traverseDirectoryTree(
item.webkitGetAsEntry(), results ) );
} else {
results.push( file );
}
}
Base.when.apply( Base, promises ).done(function() {
if ( !results.length ) {
return;
}
callback( results );
});
},
_traverseDirectoryTree: function( entry, results ) {
var deferred = Base.Deferred(),
me = this;
if ( entry.isFile ) {
entry.file(function( file ) {
results.push( file );
deferred.resolve();
});
} else if ( entry.isDirectory ) {
entry.createReader().readEntries(function( entries ) {
var len = entries.length,
promises = [],
arr = [], // 为了保证顺序。
i;
for ( i = 0; i < len; i++ ) {
promises.push( me._traverseDirectoryTree(
entries[ i ], arr ) );
}
Base.when.apply( Base, promises ).then(function() {
results.push.apply( results, arr );
deferred.resolve();
}, deferred.reject );
});
}
return deferred.promise();
},
destroy: function() {
var elem = this.elem;
// 还没 init 就调用 destroy
if (!elem) {
return;
}
elem.off( 'dragenter', this.dragEnterHandler );
elem.off( 'dragover', this.dragOverHandler );
elem.off( 'dragleave', this.dragLeaveHandler );
elem.off( 'drop', this.dropHandler );
if ( this.options.disableGlobalDnd ) {
$( document ).off( 'dragover', this.dragOverHandler );
$( document ).off( 'drop', this.dropHandler );
}
}
});
});
/**
* @fileOverview FilePaste
*/
define('runtime/html5/filepaste',[
'base',
'runtime/html5/runtime',
'lib/file'
], function( Base, Html5Runtime, File ) {
return Html5Runtime.register( 'FilePaste', {
init: function() {
var opts = this.options,
elem = this.elem = opts.container,
accept = '.*',
arr, i, len, item;
// accetp的mimeTypes中生成匹配正则。
if ( opts.accept ) {
arr = [];
for ( i = 0, len = opts.accept.length; i < len; i++ ) {
item = opts.accept[ i ].mimeTypes;
item && arr.push( item );
}
if ( arr.length ) {
accept = arr.join(',');
accept = accept.replace( /,/g, '|' ).replace( /\*/g, '.*' );
}
}
this.accept = accept = new RegExp( accept, 'i' );
this.hander = Base.bindFn( this._pasteHander, this );
elem.on( 'paste', this.hander );
},
_pasteHander: function( e ) {
var allowed = [],
ruid = this.getRuid(),
items, item, blob, i, len;
e = e.originalEvent || e;
items = e.clipboardData.items;
for ( i = 0, len = items.length; i < len; i++ ) {
item = items[ i ];
if ( item.kind !== 'file' || !(blob = item.getAsFile()) ) {
continue;
}
allowed.push( new File( ruid, blob ) );
}
if ( allowed.length ) {
// 不阻止非文件粘贴(文字粘贴)的事件冒泡
e.preventDefault();
e.stopPropagation();
this.trigger( 'paste', allowed );
}
},
destroy: function() {
this.elem.off( 'paste', this.hander );
}
});
});
/**
* @fileOverview FilePicker
*/
define('runtime/html5/filepicker',[
'base',
'runtime/html5/runtime'
], function( Base, Html5Runtime ) {
var $ = Base.$;
return Html5Runtime.register( 'FilePicker', {
init: function() {
var container = this.getRuntime().getContainer(),
me = this,
owner = me.owner,
opts = me.options,
label = this.label = $( document.createElement('label') ),
input = this.input = $( document.createElement('input') ),
arr, i, len, mouseHandler, changeHandler;
input.attr( 'type', 'file' );
input.attr( 'capture', 'camera');
input.attr( 'name', opts.name );
input.addClass('webuploader-element-invisible');
label.on( 'click', function(e) {
input.trigger('click');
e.stopPropagation();
owner.trigger('dialogopen');
});
label.css({
opacity: 0,
width: '100%',
height: '100%',
display: 'block',
cursor: 'pointer',
background: '#ffffff'
});
if ( opts.multiple ) {
input.attr( 'multiple', 'multiple' );
}
// @todo Firefox不支持单独指定后缀
if ( opts.accept && opts.accept.length > 0 ) {
arr = [];
for ( i = 0, len = opts.accept.length; i < len; i++ ) {
arr.push( opts.accept[ i ].mimeTypes );
}
input.attr( 'accept', arr.join(',') );
}
container.append( input );
container.append( label );
mouseHandler = function( e ) {
owner.trigger( e.type );
};
changeHandler = function( e ) {
var clone;
// 解决chrome 56 第二次打开文件选择器,然后点击取消,依然会触发change事件的问题
if (e.target.files.length === 0){
return false;
}
// 第一次上传图片后,第二次再点击弹出文件选择器窗,等待
me.files = e.target.files;
// reset input
clone = this.cloneNode( true );
clone.value = null;
this.parentNode.replaceChild( clone, this );
input.off();
input = $( clone ).on( 'change', changeHandler )
.on( 'mouseenter mouseleave', mouseHandler );
owner.trigger('change');
}
input.on( 'change', changeHandler);
label.on( 'mouseenter mouseleave', mouseHandler );
},
getFiles: function() {
return this.files;
},
destroy: function() {
this.input.off();
this.label.off();
}
});
});
/**
* @fileOverview Transport
* @todo 支持chunked传输,优势:
* 可以将大文件分成小块,挨个传输,可以提高大文件成功率,当失败的时候,也只需要重传那小部分,
* 而不需要重头再传一次。另外断点续传也需要用chunked方式。
*/
define('runtime/html5/transport',[
'base',
'runtime/html5/runtime'
], function( Base, Html5Runtime ) {
var noop = Base.noop,
$ = Base.$;
return Html5Runtime.register( 'Transport', {
init: function() {
this._status = 0;
this._response = null;
},
send: function() {
var owner = this.owner,
opts = this.options,
xhr = this._initAjax(),
blob = owner._blob,
server = opts.server,
formData, binary, fr;
if ( opts.sendAsBinary ) {
server += opts.attachInfoToQuery !== false ? ((/\?/.test( server ) ? '&' : '?') +
$.param( owner._formData )) : '';
binary = blob.getSource();
} else {
formData = new FormData();
$.each( owner._formData, function( k, v ) {
formData.append( k, v );
});
formData.append( opts.fileVal, blob.getSource(),
opts.filename || owner._formData.name || '' );
}
if ( opts.withCredentials && 'withCredentials' in xhr ) {
xhr.open( opts.method, server, true );
xhr.withCredentials = true;
} else {
xhr.open( opts.method, server );
}
this._setRequestHeader( xhr, opts.headers );
if ( binary ) {
// 强制设置成 content-type 为文件流。
xhr.overrideMimeType &&
xhr.overrideMimeType('application/octet-stream');
// android直接发送blob会导致服务端接收到的是空文件。
// bug详情。
// https://code.google.com/p/android/issues/detail?id=39882
// 所以先用fileReader读取出来再通过arraybuffer的方式发送。
if ( Base.os.android ) {
fr = new FileReader();
fr.onload = function() {
xhr.send( this.result );
fr = fr.onload = null;
};
fr.readAsArrayBuffer( binary );
} else {
xhr.send( binary );
}
} else {
xhr.send( formData );
}
},
getResponse: function() {
return this._response;
},
getResponseAsJson: function() {
return this._parseJson( this._response );
},
getResponseHeaders: function() {
return this._headers;
},
getStatus: function() {
return this._status;
},
abort: function() {
var xhr = this._xhr;
if ( xhr ) {
xhr.upload.onprogress = noop;
xhr.onreadystatechange = noop;
xhr.abort();
this._xhr = xhr = null;
}
},
destroy: function() {
this.abort();
},
_parseHeader: function(raw) {
var ret = {};
raw && raw.replace(/^([^\:]+):(.*)$/mg, function(_, key, value) {
ret[key.trim()] = value.trim();
});
return ret;
},
_initAjax: function() {
var me = this,
xhr = new XMLHttpRequest(),
opts = this.options;
if ( opts.withCredentials && !('withCredentials' in xhr) &&
typeof XDomainRequest !== 'undefined' ) {
xhr = new XDomainRequest();
}
xhr.upload.onprogress = function( e ) {
var percentage = 0;
if ( e.lengthComputable ) {
percentage = e.loaded / e.total;
}
return me.trigger( 'progress', percentage );
};
xhr.onreadystatechange = function() {
if ( xhr.readyState !== 4 ) {
return;
}
xhr.upload.onprogress = noop;
xhr.onreadystatechange = noop;
me._xhr = null;
me._status = xhr.status;
var separator = '|', // 分隔符
// 拼接的状态,在 widgets/upload.js 会有代码用到这个分隔符
status = separator + xhr.status +
separator + xhr.statusText;
if ( xhr.status >= 200 && xhr.status < 300 ) {
me._response = xhr.responseText;
me._headers = me._parseHeader(xhr.getAllResponseHeaders());
return me.trigger('load');
} else if ( xhr.status >= 500 && xhr.status < 600 ) {
me._response = xhr.responseText;
me._headers = me._parseHeader(xhr.getAllResponseHeaders());
return me.trigger( 'error', 'server' + status );
}
return me.trigger( 'error', me._status ? 'http' + status : 'abort' );
};
me._xhr = xhr;
return xhr;
},
_setRequestHeader: function( xhr, headers ) {
$.each( headers, function( key, val ) {
xhr.setRequestHeader( key, val );
});
},
_parseJson: function( str ) {
var json;
try {
json = JSON.parse( str );
} catch ( ex ) {
json = {};
}
return json;
}
});
});
/**
* @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 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;
},
getResponseHeaders: function() {
// flash 暂不支持
return {};
},
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-'+status;
} else {
err = 'http-'+status;
}
if ( readBody ) {
me._response = xhr.exec('getResponse');
me._response = decodeURIComponent( me._response );
// flash 处理可能存在 bug, 没辙只能靠 js 了
// try {
// me._responseJson = xhr.exec('getResponseAsJson');
// } catch ( error ) {
p = function( s ) {
try {
if (window.JSON && window.JSON.parse) {
return JSON.parse(s);
}
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() {
var status = xhr.exec('getStatus'),err = status?'http-'+status:'http';
xhr.off();
me._xhr = null;
me.trigger( 'error', err );
});
me._xhr = xhr;
return xhr;
},
_setRequestHeader: function( xhr, headers ) {
$.each( headers, function( key, val ) {
xhr.exec( 'setRequestHeader', key, val );
});
}
});
});
/**
* @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( this.getRuid(), blob );
}
});
});
/**
* @fileOverview 没有图像处理的版本。
*/
define('preset/withoutimage',[
'base',
// widgets
'widgets/filednd',
'widgets/filepaste',
'widgets/filepicker',
'widgets/queue',
'widgets/runtime',
'widgets/upload',
'widgets/validator',
// runtimes
// html5
'runtime/html5/blob',
'runtime/html5/dnd',
'runtime/html5/filepaste',
'runtime/html5/filepicker',
'runtime/html5/transport',
// flash
'runtime/flash/filepicker',
'runtime/flash/transport',
'runtime/flash/blob'
], function( Base ) {
return Base;
});
define('webuploader',[
'preset/withoutimage'
], function( preset ) {
return preset;
});
return require('webuploader');
});
================================================
FILE: dist/webuploader.nolog.js
================================================
/*! WebUploader 0.1.8-alpha */
/**
* @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
* @require "jquery"
* @require "zepto"
*/
define('dollar-third',[],function() {
var req = window.require;
var $ = window.__dollar ||
window.jQuery ||
window.Zepto ||
req('jquery') ||
req('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.8-alpha',
/**
* @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 错误信息
*/
define('lib/dnd',[
'base',
'mediator',
'runtime/client'
], function( Base, Mediator, RuntimeClent ) {
var $ = Base.$;
function DragAndDrop( opts ) {
opts = this.options = $.extend({}, DragAndDrop.options, opts );
opts.container = $( opts.container );
if ( !opts.container.length ) {
return;
}
RuntimeClent.call( this, 'DragAndDrop' );
}
DragAndDrop.options = {
accept: null,
disableGlobalDnd: false
};
Base.inherits( RuntimeClent, {
constructor: DragAndDrop,
init: function() {
var me = this;
me.connectRuntime( me.options, function() {
me.exec('init');
me.trigger('ready');
});
}
});
Mediator.installTo( DragAndDrop.prototype );
return DragAndDrop;
});
/**
* @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 DragAndDrop Widget。
*/
define('widgets/filednd',[
'base',
'uploader',
'lib/dnd',
'widgets/widget'
], function( Base, Uploader, Dnd ) {
var $ = Base.$;
Uploader.options.dnd = '';
/**
* @property {Selector} [dnd=undefined] 指定Drag And Drop拖拽的容器,如果不指定,则不启动。
* @namespace options
* @for Uploader
*/
/**
* @property {Selector} [disableGlobalDnd=false] 是否禁掉整个页面的拖拽功能,如果不禁用,图片拖进来的时候会默认被浏览器打开。
* @namespace options
* @for Uploader
*/
/**
* @event dndAccept
* @param {DataTransferItemList} items DataTransferItem
* @description 阻止此事件可以拒绝某些类型的文件拖入进来。目前只有 chrome 提供这样的 API,且只能通过 mime-type 验证。
* @for Uploader
*/
return Uploader.register({
name: 'dnd',
init: function( opts ) {
if ( !opts.dnd ||
this.request('predict-runtime-type') !== 'html5' ) {
return;
}
var me = this,
deferred = Base.Deferred(),
options = $.extend({}, {
disableGlobalDnd: opts.disableGlobalDnd,
container: opts.dnd,
accept: opts.accept
}),
dnd;
this.dnd = dnd = new Dnd( options );
dnd.once( 'ready', deferred.resolve );
dnd.on( 'drop', function( files ) {
me.request( 'add-file', [ files ]);
});
// 检测文件是否全部允许添加。
dnd.on( 'accept', function( items ) {
return me.owner.trigger( 'dndAccept', items );
});
dnd.init();
return deferred.promise();
},
destroy: function() {
this.dnd && this.dnd.destroy();
}
});
});
/**
* @fileOverview 错误信息
*/
define('lib/filepaste',[
'base',
'mediator',
'runtime/client'
], function( Base, Mediator, RuntimeClent ) {
var $ = Base.$;
function FilePaste( opts ) {
opts = this.options = $.extend({}, opts );
opts.container = $( opts.container || document.body );
RuntimeClent.call( this, 'FilePaste' );
}
Base.inherits( RuntimeClent, {
constructor: FilePaste,
init: function() {
var me = this;
me.connectRuntime( me.options, function() {
me.exec('init');
me.trigger('ready');
});
}
});
Mediator.installTo( FilePaste.prototype );
return FilePaste;
});
/**
* @fileOverview 组件基类。
*/
define('widgets/filepaste',[
'base',
'uploader',
'lib/filepaste',
'widgets/widget'
], function( Base, Uploader, FilePaste ) {
var $ = Base.$;
/**
* @property {Selector} [paste=undefined] 指定监听paste事件的容器,如果不指定,不启用此功能。此功能为通过粘贴来添加截屏的图片。建议设置为`document.body`.
* @namespace options
* @for Uploader
*/
return Uploader.register({
name: 'paste',
init: function( opts ) {
if ( !opts.paste ||
this.request('predict-runtime-type') !== 'html5' ) {
return;
}
var me = this,
deferred = Base.Deferred(),
options = $.extend({}, {
container: opts.paste,
accept: opts.accept
}),
paste;
this.paste = paste = new FilePaste( options );
paste.once( 'ready', deferred.resolve );
paste.on( 'paste', function( files ) {
me.owner.request( 'add-file', [ files ]);
});
paste.init();
return deferred.promise();
},
destroy: function() {
this.paste && this.paste.destroy();
}
});
});
/**
* @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 ||
file.lastModified && new Date(file.lastModified).toLocaleString() ||
(new Date()).toLocaleString();
Blob.apply( this, arguments );
}
return Base.inherits( Blob, File );
});
/**
* @fileOverview 错误信息
*/
define('lib/filepicker',[
'base',
'runtime/client',
'lib/file'
], function( Base, RuntimeClient, 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 );
RuntimeClient.call( this, 'FilePicker', true );
}
FilePicker.options = {
button: null,
container: null,
label: null,
innerHTML: null,
multiple: true,
accept: null,
name: 'file',
style: 'webuploader-pick' //pick element class attribute, default is "webuploader-pick"
};
Base.inherits( RuntimeClient, {
constructor: FilePicker,
init: function() {
var me = this,
opts = me.options,
button = opts.button,
style = opts.style;
if (style)
button.addClass('webuploader-pick');
me.on( 'all', function( type ) {
var files;
switch ( type ) {
case 'mouseenter':
if (style)
button.addClass('webuploader-pick-hover');
break;
case 'mouseleave':
if (style)
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(),
*/
width = button[0] && button[0].offsetWidth || button.outerWidth() || button.width(),
height = button[0] && button[0].offsetHeight || 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/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 {Array} [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.on('dialogopen', function() {
me.owner.trigger('dialogOpen', picker.button);
});
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.getAsDataUrl( opts.type ) );
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` 被移除的文件数。
* * `numOfInterrupt` 被中断的文件数。
* @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 ];
this._delFile(file);
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 );
});
}
},
_delFile : function(file){
for(var i = this._queue.length - 1 ; i >= 0 ; i-- ){
if(this._queue[i] == file){
this._queue.splice(i,1);
break;
}
}
},
_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 );
});
if ( files.length ) {
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();
},
getResponseHeaders: function() {
return this.exec('getResponseHeaders');
},
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 {Number} [chunkRetryDelay=1000]
* @namespace options
* @for Uploader
* @description 开启重试后,设置重试延时时间, 单位毫秒。默认1000毫秒,即1秒.
*/
chunkRetryDelay: 1000,
/**
* @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) {
file.setStatus( Status.QUEUED );
$.each( me.pool, function( _, v ) {
// 之前暂停过。
if (v.file !== file) {
return;
}
v.transport && v.transport.send();
file.setStatus( Status.PROGRESS );
});
} else if (file.getStatus() !== Status.PROGRESS) {
file.setStatus( Status.QUEUED );
}
} else {
$.each( me.request( 'get-files', [ Status.INITED ] ), function() {
this.setStatus( Status.QUEUED );
});
}
if ( me.runing ) {
me.owner.trigger('startUpload', file);// 开始上传或暂停恢复的,trigger event
return Base.nextTick( me.__tick );
}
me.runing = true;
var files = [];
// 如果有暂停的,则续传
file || $.each( me.pool, function( _, v ) {
var file = v.file;
if ( file.getStatus() === Status.INTERRUPT ) {
me._trigged = false;
files.push(file);
if (v.waiting) {
return;
}
// 文件 prepare 完后,如果暂停了,这个时候只会把文件插入 pool, 而不会创建 tranport,
v.transport ? v.transport.send() : me._doSend(v);
}
});
$.each(files, function() {
this.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) {
v.transport && v.transport.abort();
if (interrupt) {
me._putback(v);
me._popBlock(v);
}
}
});
me.owner.trigger('stopUpload', file);// 暂停,trigger event
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 );
},
/**
* 判断`Uploader`是否正在上传中。
* @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.remaning++;
block.file.remaning++;
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, 每个分片发送之前可能要做些异步的事情。
block.waiting = promise = me.request( 'before-send', block, function() {
delete block.waiting;
// 有可能文件已经上传出错了,所以不需要再传输了。
if ( file.getStatus() === Status.PROGRESS ) {
me._doSend( block );
} else if (block.file.getStatus() !== Status.INTERRUPT) {
me._popBlock(block);
}
Base.nextTick(me.__tick);
});
// 如果为fail了,则跳过此分片。
promise.fail(function() {
delete block.waiting;
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 = $.extend({}, me.options, block.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();
ret._headers = tr.getResponseHeaders();
block.response = ret;
fn = function( value ) {
reject = value;
};
// 服务端响应了,不代表成功了,询问是否响应正确。
if ( !owner.trigger( 'uploadAccept', block, ret, fn ) ) {
reject = reject || 'server';
}
return reject;
};
// 尝试重试,然后广播文件上传出错。
tr.on( 'error', function( type, flag ) {
// 在 runtime/html5/transport.js 上为 type 加上了状态码,形式:type|status|text(如:http-403-Forbidden)
// 这里把状态码解释出来,并还原后面代码所依赖的 type 变量
var typeArr = type.split( '|' ), status, statusText;
type = typeArr[0];
status = parseFloat( typeArr[1] ),
statusText = typeArr[2];
block.retried = block.retried || 0;
// 自动重试
if ( block.chunks > 1 && ~'http,abort,server'.indexOf( type.replace( /-.*/, '' ) ) &&
block.retried < opts.chunkRetry ) {
block.retried++;
me.retryTimer = setTimeout(function() {
tr.send();
}, opts.chunkRetryDelay || 1000);
} else {
// http status 500 ~ 600
if ( !flag && type === 'server' ) {
type = requestAccept( type );
}
file.setStatus( Status.ERROR, type );
owner.trigger( 'uploadError', file, type, status, statusText );
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 );
},
destroy: function() {
clearTimeout(this.retryTimer);
}
});
});
/**
* @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 ) {
// 增加beforeFileQueuedCheckfileNumLimit验证,主要为了再次加载时(已存在历史文件)验证数量是否超过设置项
if (!this.trigger('beforeFileQueuedCheckfileNumLimit', file,count)) {
return false;
}
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 Md5
*/
define('lib/md5',[
'runtime/client',
'mediator'
], function( RuntimeClient, Mediator ) {
function Md5() {
RuntimeClient.call( this, 'Md5' );
}
// 让 Md5 具备事件功能。
Mediator.installTo( Md5.prototype );
Md5.prototype.loadFromBlob = function( blob ) {
var me = this;
if ( me.getRuid() ) {
me.disconnectRuntime();
}
// 连接到blob归属的同一个runtime.
me.connectRuntime( blob.ruid, function() {
me.exec('init');
me.exec( 'loadFromBlob', blob );
});
};
Md5.prototype.getResult = function() {
return this.exec('getResult');
};
return Md5;
});
/**
* @fileOverview 图片操作, 负责预览图片和上传前压缩图片
*/
define('widgets/md5',[
'base',
'uploader',
'lib/md5',
'lib/blob',
'widgets/widget'
], function( Base, Uploader, Md5, Blob ) {
return Uploader.register({
name: 'md5',
/**
* 计算文件 md5 值,返回一个 promise 对象,可以监听 progress 进度。
*
*
* @method md5File
* @grammar md5File( file[, start[, end]] ) => promise
* @for Uploader
* @example
*
* uploader.on( 'fileQueued', function( file ) {
* var $li = ...;
*
* uploader.md5File( file )
*
* // 及时显示进度
* .progress(function(percentage) {
* console.log('Percentage:', percentage);
* })
*
* // 完成
* .then(function(val) {
* console.log('md5 result:', val);
* });
*
* });
*/
md5File: function( file, start, end ) {
var md5 = new Md5(),
deferred = Base.Deferred(),
blob = (file instanceof Blob) ? file :
this.request( 'get-file', file ).source;
md5.on( 'progress load', function( e ) {
e = e || {};
deferred.notify( e.total ? e.loaded / e.total : 1 );
});
md5.on( 'complete', function() {
deferred.resolve( md5.getResult() );
});
md5.on( 'error', function( reason ) {
deferred.reject( reason );
});
if ( arguments.length > 1 ) {
start = start || 0;
end = end || 0;
start < 0 && (start = blob.size + start);
end < 0 && (end = blob.size + end);
end = Math.min( end, blob.size );
blob = blob.slice( start, end );
}
md5.loadFromBlob( blob );
return deferred.promise();
}
});
});
/**
* @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 Html5Runtime
*/
define('runtime/html5/runtime',[
'base',
'runtime/runtime',
'runtime/compbase'
], function( Base, Runtime, CompBase ) {
var type = 'html5',
components = {};
function Html5Runtime() {
var pool = {},
me = this,
destroy = this.destroy;
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;
if ( components[ comp ] ) {
instance = pool[ uid ] = pool[ uid ] ||
new components[ comp ]( client, me );
if ( instance[ fn ] ) {
return instance[ fn ].apply( instance, args );
}
}
};
me.destroy = function() {
// @todo 删除池子中的所有实例
return destroy && destroy.apply( this, arguments );
};
}
Base.inherits( Runtime, {
constructor: Html5Runtime,
// 不需要连接其他程序,直接执行callback
init: function() {
var me = this;
setTimeout(function() {
me.trigger('ready');
}, 1 );
}
});
// 注册Components
Html5Runtime.register = function( name, component ) {
var klass = components[ name ] = Base.inherits( CompBase, component );
return klass;
};
// 注册html5运行时。
// 只有在支持的前提下注册。
if ( window.Blob && window.FileReader && window.DataView ) {
Runtime.addRuntime( type, Html5Runtime );
}
return Html5Runtime;
});
/**
* @fileOverview Blob Html实现
*/
define('runtime/html5/blob',[
'runtime/html5/runtime',
'lib/blob'
], function( Html5Runtime, Blob ) {
return Html5Runtime.register( 'Blob', {
slice: function( start, end ) {
var blob = this.owner.source,
slice = blob.slice || blob.webkitSlice || blob.mozSlice;
blob = slice.call( blob, start, end );
return new Blob( this.getRuid(), blob );
}
});
});
/**
* @fileOverview FilePaste
*/
define('runtime/html5/dnd',[
'base',
'runtime/html5/runtime',
'lib/file'
], function( Base, Html5Runtime, File ) {
var $ = Base.$,
prefix = 'webuploader-dnd-';
return Html5Runtime.register( 'DragAndDrop', {
init: function() {
var elem = this.elem = this.options.container;
this.dragEnterHandler = Base.bindFn( this._dragEnterHandler, this );
this.dragOverHandler = Base.bindFn( this._dragOverHandler, this );
this.dragLeaveHandler = Base.bindFn( this._dragLeaveHandler, this );
this.dropHandler = Base.bindFn( this._dropHandler, this );
this.dndOver = false;
elem.on( 'dragenter', this.dragEnterHandler );
elem.on( 'dragover', this.dragOverHandler );
elem.on( 'dragleave', this.dragLeaveHandler );
elem.on( 'drop', this.dropHandler );
if ( this.options.disableGlobalDnd ) {
$( document ).on( 'dragover', this.dragOverHandler );
$( document ).on( 'drop', this.dropHandler );
}
},
_dragEnterHandler: function( e ) {
var me = this,
denied = me._denied || false,
items;
e = e.originalEvent || e;
if ( !me.dndOver ) {
me.dndOver = true;
// 注意只有 chrome 支持。
items = e.dataTransfer.items;
if ( items && items.length ) {
me._denied = denied = !me.trigger( 'accept', items );
}
me.elem.addClass( prefix + 'over' );
me.elem[ denied ? 'addClass' :
'removeClass' ]( prefix + 'denied' );
}
e.dataTransfer.dropEffect = denied ? 'none' : 'copy';
return false;
},
_dragOverHandler: function( e ) {
// 只处理框内的。
var parentElem = this.elem.parent().get( 0 );
if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) {
return false;
}
clearTimeout( this._leaveTimer );
this._dragEnterHandler.call( this, e );
return false;
},
_dragLeaveHandler: function() {
var me = this,
handler;
handler = function() {
me.dndOver = false;
me.elem.removeClass( prefix + 'over ' + prefix + 'denied' );
};
clearTimeout( me._leaveTimer );
me._leaveTimer = setTimeout( handler, 100 );
return false;
},
_dropHandler: function( e ) {
var me = this,
ruid = me.getRuid(),
parentElem = me.elem.parent().get( 0 ),
dataTransfer, data;
// 只处理框内的。
if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) {
return false;
}
e = e.originalEvent || e;
dataTransfer = e.dataTransfer;
// 如果是页面内拖拽,还不能处理,不阻止事件。
// 此处 ie11 下会报参数错误,
try {
data = dataTransfer.getData('text/html');
} catch( err ) {
}
me.dndOver = false;
me.elem.removeClass( prefix + 'over' );
if ( !dataTransfer || data ) {
return;
}
me._getTansferFiles( dataTransfer, function( results ) {
me.trigger( 'drop', $.map( results, function( file ) {
return new File( ruid, file );
}) );
});
return false;
},
// 如果传入 callback 则去查看文件夹,否则只管当前文件夹。
_getTansferFiles: function( dataTransfer, callback ) {
var results = [],
promises = [],
items, files, file, item, i, len, canAccessFolder;
items = dataTransfer.items;
files = dataTransfer.files;
canAccessFolder = !!(items && items[ 0 ].webkitGetAsEntry);
for ( i = 0, len = files.length; i < len; i++ ) {
file = files[ i ];
item = items && items[ i ];
if ( canAccessFolder && item.webkitGetAsEntry().isDirectory ) {
promises.push( this._traverseDirectoryTree(
item.webkitGetAsEntry(), results ) );
} else {
results.push( file );
}
}
Base.when.apply( Base, promises ).done(function() {
if ( !results.length ) {
return;
}
callback( results );
});
},
_traverseDirectoryTree: function( entry, results ) {
var deferred = Base.Deferred(),
me = this;
if ( entry.isFile ) {
entry.file(function( file ) {
results.push( file );
deferred.resolve();
});
} else if ( entry.isDirectory ) {
entry.createReader().readEntries(function( entries ) {
var len = entries.length,
promises = [],
arr = [], // 为了保证顺序。
i;
for ( i = 0; i < len; i++ ) {
promises.push( me._traverseDirectoryTree(
entries[ i ], arr ) );
}
Base.when.apply( Base, promises ).then(function() {
results.push.apply( results, arr );
deferred.resolve();
}, deferred.reject );
});
}
return deferred.promise();
},
destroy: function() {
var elem = this.elem;
// 还没 init 就调用 destroy
if (!elem) {
return;
}
elem.off( 'dragenter', this.dragEnterHandler );
elem.off( 'dragover', this.dragOverHandler );
elem.off( 'dragleave', this.dragLeaveHandler );
elem.off( 'drop', this.dropHandler );
if ( this.options.disableGlobalDnd ) {
$( document ).off( 'dragover', this.dragOverHandler );
$( document ).off( 'drop', this.dropHandler );
}
}
});
});
/**
* @fileOverview FilePaste
*/
define('runtime/html5/filepaste',[
'base',
'runtime/html5/runtime',
'lib/file'
], function( Base, Html5Runtime, File ) {
return Html5Runtime.register( 'FilePaste', {
init: function() {
var opts = this.options,
elem = this.elem = opts.container,
accept = '.*',
arr, i, len, item;
// accetp的mimeTypes中生成匹配正则。
if ( opts.accept ) {
arr = [];
for ( i = 0, len = opts.accept.length; i < len; i++ ) {
item = opts.accept[ i ].mimeTypes;
item && arr.push( item );
}
if ( arr.length ) {
accept = arr.join(',');
accept = accept.replace( /,/g, '|' ).replace( /\*/g, '.*' );
}
}
this.accept = accept = new RegExp( accept, 'i' );
this.hander = Base.bindFn( this._pasteHander, this );
elem.on( 'paste', this.hander );
},
_pasteHander: function( e ) {
var allowed = [],
ruid = this.getRuid(),
items, item, blob, i, len;
e = e.originalEvent || e;
items = e.clipboardData.items;
for ( i = 0, len = items.length; i < len; i++ ) {
item = items[ i ];
if ( item.kind !== 'file' || !(blob = item.getAsFile()) ) {
continue;
}
allowed.push( new File( ruid, blob ) );
}
if ( allowed.length ) {
// 不阻止非文件粘贴(文字粘贴)的事件冒泡
e.preventDefault();
e.stopPropagation();
this.trigger( 'paste', allowed );
}
},
destroy: function() {
this.elem.off( 'paste', this.hander );
}
});
});
/**
* @fileOverview FilePicker
*/
define('runtime/html5/filepicker',[
'base',
'runtime/html5/runtime'
], function( Base, Html5Runtime ) {
var $ = Base.$;
return Html5Runtime.register( 'FilePicker', {
init: function() {
var container = this.getRuntime().getContainer(),
me = this,
owner = me.owner,
opts = me.options,
label = this.label = $( document.createElement('label') ),
input = this.input = $( document.createElement('input') ),
arr, i, len, mouseHandler, changeHandler;
input.attr( 'type', 'file' );
input.attr( 'capture', 'camera');
input.attr( 'name', opts.name );
input.addClass('webuploader-element-invisible');
label.on( 'click', function(e) {
input.trigger('click');
e.stopPropagation();
owner.trigger('dialogopen');
});
label.css({
opacity: 0,
width: '100%',
height: '100%',
display: 'block',
cursor: 'pointer',
background: '#ffffff'
});
if ( opts.multiple ) {
input.attr( 'multiple', 'multiple' );
}
// @todo Firefox不支持单独指定后缀
if ( opts.accept && opts.accept.length > 0 ) {
arr = [];
for ( i = 0, len = opts.accept.length; i < len; i++ ) {
arr.push( opts.accept[ i ].mimeTypes );
}
input.attr( 'accept', arr.join(',') );
}
container.append( input );
container.append( label );
mouseHandler = function( e ) {
owner.trigger( e.type );
};
changeHandler = function( e ) {
var clone;
// 解决chrome 56 第二次打开文件选择器,然后点击取消,依然会触发change事件的问题
if (e.target.files.length === 0){
return false;
}
// 第一次上传图片后,第二次再点击弹出文件选择器窗,等待
me.files = e.target.files;
// reset input
clone = this.cloneNode( true );
clone.value = null;
this.parentNode.replaceChild( clone, this );
input.off();
input = $( clone ).on( 'change', changeHandler )
.on( 'mouseenter mouseleave', mouseHandler );
owner.trigger('change');
}
input.on( 'change', changeHandler);
label.on( 'mouseenter mouseleave', mouseHandler );
},
getFiles: function() {
return this.files;
},
destroy: function() {
this.input.off();
this.label.off();
}
});
});
/**
* Terms:
*
* Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
* @fileOverview Image控件
*/
define('runtime/html5/util',[
'base'
], function( Base ) {
var urlAPI = window.createObjectURL && window ||
window.URL && URL.revokeObjectURL && URL ||
window.webkitURL,
createObjectURL = Base.noop,
revokeObjectURL = createObjectURL;
if ( urlAPI ) {
// 更安全的方式调用,比如android里面就能把context改成其他的对象。
createObjectURL = function() {
return urlAPI.createObjectURL.apply( urlAPI, arguments );
};
revokeObjectURL = function() {
return urlAPI.revokeObjectURL.apply( urlAPI, arguments );
};
}
return {
createObjectURL: createObjectURL,
revokeObjectURL: revokeObjectURL,
dataURL2Blob: function( dataURI ) {
var byteStr, intArray, ab, i, mimetype, parts;
parts = dataURI.split(',');
if ( ~parts[ 0 ].indexOf('base64') ) {
byteStr = atob( parts[ 1 ] );
} else {
byteStr = decodeURIComponent( parts[ 1 ] );
}
ab = new ArrayBuffer( byteStr.length );
intArray = new Uint8Array( ab );
for ( i = 0; i < byteStr.length; i++ ) {
intArray[ i ] = byteStr.charCodeAt( i );
}
mimetype = parts[ 0 ].split(':')[ 1 ].split(';')[ 0 ];
return this.arrayBufferToBlob( ab, mimetype );
},
dataURL2ArrayBuffer: function( dataURI ) {
var byteStr, intArray, i, parts;
parts = dataURI.split(',');
if ( ~parts[ 0 ].indexOf('base64') ) {
byteStr = atob( parts[ 1 ] );
} else {
byteStr = decodeURIComponent( parts[ 1 ] );
}
intArray = new Uint8Array( byteStr.length );
for ( i = 0; i < byteStr.length; i++ ) {
intArray[ i ] = byteStr.charCodeAt( i );
}
return intArray.buffer;
},
arrayBufferToBlob: function( buffer, type ) {
var builder = window.BlobBuilder || window.WebKitBlobBuilder,
bb;
// android不支持直接new Blob, 只能借助blobbuilder.
if ( builder ) {
bb = new builder();
bb.append( buffer );
return bb.getBlob( type );
}
return new Blob([ buffer ], type ? { type: type } : {} );
},
// 抽出来主要是为了解决android下面canvas.toDataUrl不支持jpeg.
// 你得到的结果是png.
canvasToDataUrl: function( canvas, type, quality ) {
return canvas.toDataURL( type, quality / 100 );
},
// imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
parseMeta: function( blob, callback ) {
callback( false, {});
},
// imagemeat会复写这个方法,如果用户选择加载那个文件了的话。
updateImageHead: function( data ) {
return data;
}
};
});
/**
* Terms:
*
* Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer
* @fileOverview Image控件
*/
define('runtime/html5/imagemeta',[
'runtime/html5/util'
], function( Util ) {
var api;
api = {
parsers: {
0xffe1: []
},
maxMetaDataSize: 262144,
parse: function( blob, cb ) {
var me = this,
fr = new FileReader();
fr.onload = function() {
cb( false, me._parse( this.result ) );
fr = fr.onload = fr.onerror = null;
};
fr.onerror = function( e ) {
cb( e.message );
fr = fr.onload = fr.onerror = null;
};
blob = blob.slice( 0, me.maxMetaDataSize );
fr.readAsArrayBuffer( blob.getSource() );
},
_parse: function( buffer, noParse ) {
if ( buffer.byteLength < 6 ) {
return;
}
var dataview = new DataView( buffer ),
offset = 2,
maxOffset = dataview.byteLength - 4,
headLength = offset,
ret = {},
markerBytes, markerLength, parsers, i;
if ( dataview.getUint16( 0 ) === 0xffd8 ) {
while ( offset < maxOffset ) {
markerBytes = dataview.getUint16( offset );
if ( markerBytes >= 0xffe0 && markerBytes <= 0xffef ||
markerBytes === 0xfffe ) {
markerLength = dataview.getUint16( offset + 2 ) + 2;
if ( offset + markerLength > dataview.byteLength ) {
break;
}
parsers = api.parsers[ markerBytes ];
if ( !noParse && parsers ) {
for ( i = 0; i < parsers.length; i += 1 ) {
parsers[ i ].call( api, dataview, offset,
markerLength, ret );
}
}
offset += markerLength;
headLength = offset;
} else {
break;
}
}
if ( headLength > 6 ) {
if ( buffer.slice ) {
ret.imageHead = buffer.slice( 2, headLength );
} else {
// Workaround for IE10, which does not yet
// support ArrayBuffer.slice:
ret.imageHead = new Uint8Array( buffer )
.subarray( 2, headLength );
}
}
}
return ret;
},
updateImageHead: function( buffer, head ) {
var data = this._parse( buffer, true ),
buf1, buf2, bodyoffset;
bodyoffset = 2;
if ( data.imageHead ) {
bodyoffset = 2 + data.imageHead.byteLength;
}
if ( buffer.slice ) {
buf2 = buffer.slice( bodyoffset );
} else {
buf2 = new Uint8Array( buffer ).subarray( bodyoffset );
}
buf1 = new Uint8Array( head.byteLength + 2 + buf2.byteLength );
buf1[ 0 ] = 0xFF;
buf1[ 1 ] = 0xD8;
buf1.set( new Uint8Array( head ), 2 );
buf1.set( new Uint8Array( buf2 ), head.byteLength + 2 );
return buf1.buffer;
}
};
Util.parseMeta = function() {
return api.parse.apply( api, arguments );
};
Util.updateImageHead = function() {
return api.updateImageHead.apply( api, arguments );
};
return api;
});
/**
* 代码来自于:https://github.com/blueimp/JavaScript-Load-Image
* 暂时项目中只用了orientation.
*
* 去除了 Exif Sub IFD Pointer, GPS Info IFD Pointer, Exif Thumbnail.
* @fileOverview EXIF解析
*/
// Sample
// ====================================
// Make : Apple
// Model : iPhone 4S
// Orientation : 1
// XResolution : 72 [72/1]
// YResolution : 72 [72/1]
// ResolutionUnit : 2
// Software : QuickTime 7.7.1
// DateTime : 2013:09:01 22:53:55
// ExifIFDPointer : 190
// ExposureTime : 0.058823529411764705 [1/17]
// FNumber : 2.4 [12/5]
// ExposureProgram : Normal program
// ISOSpeedRatings : 800
// ExifVersion : 0220
// DateTimeOriginal : 2013:09:01 22:52:51
// DateTimeDigitized : 2013:09:01 22:52:51
// ComponentsConfiguration : YCbCr
// ShutterSpeedValue : 4.058893515764426
// ApertureValue : 2.5260688216892597 [4845/1918]
// BrightnessValue : -0.3126686601998395
// MeteringMode : Pattern
// Flash : Flash did not fire, compulsory flash mode
// FocalLength : 4.28 [107/25]
// SubjectArea : [4 values]
// FlashpixVersion : 0100
// ColorSpace : 1
// PixelXDimension : 2448
// PixelYDimension : 3264
// SensingMethod : One-chip color area sensor
// ExposureMode : 0
// WhiteBalance : Auto white balance
// FocalLengthIn35mmFilm : 35
// SceneCaptureType : Standard
define('runtime/html5/imagemeta/exif',[
'base',
'runtime/html5/imagemeta'
], function( Base, ImageMeta ) {
var EXIF = {};
EXIF.ExifMap = function() {
return this;
};
EXIF.ExifMap.prototype.map = {
'Orientation': 0x0112
};
EXIF.ExifMap.prototype.get = function( id ) {
return this[ id ] || this[ this.map[ id ] ];
};
EXIF.exifTagTypes = {
// byte, 8-bit unsigned int:
1: {
getValue: function( dataView, dataOffset ) {
return dataView.getUint8( dataOffset );
},
size: 1
},
// ascii, 8-bit byte:
2: {
getValue: function( dataView, dataOffset ) {
return String.fromCharCode( dataView.getUint8( dataOffset ) );
},
size: 1,
ascii: true
},
// short, 16 bit int:
3: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getUint16( dataOffset, littleEndian );
},
size: 2
},
// long, 32 bit int:
4: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getUint32( dataOffset, littleEndian );
},
size: 4
},
// rational = two long values,
// first is numerator, second is denominator:
5: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getUint32( dataOffset, littleEndian ) /
dataView.getUint32( dataOffset + 4, littleEndian );
},
size: 8
},
// slong, 32 bit signed int:
9: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getInt32( dataOffset, littleEndian );
},
size: 4
},
// srational, two slongs, first is numerator, second is denominator:
10: {
getValue: function( dataView, dataOffset, littleEndian ) {
return dataView.getInt32( dataOffset, littleEndian ) /
dataView.getInt32( dataOffset + 4, littleEndian );
},
size: 8
}
};
// undefined, 8-bit byte, value depending on field:
EXIF.exifTagTypes[ 7 ] = EXIF.exifTagTypes[ 1 ];
EXIF.getExifValue = function( dataView, tiffOffset, offset, type, length,
littleEndian ) {
var tagType = EXIF.exifTagTypes[ type ],
tagSize, dataOffset, values, i, str, c;
if ( !tagType ) {
Base.log('Invalid Exif data: Invalid tag type.');
return;
}
tagSize = tagType.size * length;
// Determine if the value is contained in the dataOffset bytes,
// or if the value at the dataOffset is a pointer to the actual data:
dataOffset = tagSize > 4 ? tiffOffset + dataView.getUint32( offset + 8,
littleEndian ) : (offset + 8);
if ( dataOffset + tagSize > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid data offset.');
return;
}
if ( length === 1 ) {
return tagType.getValue( dataView, dataOffset, littleEndian );
}
values = [];
for ( i = 0; i < length; i += 1 ) {
values[ i ] = tagType.getValue( dataView,
dataOffset + i * tagType.size, littleEndian );
}
if ( tagType.ascii ) {
str = '';
// Concatenate the chars:
for ( i = 0; i < values.length; i += 1 ) {
c = values[ i ];
// Ignore the terminating NULL byte(s):
if ( c === '\u0000' ) {
break;
}
str += c;
}
return str;
}
return values;
};
EXIF.parseExifTag = function( dataView, tiffOffset, offset, littleEndian,
data ) {
var tag = dataView.getUint16( offset, littleEndian );
data.exif[ tag ] = EXIF.getExifValue( dataView, tiffOffset, offset,
dataView.getUint16( offset + 2, littleEndian ), // tag type
dataView.getUint32( offset + 4, littleEndian ), // tag length
littleEndian );
};
EXIF.parseExifTags = function( dataView, tiffOffset, dirOffset,
littleEndian, data ) {
var tagsNumber, dirEndOffset, i;
if ( dirOffset + 6 > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid directory offset.');
return;
}
tagsNumber = dataView.getUint16( dirOffset, littleEndian );
dirEndOffset = dirOffset + 2 + 12 * tagsNumber;
if ( dirEndOffset + 4 > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid directory size.');
return;
}
for ( i = 0; i < tagsNumber; i += 1 ) {
this.parseExifTag( dataView, tiffOffset,
dirOffset + 2 + 12 * i, // tag offset
littleEndian, data );
}
// Return the offset to the next directory:
return dataView.getUint32( dirEndOffset, littleEndian );
};
// EXIF.getExifThumbnail = function(dataView, offset, length) {
// var hexData,
// i,
// b;
// if (!length || offset + length > dataView.byteLength) {
// Base.log('Invalid Exif data: Invalid thumbnail data.');
// return;
// }
// hexData = [];
// for (i = 0; i < length; i += 1) {
// b = dataView.getUint8(offset + i);
// hexData.push((b < 16 ? '0' : '') + b.toString(16));
// }
// return 'data:image/jpeg,%' + hexData.join('%');
// };
EXIF.parseExifData = function( dataView, offset, length, data ) {
var tiffOffset = offset + 10,
littleEndian, dirOffset;
// Check for the ASCII code for "Exif" (0x45786966):
if ( dataView.getUint32( offset + 4 ) !== 0x45786966 ) {
// No Exif data, might be XMP data instead
return;
}
if ( tiffOffset + 8 > dataView.byteLength ) {
Base.log('Invalid Exif data: Invalid segment size.');
return;
}
// Check for the two null bytes:
if ( dataView.getUint16( offset + 8 ) !== 0x0000 ) {
Base.log('Invalid Exif data: Missing byte alignment offset.');
return;
}
// Check the byte alignment:
switch ( dataView.getUint16( tiffOffset ) ) {
case 0x4949:
littleEndian = true;
break;
case 0x4D4D:
littleEndian = false;
break;
default:
Base.log('Invalid Exif data: Invalid byte alignment marker.');
return;
}
// Check for the TIFF tag marker (0x002A):
if ( dataView.getUint16( tiffOffset + 2, littleEndian ) !== 0x002A ) {
Base.log('Invalid Exif data: Missing TIFF marker.');
return;
}
// Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal:
dirOffset = dataView.getUint32( tiffOffset + 4, littleEndian );
// Create the exif object to store the tags:
data.exif = new EXIF.ExifMap();
// Parse the tags of the main image directory and retrieve the
// offset to the next directory, usually the thumbnail directory:
dirOffset = EXIF.parseExifTags( dataView, tiffOffset,
tiffOffset + dirOffset, littleEndian, data );
// 尝试读取缩略图
// if ( dirOffset ) {
// thumbnailData = {exif: {}};
// dirOffset = EXIF.parseExifTags(
// dataView,
// tiffOffset,
// tiffOffset + dirOffset,
// littleEndian,
// thumbnailData
// );
// // Check for JPEG Thumbnail offset:
// if (thumbnailData.exif[0x0201]) {
// data.exif.Thumbnail = EXIF.getExifThumbnail(
// dataView,
// tiffOffset + thumbnailData.exif[0x0201],
// thumbnailData.exif[0x0202] // Thumbnail data length
// );
// }
// }
};
ImageMeta.parsers[ 0xffe1 ].push( EXIF.parseExifData );
return EXIF;
});
/**
* 这个方式性能不行,但是可以解决android里面的toDataUrl的bug
* android里面toDataUrl('image/jpege')得到的结果却是png.
*
* 所以这里没辙,只能借助这个工具
* @fileOverview jpeg encoder
*/
define('runtime/html5/jpegencoder',[], function( require, exports, module ) {
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009
Basic GUI blocking jpeg encoder
*/
function JPEGEncoder(quality) {
var self = this;
var fround = Math.round;
var ffloor = Math.floor;
var YTable = new Array(64);
var UVTable = new Array(64);
var fdtbl_Y = new Array(64);
var fdtbl_UV = new Array(64);
var YDC_HT;
var UVDC_HT;
var YAC_HT;
var UVAC_HT;
var bitcode = new Array(65535);
var category = new Array(65535);
var outputfDCTQuant = new Array(64);
var DU = new Array(64);
var byteout = [];
var bytenew = 0;
var bytepos = 7;
var YDU = new Array(64);
var UDU = new Array(64);
var VDU = new Array(64);
var clt = new Array(256);
var RGB_YUV_TABLE = new Array(2048);
var currentQuality;
var ZigZag = [
0, 1, 5, 6,14,15,27,28,
2, 4, 7,13,16,26,29,42,
3, 8,12,17,25,30,41,43,
9,11,18,24,31,40,44,53,
10,19,23,32,39,45,52,54,
20,22,33,38,46,51,55,60,
21,34,37,47,50,56,59,61,
35,36,48,49,57,58,62,63
];
var std_dc_luminance_nrcodes = [0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0];
var std_dc_luminance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
var std_ac_luminance_nrcodes = [0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d];
var std_ac_luminance_values = [
0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,
0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,
0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,
0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,
0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,
0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,
0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,
0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,
0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,
0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,
0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,
0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,
0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,
0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,
0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,
0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,
0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,
0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,
0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
0xf9,0xfa
];
var std_dc_chrominance_nrcodes = [0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0];
var std_dc_chrominance_values = [0,1,2,3,4,5,6,7,8,9,10,11];
var std_ac_chrominance_nrcodes = [0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77];
var std_ac_chrominance_values = [
0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,
0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,
0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,
0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,
0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,
0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,
0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,
0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,
0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,
0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,
0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,
0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,
0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,
0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,
0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,
0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,
0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,
0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,
0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
0xf9,0xfa
];
function initQuantTables(sf){
var YQT = [
16, 11, 10, 16, 24, 40, 51, 61,
12, 12, 14, 19, 26, 58, 60, 55,
14, 13, 16, 24, 40, 57, 69, 56,
14, 17, 22, 29, 51, 87, 80, 62,
18, 22, 37, 56, 68,109,103, 77,
24, 35, 55, 64, 81,104,113, 92,
49, 64, 78, 87,103,121,120,101,
72, 92, 95, 98,112,100,103, 99
];
for (var i = 0; i < 64; i++) {
var t = ffloor((YQT[i]*sf+50)/100);
if (t < 1) {
t = 1;
} else if (t > 255) {
t = 255;
}
YTable[ZigZag[i]] = t;
}
var UVQT = [
17, 18, 24, 47, 99, 99, 99, 99,
18, 21, 26, 66, 99, 99, 99, 99,
24, 26, 56, 99, 99, 99, 99, 99,
47, 66, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99
];
for (var j = 0; j < 64; j++) {
var u = ffloor((UVQT[j]*sf+50)/100);
if (u < 1) {
u = 1;
} else if (u > 255) {
u = 255;
}
UVTable[ZigZag[j]] = u;
}
var aasf = [
1.0, 1.387039845, 1.306562965, 1.175875602,
1.0, 0.785694958, 0.541196100, 0.275899379
];
var k = 0;
for (var row = 0; row < 8; row++)
{
for (var col = 0; col < 8; col++)
{
fdtbl_Y[k] = (1.0 / (YTable [ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
fdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
k++;
}
}
}
function computeHuffmanTbl(nrcodes, std_table){
var codevalue = 0;
var pos_in_table = 0;
var HT = new Array();
for (var k = 1; k <= 16; k++) {
for (var j = 1; j <= nrcodes[k]; j++) {
HT[std_table[pos_in_table]] = [];
HT[std_table[pos_in_table]][0] = codevalue;
HT[std_table[pos_in_table]][1] = k;
pos_in_table++;
codevalue++;
}
codevalue*=2;
}
return HT;
}
function initHuffmanTbl()
{
YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values);
UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values);
YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values);
UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values);
}
function initCategoryNumber()
{
var nrlower = 1;
var nrupper = 2;
for (var cat = 1; cat <= 15; cat++) {
//Positive numbers
for (var nr = nrlower; nr>0] = 38470 * i;
RGB_YUV_TABLE[(i+ 512)>>0] = 7471 * i + 0x8000;
RGB_YUV_TABLE[(i+ 768)>>0] = -11059 * i;
RGB_YUV_TABLE[(i+1024)>>0] = -21709 * i;
RGB_YUV_TABLE[(i+1280)>>0] = 32768 * i + 0x807FFF;
RGB_YUV_TABLE[(i+1536)>>0] = -27439 * i;
RGB_YUV_TABLE[(i+1792)>>0] = - 5329 * i;
}
}
// IO functions
function writeBits(bs)
{
var value = bs[0];
var posval = bs[1]-1;
while ( posval >= 0 ) {
if (value & (1 << posval) ) {
bytenew |= (1 << bytepos);
}
posval--;
bytepos--;
if (bytepos < 0) {
if (bytenew == 0xFF) {
writeByte(0xFF);
writeByte(0);
}
else {
writeByte(bytenew);
}
bytepos=7;
bytenew=0;
}
}
}
function writeByte(value)
{
byteout.push(clt[value]); // write char directly instead of converting later
}
function writeWord(value)
{
writeByte((value>>8)&0xFF);
writeByte((value )&0xFF);
}
// DCT & quantization core
function fDCTQuant(data, fdtbl)
{
var d0, d1, d2, d3, d4, d5, d6, d7;
/* Pass 1: process rows. */
var dataOff=0;
var i;
var I8 = 8;
var I64 = 64;
for (i=0; i 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0);
//outputfDCTQuant[i] = fround(fDCTQuant);
}
return outputfDCTQuant;
}
function writeAPP0()
{
writeWord(0xFFE0); // marker
writeWord(16); // length
writeByte(0x4A); // J
writeByte(0x46); // F
writeByte(0x49); // I
writeByte(0x46); // F
writeByte(0); // = "JFIF",'\0'
writeByte(1); // versionhi
writeByte(1); // versionlo
writeByte(0); // xyunits
writeWord(1); // xdensity
writeWord(1); // ydensity
writeByte(0); // thumbnwidth
writeByte(0); // thumbnheight
}
function writeSOF0(width, height)
{
writeWord(0xFFC0); // marker
writeWord(17); // length, truecolor YUV JPG
writeByte(8); // precision
writeWord(height);
writeWord(width);
writeByte(3); // nrofcomponents
writeByte(1); // IdY
writeByte(0x11); // HVY
writeByte(0); // QTY
writeByte(2); // IdU
writeByte(0x11); // HVU
writeByte(1); // QTU
writeByte(3); // IdV
writeByte(0x11); // HVV
writeByte(1); // QTV
}
function writeDQT()
{
writeWord(0xFFDB); // marker
writeWord(132); // length
writeByte(0);
for (var i=0; i<64; i++) {
writeByte(YTable[i]);
}
writeByte(1);
for (var j=0; j<64; j++) {
writeByte(UVTable[j]);
}
}
function writeDHT()
{
writeWord(0xFFC4); // marker
writeWord(0x01A2); // length
writeByte(0); // HTYDCinfo
for (var i=0; i<16; i++) {
writeByte(std_dc_luminance_nrcodes[i+1]);
}
for (var j=0; j<=11; j++) {
writeByte(std_dc_luminance_values[j]);
}
writeByte(0x10); // HTYACinfo
for (var k=0; k<16; k++) {
writeByte(std_ac_luminance_nrcodes[k+1]);
}
for (var l=0; l<=161; l++) {
writeByte(std_ac_luminance_values[l]);
}
writeByte(1); // HTUDCinfo
for (var m=0; m<16; m++) {
writeByte(std_dc_chrominance_nrcodes[m+1]);
}
for (var n=0; n<=11; n++) {
writeByte(std_dc_chrominance_values[n]);
}
writeByte(0x11); // HTUACinfo
for (var o=0; o<16; o++) {
writeByte(std_ac_chrominance_nrcodes[o+1]);
}
for (var p=0; p<=161; p++) {
writeByte(std_ac_chrominance_values[p]);
}
}
function writeSOS()
{
writeWord(0xFFDA); // marker
writeWord(12); // length
writeByte(3); // nrofcomponents
writeByte(1); // IdY
writeByte(0); // HTY
writeByte(2); // IdU
writeByte(0x11); // HTU
writeByte(3); // IdV
writeByte(0x11); // HTV
writeByte(0); // Ss
writeByte(0x3f); // Se
writeByte(0); // Bf
}
function processDU(CDU, fdtbl, DC, HTDC, HTAC){
var EOB = HTAC[0x00];
var M16zeroes = HTAC[0xF0];
var pos;
var I16 = 16;
var I63 = 63;
var I64 = 64;
var DU_DCT = fDCTQuant(CDU, fdtbl);
//ZigZag reorder
for (var j=0;j0)&&(DU[end0pos]==0); end0pos--) {};
//end0pos = first element in reverse order !=0
if ( end0pos == 0) {
writeBits(EOB);
return DC;
}
var i = 1;
var lng;
while ( i <= end0pos ) {
var startpos = i;
for (; (DU[i]==0) && (i<=end0pos); ++i) {}
var nrzeroes = i-startpos;
if ( nrzeroes >= I16 ) {
lng = nrzeroes>>4;
for (var nrmarker=1; nrmarker <= lng; ++nrmarker)
writeBits(M16zeroes);
nrzeroes = nrzeroes&0xF;
}
pos = 32767+DU[i];
writeBits(HTAC[(nrzeroes<<4)+category[pos]]);
writeBits(bitcode[pos]);
i++;
}
if ( end0pos != I63 ) {
writeBits(EOB);
}
return DC;
}
function initCharLookupTable(){
var sfcc = String.fromCharCode;
for(var i=0; i < 256; i++){ ///// ACHTUNG // 255
clt[i] = sfcc(i);
}
}
this.encode = function(image,quality) // image data object
{
// var time_start = new Date().getTime();
if(quality) setQuality(quality);
// Initialize bit writer
byteout = new Array();
bytenew=0;
bytepos=7;
// Add JPEG headers
writeWord(0xFFD8); // SOI
writeAPP0();
writeDQT();
writeSOF0(image.width,image.height);
writeDHT();
writeSOS();
// Encode 8x8 macroblocks
var DCY=0;
var DCU=0;
var DCV=0;
bytenew=0;
bytepos=7;
this.encode.displayName = "_encode_";
var imageData = image.data;
var width = image.width;
var height = image.height;
var quadWidth = width*4;
var tripleWidth = width*3;
var x, y = 0;
var r, g, b;
var start,p, col,row,pos;
while(y < height){
x = 0;
while(x < quadWidth){
start = quadWidth * y + x;
p = start;
col = -1;
row = 0;
for(pos=0; pos < 64; pos++){
row = pos >> 3;// /8
col = ( pos & 7 ) * 4; // %8
p = start + ( row * quadWidth ) + col;
if(y+row >= height){ // padding bottom
p-= (quadWidth*(y+1+row-height));
}
if(x+col >= quadWidth){ // padding right
p-= ((x+col) - quadWidth +4)
}
r = imageData[ p++ ];
g = imageData[ p++ ];
b = imageData[ p++ ];
/* // calculate YUV values dynamically
YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80
UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));
VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));
*/
// use lookup table (slightly faster)
YDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256)>>0] + RGB_YUV_TABLE[(b + 512)>>0]) >> 16)-128;
UDU[pos] = ((RGB_YUV_TABLE[(r + 768)>>0] + RGB_YUV_TABLE[(g + 1024)>>0] + RGB_YUV_TABLE[(b + 1280)>>0]) >> 16)-128;
VDU[pos] = ((RGB_YUV_TABLE[(r + 1280)>>0] + RGB_YUV_TABLE[(g + 1536)>>0] + RGB_YUV_TABLE[(b + 1792)>>0]) >> 16)-128;
}
DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
x+=32;
}
y+=8;
}
////////////////////////////////////////////////////////////////
// Do the bit alignment of the EOI marker
if ( bytepos >= 0 ) {
var fillbits = [];
fillbits[1] = bytepos+1;
fillbits[0] = (1<<(bytepos+1))-1;
writeBits(fillbits);
}
writeWord(0xFFD9); //EOI
var jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join(''));
byteout = [];
// benchmarking
// var duration = new Date().getTime() - time_start;
// console.log('Encoding time: '+ currentQuality + 'ms');
//
return jpegDataUri
}
function setQuality(quality){
if (quality <= 0) {
quality = 1;
}
if (quality > 100) {
quality = 100;
}
if(currentQuality == quality) return // don't recalc if unchanged
var sf = 0;
if (quality < 50) {
sf = Math.floor(5000 / quality);
} else {
sf = Math.floor(200 - quality*2);
}
initQuantTables(sf);
currentQuality = quality;
// console.log('Quality set to: '+quality +'%');
}
function init(){
// var time_start = new Date().getTime();
if(!quality) quality = 50;
// Create tables
initCharLookupTable()
initHuffmanTbl();
initCategoryNumber();
initRGBYUVTable();
setQuality(quality);
// var duration = new Date().getTime() - time_start;
// console.log('Initialization '+ duration + 'ms');
}
init();
};
JPEGEncoder.encode = function( data, quality ) {
var encoder = new JPEGEncoder( quality );
return encoder.encode( data );
}
return JPEGEncoder;
});
/**
* @fileOverview Fix android canvas.toDataUrl bug.
*/
define('runtime/html5/androidpatch',[
'runtime/html5/util',
'runtime/html5/jpegencoder',
'base'
], function( Util, encoder, Base ) {
var origin = Util.canvasToDataUrl,
supportJpeg;
Util.canvasToDataUrl = function( canvas, type, quality ) {
var ctx, w, h, fragement, parts;
// 非android手机直接跳过。
if ( !Base.os.android ) {
return origin.apply( null, arguments );
}
// 检测是否canvas支持jpeg导出,根据数据格式来判断。
// JPEG 前两位分别是:255, 216
if ( type === 'image/jpeg' && typeof supportJpeg === 'undefined' ) {
fragement = origin.apply( null, arguments );
parts = fragement.split(',');
if ( ~parts[ 0 ].indexOf('base64') ) {
fragement = atob( parts[ 1 ] );
} else {
fragement = decodeURIComponent( parts[ 1 ] );
}
fragement = fragement.substring( 0, 2 );
supportJpeg = fragement.charCodeAt( 0 ) === 255 &&
fragement.charCodeAt( 1 ) === 216;
}
// 只有在android环境下才修复
if ( type === 'image/jpeg' && !supportJpeg ) {
w = canvas.width;
h = canvas.height;
ctx = canvas.getContext('2d');
return encoder.encode( ctx.getImageData( 0, 0, w, h ), quality );
}
return origin.apply( null, arguments );
};
});
/**
* @fileOverview Image
*/
define('runtime/html5/image',[
'base',
'runtime/html5/runtime',
'runtime/html5/util'
], function( Base, Html5Runtime, Util ) {
var BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D';
return Html5Runtime.register( 'Image', {
// flag: 标记是否被修改过。
modified: false,
init: function() {
var me = this,
img = new Image();
img.onload = function() {
me._info = {
type: me.type,
width: this.width,
height: this.height
};
//debugger;
// 读取meta信息。
if ( !me._metas && 'image/jpeg' === me.type ) {
Util.parseMeta( me._blob, function( error, ret ) {
me._metas = ret;
me.owner.trigger('load');
});
} else {
me.owner.trigger('load');
}
};
img.onerror = function() {
me.owner.trigger('error');
};
me._img = img;
},
loadFromBlob: function( blob ) {
var me = this,
img = me._img;
me._blob = blob;
me.type = blob.type;
img.src = Util.createObjectURL( blob.getSource() );
me.owner.once( 'load', function() {
Util.revokeObjectURL( img.src );
});
},
resize: function( width, height ) {
var canvas = this._canvas ||
(this._canvas = document.createElement('canvas'));
this._resize( this._img, canvas, width, height );
this._blob = null; // 没用了,可以删掉了。
this.modified = true;
this.owner.trigger( 'complete', 'resize' );
},
crop: function( x, y, w, h, s ) {
var cvs = this._canvas ||
(this._canvas = document.createElement('canvas')),
opts = this.options,
img = this._img,
iw = img.naturalWidth,
ih = img.naturalHeight,
orientation = this.getOrientation();
s = s || 1;
// todo 解决 orientation 的问题。
// values that require 90 degree rotation
// if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) {
// switch ( orientation ) {
// case 6:
// tmp = x;
// x = y;
// y = iw * s - tmp - w;
// console.log(ih * s, tmp, w)
// break;
// }
// (w ^= h, h ^= w, w ^= h);
// }
cvs.width = w;
cvs.height = h;
opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation );
this._renderImageToCanvas( cvs, img, -x, -y, iw * s, ih * s );
this._blob = null; // 没用了,可以删掉了。
this.modified = true;
this.owner.trigger( 'complete', 'crop' );
},
getAsBlob: function( type ) {
var blob = this._blob,
opts = this.options,
canvas;
type = type || this.type;
// blob需要重新生成。
if ( this.modified || this.type !== type ) {
canvas = this._canvas;
if ( type === 'image/jpeg' ) {
blob = Util.canvasToDataUrl( canvas, type, opts.quality );
if ( opts.preserveHeaders && this._metas &&
this._metas.imageHead ) {
blob = Util.dataURL2ArrayBuffer( blob );
blob = Util.updateImageHead( blob,
this._metas.imageHead );
blob = Util.arrayBufferToBlob( blob, type );
return blob;
}
} else {
blob = Util.canvasToDataUrl( canvas, type );
}
blob = Util.dataURL2Blob( blob );
}
return blob;
},
getAsDataUrl: function( type ) {
var opts = this.options;
type = type || this.type;
if ( type === 'image/jpeg' ) {
return Util.canvasToDataUrl( this._canvas, type, opts.quality );
} else {
return this._canvas.toDataURL( type );
}
},
getOrientation: function() {
return this._metas && this._metas.exif &&
this._metas.exif.get('Orientation') || 1;
},
info: function( val ) {
// setter
if ( val ) {
this._info = val;
return this;
}
// getter
return this._info;
},
meta: function( val ) {
// setter
if ( val ) {
this._metas = val;
return this;
}
// getter
return this._metas;
},
destroy: function() {
var canvas = this._canvas;
this._img.onload = null;
if ( canvas ) {
canvas.getContext('2d')
.clearRect( 0, 0, canvas.width, canvas.height );
canvas.width = canvas.height = 0;
this._canvas = null;
}
// 释放内存。非常重要,否则释放不了image的内存。
this._img.src = BLANK;
this._img = this._blob = null;
},
_resize: function( img, cvs, width, height ) {
var opts = this.options,
naturalWidth = img.width,
naturalHeight = img.height,
orientation = this.getOrientation(),
scale, w, h, x, y;
// values that require 90 degree rotation
if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) {
// 交换width, height的值。
width ^= height;
height ^= width;
width ^= height;
}
scale = Math[ opts.crop ? 'max' : 'min' ]( width / naturalWidth,
height / naturalHeight );
// 不允许放大。
opts.allowMagnify || (scale = Math.min( 1, scale ));
w = naturalWidth * scale;
h = naturalHeight * scale;
if ( opts.crop ) {
cvs.width = width;
cvs.height = height;
} else {
cvs.width = w;
cvs.height = h;
}
x = (cvs.width - w) / 2;
y = (cvs.height - h) / 2;
opts.preserveHeaders || this._rotate2Orientaion( cvs, orientation );
this._renderImageToCanvas( cvs, img, x, y, w, h );
},
_rotate2Orientaion: function( canvas, orientation ) {
var width = canvas.width,
height = canvas.height,
ctx = canvas.getContext('2d');
switch ( orientation ) {
case 5:
case 6:
case 7:
case 8:
canvas.width = height;
canvas.height = width;
break;
}
switch ( orientation ) {
case 2: // horizontal flip
ctx.translate( width, 0 );
ctx.scale( -1, 1 );
break;
case 3: // 180 rotate left
ctx.translate( width, height );
ctx.rotate( Math.PI );
break;
case 4: // vertical flip
ctx.translate( 0, height );
ctx.scale( 1, -1 );
break;
case 5: // vertical flip + 90 rotate right
ctx.rotate( 0.5 * Math.PI );
ctx.scale( 1, -1 );
break;
case 6: // 90 rotate right
ctx.rotate( 0.5 * Math.PI );
ctx.translate( 0, -height );
break;
case 7: // horizontal flip + 90 rotate right
ctx.rotate( 0.5 * Math.PI );
ctx.translate( width, -height );
ctx.scale( -1, 1 );
break;
case 8: // 90 rotate left
ctx.rotate( -0.5 * Math.PI );
ctx.translate( -width, 0 );
break;
}
},
// https://github.com/stomita/ios-imagefile-megapixel/
// blob/master/src/megapix-image.js
_renderImageToCanvas: (function() {
// 如果不是ios, 不需要这么复杂!
if ( !Base.os.ios ) {
return function( canvas ) {
var args = Base.slice( arguments, 1 ),
ctx = canvas.getContext('2d');
ctx.drawImage.apply( ctx, args );
};
}
/**
* Detecting vertical squash in loaded image.
* Fixes a bug which squash image vertically while drawing into
* canvas for some images.
*/
function detectVerticalSquash( img, iw, ih ) {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
sy = 0,
ey = ih,
py = ih,
data, alpha, ratio;
canvas.width = 1;
canvas.height = ih;
ctx.drawImage( img, 0, 0 );
data = ctx.getImageData( 0, 0, 1, ih ).data;
// search image edge pixel position in case
// it is squashed vertically.
while ( py > sy ) {
alpha = data[ (py - 1) * 4 + 3 ];
if ( alpha === 0 ) {
ey = py;
} else {
sy = py;
}
py = (ey + sy) >> 1;
}
ratio = (py / ih);
return (ratio === 0) ? 1 : ratio;
}
// fix ie7 bug
// http://stackoverflow.com/questions/11929099/
// html5-canvas-drawimage-ratio-bug-ios
if ( Base.os.ios >= 7 ) {
return function( canvas, img, x, y, w, h ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
vertSquashRatio = detectVerticalSquash( img, iw, ih );
return canvas.getContext('2d').drawImage( img, 0, 0,
iw * vertSquashRatio, ih * vertSquashRatio,
x, y, w, h );
};
}
/**
* Detect subsampling in loaded image.
* In iOS, larger images than 2M pixels may be
* subsampled in rendering.
*/
function detectSubsampling( img ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
canvas, ctx;
// subsampling may happen overmegapixel image
if ( iw * ih > 1024 * 1024 ) {
canvas = document.createElement('canvas');
canvas.width = canvas.height = 1;
ctx = canvas.getContext('2d');
ctx.drawImage( img, -iw + 1, 0 );
// subsampled image becomes half smaller in rendering size.
// check alpha channel value to confirm image is covering
// edge pixel or not. if alpha value is 0
// image is not covering, hence subsampled.
return ctx.getImageData( 0, 0, 1, 1 ).data[ 3 ] === 0;
} else {
return false;
}
}
return function( canvas, img, x, y, width, height ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
ctx = canvas.getContext('2d'),
subsampled = detectSubsampling( img ),
doSquash = this.type === 'image/jpeg',
d = 1024,
sy = 0,
dy = 0,
tmpCanvas, tmpCtx, vertSquashRatio, dw, dh, sx, dx;
if ( subsampled ) {
iw /= 2;
ih /= 2;
}
ctx.save();
tmpCanvas = document.createElement('canvas');
tmpCanvas.width = tmpCanvas.height = d;
tmpCtx = tmpCanvas.getContext('2d');
vertSquashRatio = doSquash ?
detectVerticalSquash( img, iw, ih ) : 1;
dw = Math.ceil( d * width / iw );
dh = Math.ceil( d * height / ih / vertSquashRatio );
while ( sy < ih ) {
sx = 0;
dx = 0;
while ( sx < iw ) {
tmpCtx.clearRect( 0, 0, d, d );
tmpCtx.drawImage( img, -sx, -sy );
ctx.drawImage( tmpCanvas, 0, 0, d, d,
x + dx, y + dy, dw, dh );
sx += d;
dx += dw;
}
sy += d;
dy += dh;
}
ctx.restore();
tmpCanvas = tmpCtx = null;
};
})()
});
});
/**
* @fileOverview Transport
* @todo 支持chunked传输,优势:
* 可以将大文件分成小块,挨个传输,可以提高大文件成功率,当失败的时候,也只需要重传那小部分,
* 而不需要重头再传一次。另外断点续传也需要用chunked方式。
*/
define('runtime/html5/transport',[
'base',
'runtime/html5/runtime'
], function( Base, Html5Runtime ) {
var noop = Base.noop,
$ = Base.$;
return Html5Runtime.register( 'Transport', {
init: function() {
this._status = 0;
this._response = null;
},
send: function() {
var owner = this.owner,
opts = this.options,
xhr = this._initAjax(),
blob = owner._blob,
server = opts.server,
formData, binary, fr;
if ( opts.sendAsBinary ) {
server += opts.attachInfoToQuery !== false ? ((/\?/.test( server ) ? '&' : '?') +
$.param( owner._formData )) : '';
binary = blob.getSource();
} else {
formData = new FormData();
$.each( owner._formData, function( k, v ) {
formData.append( k, v );
});
formData.append( opts.fileVal, blob.getSource(),
opts.filename || owner._formData.name || '' );
}
if ( opts.withCredentials && 'withCredentials' in xhr ) {
xhr.open( opts.method, server, true );
xhr.withCredentials = true;
} else {
xhr.open( opts.method, server );
}
this._setRequestHeader( xhr, opts.headers );
if ( binary ) {
// 强制设置成 content-type 为文件流。
xhr.overrideMimeType &&
xhr.overrideMimeType('application/octet-stream');
// android直接发送blob会导致服务端接收到的是空文件。
// bug详情。
// https://code.google.com/p/android/issues/detail?id=39882
// 所以先用fileReader读取出来再通过arraybuffer的方式发送。
if ( Base.os.android ) {
fr = new FileReader();
fr.onload = function() {
xhr.send( this.result );
fr = fr.onload = null;
};
fr.readAsArrayBuffer( binary );
} else {
xhr.send( binary );
}
} else {
xhr.send( formData );
}
},
getResponse: function() {
return this._response;
},
getResponseAsJson: function() {
return this._parseJson( this._response );
},
getResponseHeaders: function() {
return this._headers;
},
getStatus: function() {
return this._status;
},
abort: function() {
var xhr = this._xhr;
if ( xhr ) {
xhr.upload.onprogress = noop;
xhr.onreadystatechange = noop;
xhr.abort();
this._xhr = xhr = null;
}
},
destroy: function() {
this.abort();
},
_parseHeader: function(raw) {
var ret = {};
raw && raw.replace(/^([^\:]+):(.*)$/mg, function(_, key, value) {
ret[key.trim()] = value.trim();
});
return ret;
},
_initAjax: function() {
var me = this,
xhr = new XMLHttpRequest(),
opts = this.options;
if ( opts.withCredentials && !('withCredentials' in xhr) &&
typeof XDomainRequest !== 'undefined' ) {
xhr = new XDomainRequest();
}
xhr.upload.onprogress = function( e ) {
var percentage = 0;
if ( e.lengthComputable ) {
percentage = e.loaded / e.total;
}
return me.trigger( 'progress', percentage );
};
xhr.onreadystatechange = function() {
if ( xhr.readyState !== 4 ) {
return;
}
xhr.upload.onprogress = noop;
xhr.onreadystatechange = noop;
me._xhr = null;
me._status = xhr.status;
var separator = '|', // 分隔符
// 拼接的状态,在 widgets/upload.js 会有代码用到这个分隔符
status = separator + xhr.status +
separator + xhr.statusText;
if ( xhr.status >= 200 && xhr.status < 300 ) {
me._response = xhr.responseText;
me._headers = me._parseHeader(xhr.getAllResponseHeaders());
return me.trigger('load');
} else if ( xhr.status >= 500 && xhr.status < 600 ) {
me._response = xhr.responseText;
me._headers = me._parseHeader(xhr.getAllResponseHeaders());
return me.trigger( 'error', 'server' + status );
}
return me.trigger( 'error', me._status ? 'http' + status : 'abort' );
};
me._xhr = xhr;
return xhr;
},
_setRequestHeader: function( xhr, headers ) {
$.each( headers, function( key, val ) {
xhr.setRequestHeader( key, val );
});
},
_parseJson: function( str ) {
var json;
try {
json = JSON.parse( str );
} catch ( ex ) {
json = {};
}
return json;
}
});
});
/**
* @fileOverview Transport flash实现
*/
define('runtime/html5/md5',[
'runtime/html5/runtime'
], function( FlashRuntime ) {
/*
* Fastest md5 implementation around (JKM md5)
* Credits: Joseph Myers
*
* @see http://www.myersdaily.org/joseph/javascript/md5-text.html
* @see http://jsperf.com/md5-shootout/7
*/
/* this function is much faster,
so if possible we use it. Some IEs
are the only ones I know of that
need the idiotic second function,
generated by an if clause. */
var add32 = function (a, b) {
return (a + b) & 0xFFFFFFFF;
},
cmn = function (q, a, b, x, s, t) {
a = add32(add32(a, q), add32(x, t));
return add32((a << s) | (a >>> (32 - s)), b);
},
ff = function (a, b, c, d, x, s, t) {
return cmn((b & c) | ((~b) & d), a, b, x, s, t);
},
gg = function (a, b, c, d, x, s, t) {
return cmn((b & d) | (c & (~d)), a, b, x, s, t);
},
hh = function (a, b, c, d, x, s, t) {
return cmn(b ^ c ^ d, a, b, x, s, t);
},
ii = function (a, b, c, d, x, s, t) {
return cmn(c ^ (b | (~d)), a, b, x, s, t);
},
md5cycle = function (x, k) {
var a = x[0],
b = x[1],
c = x[2],
d = x[3];
a = ff(a, b, c, d, k[0], 7, -680876936);
d = ff(d, a, b, c, k[1], 12, -389564586);
c = ff(c, d, a, b, k[2], 17, 606105819);
b = ff(b, c, d, a, k[3], 22, -1044525330);
a = ff(a, b, c, d, k[4], 7, -176418897);
d = ff(d, a, b, c, k[5], 12, 1200080426);
c = ff(c, d, a, b, k[6], 17, -1473231341);
b = ff(b, c, d, a, k[7], 22, -45705983);
a = ff(a, b, c, d, k[8], 7, 1770035416);
d = ff(d, a, b, c, k[9], 12, -1958414417);
c = ff(c, d, a, b, k[10], 17, -42063);
b = ff(b, c, d, a, k[11], 22, -1990404162);
a = ff(a, b, c, d, k[12], 7, 1804603682);
d = ff(d, a, b, c, k[13], 12, -40341101);
c = ff(c, d, a, b, k[14], 17, -1502002290);
b = ff(b, c, d, a, k[15], 22, 1236535329);
a = gg(a, b, c, d, k[1], 5, -165796510);
d = gg(d, a, b, c, k[6], 9, -1069501632);
c = gg(c, d, a, b, k[11], 14, 643717713);
b = gg(b, c, d, a, k[0], 20, -373897302);
a = gg(a, b, c, d, k[5], 5, -701558691);
d = gg(d, a, b, c, k[10], 9, 38016083);
c = gg(c, d, a, b, k[15], 14, -660478335);
b = gg(b, c, d, a, k[4], 20, -405537848);
a = gg(a, b, c, d, k[9], 5, 568446438);
d = gg(d, a, b, c, k[14], 9, -1019803690);
c = gg(c, d, a, b, k[3], 14, -187363961);
b = gg(b, c, d, a, k[8], 20, 1163531501);
a = gg(a, b, c, d, k[13], 5, -1444681467);
d = gg(d, a, b, c, k[2], 9, -51403784);
c = gg(c, d, a, b, k[7], 14, 1735328473);
b = gg(b, c, d, a, k[12], 20, -1926607734);
a = hh(a, b, c, d, k[5], 4, -378558);
d = hh(d, a, b, c, k[8], 11, -2022574463);
c = hh(c, d, a, b, k[11], 16, 1839030562);
b = hh(b, c, d, a, k[14], 23, -35309556);
a = hh(a, b, c, d, k[1], 4, -1530992060);
d = hh(d, a, b, c, k[4], 11, 1272893353);
c = hh(c, d, a, b, k[7], 16, -155497632);
b = hh(b, c, d, a, k[10], 23, -1094730640);
a = hh(a, b, c, d, k[13], 4, 681279174);
d = hh(d, a, b, c, k[0], 11, -358537222);
c = hh(c, d, a, b, k[3], 16, -722521979);
b = hh(b, c, d, a, k[6], 23, 76029189);
a = hh(a, b, c, d, k[9], 4, -640364487);
d = hh(d, a, b, c, k[12], 11, -421815835);
c = hh(c, d, a, b, k[15], 16, 530742520);
b = hh(b, c, d, a, k[2], 23, -995338651);
a = ii(a, b, c, d, k[0], 6, -198630844);
d = ii(d, a, b, c, k[7], 10, 1126891415);
c = ii(c, d, a, b, k[14], 15, -1416354905);
b = ii(b, c, d, a, k[5], 21, -57434055);
a = ii(a, b, c, d, k[12], 6, 1700485571);
d = ii(d, a, b, c, k[3], 10, -1894986606);
c = ii(c, d, a, b, k[10], 15, -1051523);
b = ii(b, c, d, a, k[1], 21, -2054922799);
a = ii(a, b, c, d, k[8], 6, 1873313359);
d = ii(d, a, b, c, k[15], 10, -30611744);
c = ii(c, d, a, b, k[6], 15, -1560198380);
b = ii(b, c, d, a, k[13], 21, 1309151649);
a = ii(a, b, c, d, k[4], 6, -145523070);
d = ii(d, a, b, c, k[11], 10, -1120210379);
c = ii(c, d, a, b, k[2], 15, 718787259);
b = ii(b, c, d, a, k[9], 21, -343485551);
x[0] = add32(a, x[0]);
x[1] = add32(b, x[1]);
x[2] = add32(c, x[2]);
x[3] = add32(d, x[3]);
},
/* there needs to be support for Unicode here,
* unless we pretend that we can redefine the MD-5
* algorithm for multi-byte characters (perhaps
* by adding every four 16-bit characters and
* shortening the sum to 32 bits). Otherwise
* I suggest performing MD-5 as if every character
* was two bytes--e.g., 0040 0025 = @%--but then
* how will an ordinary MD-5 sum be matched?
* There is no way to standardize text to something
* like UTF-8 before transformation; speed cost is
* utterly prohibitive. The JavaScript standard
* itself needs to look at this: it should start
* providing access to strings as preformed UTF-8
* 8-bit unsigned value arrays.
*/
md5blk = function (s) {
var md5blks = [],
i; /* Andy King said do it this way. */
for (i = 0; i < 64; i += 4) {
md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
}
return md5blks;
},
md5blk_array = function (a) {
var md5blks = [],
i; /* Andy King said do it this way. */
for (i = 0; i < 64; i += 4) {
md5blks[i >> 2] = a[i] + (a[i + 1] << 8) + (a[i + 2] << 16) + (a[i + 3] << 24);
}
return md5blks;
},
md51 = function (s) {
var n = s.length,
state = [1732584193, -271733879, -1732584194, 271733878],
i,
length,
tail,
tmp,
lo,
hi;
for (i = 64; i <= n; i += 64) {
md5cycle(state, md5blk(s.substring(i - 64, i)));
}
s = s.substring(i - 64);
length = s.length;
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3);
}
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i = 0; i < 16; i += 1) {
tail[i] = 0;
}
}
// Beware that the final length might not fit in 32 bits so we take care of that
tmp = n * 8;
tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
lo = parseInt(tmp[2], 16);
hi = parseInt(tmp[1], 16) || 0;
tail[14] = lo;
tail[15] = hi;
md5cycle(state, tail);
return state;
},
md51_array = function (a) {
var n = a.length,
state = [1732584193, -271733879, -1732584194, 271733878],
i,
length,
tail,
tmp,
lo,
hi;
for (i = 64; i <= n; i += 64) {
md5cycle(state, md5blk_array(a.subarray(i - 64, i)));
}
// Not sure if it is a bug, however IE10 will always produce a sub array of length 1
// containing the last element of the parent array if the sub array specified starts
// beyond the length of the parent array - weird.
// https://connect.microsoft.com/IE/feedback/details/771452/typed-array-subarray-issue
a = (i - 64) < n ? a.subarray(i - 64) : new Uint8Array(0);
length = a.length;
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= a[i] << ((i % 4) << 3);
}
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i = 0; i < 16; i += 1) {
tail[i] = 0;
}
}
// Beware that the final length might not fit in 32 bits so we take care of that
tmp = n * 8;
tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
lo = parseInt(tmp[2], 16);
hi = parseInt(tmp[1], 16) || 0;
tail[14] = lo;
tail[15] = hi;
md5cycle(state, tail);
return state;
},
hex_chr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'],
rhex = function (n) {
var s = '',
j;
for (j = 0; j < 4; j += 1) {
s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F];
}
return s;
},
hex = function (x) {
var i;
for (i = 0; i < x.length; i += 1) {
x[i] = rhex(x[i]);
}
return x.join('');
},
md5 = function (s) {
return hex(md51(s));
},
////////////////////////////////////////////////////////////////////////////
/**
* SparkMD5 OOP implementation.
*
* Use this class to perform an incremental md5, otherwise use the
* static methods instead.
*/
SparkMD5 = function () {
// call reset to init the instance
this.reset();
};
// In some cases the fast add32 function cannot be used..
if (md5('hello') !== '5d41402abc4b2a76b9719d911017c592') {
add32 = function (x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF),
msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
};
}
/**
* Appends a string.
* A conversion will be applied if an utf8 string is detected.
*
* @param {String} str The string to be appended
*
* @return {SparkMD5} The instance itself
*/
SparkMD5.prototype.append = function (str) {
// converts the string to utf8 bytes if necessary
if (/[\u0080-\uFFFF]/.test(str)) {
str = unescape(encodeURIComponent(str));
}
// then append as binary
this.appendBinary(str);
return this;
};
/**
* Appends a binary string.
*
* @param {String} contents The binary string to be appended
*
* @return {SparkMD5} The instance itself
*/
SparkMD5.prototype.appendBinary = function (contents) {
this._buff += contents;
this._length += contents.length;
var length = this._buff.length,
i;
for (i = 64; i <= length; i += 64) {
md5cycle(this._state, md5blk(this._buff.substring(i - 64, i)));
}
this._buff = this._buff.substr(i - 64);
return this;
};
/**
* Finishes the incremental computation, reseting the internal state and
* returning the result.
* Use the raw parameter to obtain the raw result instead of the hex one.
*
* @param {Boolean} raw True to get the raw result, false to get the hex result
*
* @return {String|Array} The result
*/
SparkMD5.prototype.end = function (raw) {
var buff = this._buff,
length = buff.length,
i,
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
ret;
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= buff.charCodeAt(i) << ((i % 4) << 3);
}
this._finish(tail, length);
ret = !!raw ? this._state : hex(this._state);
this.reset();
return ret;
};
/**
* Finish the final calculation based on the tail.
*
* @param {Array} tail The tail (will be modified)
* @param {Number} length The length of the remaining buffer
*/
SparkMD5.prototype._finish = function (tail, length) {
var i = length,
tmp,
lo,
hi;
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(this._state, tail);
for (i = 0; i < 16; i += 1) {
tail[i] = 0;
}
}
// Do the final computation based on the tail and length
// Beware that the final length may not fit in 32 bits so we take care of that
tmp = this._length * 8;
tmp = tmp.toString(16).match(/(.*?)(.{0,8})$/);
lo = parseInt(tmp[2], 16);
hi = parseInt(tmp[1], 16) || 0;
tail[14] = lo;
tail[15] = hi;
md5cycle(this._state, tail);
};
/**
* Resets the internal state of the computation.
*
* @return {SparkMD5} The instance itself
*/
SparkMD5.prototype.reset = function () {
this._buff = "";
this._length = 0;
this._state = [1732584193, -271733879, -1732584194, 271733878];
return this;
};
/**
* Releases memory used by the incremental buffer and other aditional
* resources. If you plan to use the instance again, use reset instead.
*/
SparkMD5.prototype.destroy = function () {
delete this._state;
delete this._buff;
delete this._length;
};
/**
* Performs the md5 hash on a string.
* A conversion will be applied if utf8 string is detected.
*
* @param {String} str The string
* @param {Boolean} raw True to get the raw result, false to get the hex result
*
* @return {String|Array} The result
*/
SparkMD5.hash = function (str, raw) {
// converts the string to utf8 bytes if necessary
if (/[\u0080-\uFFFF]/.test(str)) {
str = unescape(encodeURIComponent(str));
}
var hash = md51(str);
return !!raw ? hash : hex(hash);
};
/**
* Performs the md5 hash on a binary string.
*
* @param {String} content The binary string
* @param {Boolean} raw True to get the raw result, false to get the hex result
*
* @return {String|Array} The result
*/
SparkMD5.hashBinary = function (content, raw) {
var hash = md51(content);
return !!raw ? hash : hex(hash);
};
/**
* SparkMD5 OOP implementation for array buffers.
*
* Use this class to perform an incremental md5 ONLY for array buffers.
*/
SparkMD5.ArrayBuffer = function () {
// call reset to init the instance
this.reset();
};
////////////////////////////////////////////////////////////////////////////
/**
* Appends an array buffer.
*
* @param {ArrayBuffer} arr The array to be appended
*
* @return {SparkMD5.ArrayBuffer} The instance itself
*/
SparkMD5.ArrayBuffer.prototype.append = function (arr) {
// TODO: we could avoid the concatenation here but the algorithm would be more complex
// if you find yourself needing extra performance, please make a PR.
var buff = this._concatArrayBuffer(this._buff, arr),
length = buff.length,
i;
this._length += arr.byteLength;
for (i = 64; i <= length; i += 64) {
md5cycle(this._state, md5blk_array(buff.subarray(i - 64, i)));
}
// Avoids IE10 weirdness (documented above)
this._buff = (i - 64) < length ? buff.subarray(i - 64) : new Uint8Array(0);
return this;
};
/**
* Finishes the incremental computation, reseting the internal state and
* returning the result.
* Use the raw parameter to obtain the raw result instead of the hex one.
*
* @param {Boolean} raw True to get the raw result, false to get the hex result
*
* @return {String|Array} The result
*/
SparkMD5.ArrayBuffer.prototype.end = function (raw) {
var buff = this._buff,
length = buff.length,
tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
i,
ret;
for (i = 0; i < length; i += 1) {
tail[i >> 2] |= buff[i] << ((i % 4) << 3);
}
this._finish(tail, length);
ret = !!raw ? this._state : hex(this._state);
this.reset();
return ret;
};
SparkMD5.ArrayBuffer.prototype._finish = SparkMD5.prototype._finish;
/**
* Resets the internal state of the computation.
*
* @return {SparkMD5.ArrayBuffer} The instance itself
*/
SparkMD5.ArrayBuffer.prototype.reset = function () {
this._buff = new Uint8Array(0);
this._length = 0;
this._state = [1732584193, -271733879, -1732584194, 271733878];
return this;
};
/**
* Releases memory used by the incremental buffer and other aditional
* resources. If you plan to use the instance again, use reset instead.
*/
SparkMD5.ArrayBuffer.prototype.destroy = SparkMD5.prototype.destroy;
/**
* Concats two array buffers, returning a new one.
*
* @param {ArrayBuffer} first The first array buffer
* @param {ArrayBuffer} second The second array buffer
*
* @return {ArrayBuffer} The new array buffer
*/
SparkMD5.ArrayBuffer.prototype._concatArrayBuffer = function (first, second) {
var firstLength = first.length,
result = new Uint8Array(firstLength + second.byteLength);
result.set(first);
result.set(new Uint8Array(second), firstLength);
return result;
};
/**
* Performs the md5 hash on an array buffer.
*
* @param {ArrayBuffer} arr The array buffer
* @param {Boolean} raw True to get the raw result, false to get the hex result
*
* @return {String|Array} The result
*/
SparkMD5.ArrayBuffer.hash = function (arr, raw) {
var hash = md51_array(new Uint8Array(arr));
return !!raw ? hash : hex(hash);
};
return FlashRuntime.register( 'Md5', {
init: function() {
// do nothing.
},
loadFromBlob: function( file ) {
var blob = file.getSource(),
chunkSize = 2 * 1024 * 1024,
chunks = Math.ceil( blob.size / chunkSize ),
chunk = 0,
owner = this.owner,
spark = new SparkMD5.ArrayBuffer(),
me = this,
blobSlice = blob.mozSlice || blob.webkitSlice || blob.slice,
loadNext, fr;
fr = new FileReader();
loadNext = function() {
var start, end;
start = chunk * chunkSize;
end = Math.min( start + chunkSize, blob.size );
fr.onload = function( e ) {
spark.append( e.target.result );
owner.trigger( 'progress', {
total: file.size,
loaded: end
});
};
fr.onloadend = function() {
fr.onloadend = fr.onload = null;
if ( ++chunk < chunks ) {
setTimeout( loadNext, 1 );
} else {
setTimeout(function(){
owner.trigger('load');
me.result = spark.end();
loadNext = file = blob = spark = null;
owner.trigger('complete');
}, 50 );
}
};
fr.readAsArrayBuffer( blobSlice.call( blob, start, end ) );
};
loadNext();
},
getResult: function() {
return this.result;
}
});
});
/**
* @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 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;
},
getResponseHeaders: function() {
// flash 暂不支持
return {};
},
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-'+status;
} else {
err = 'http-'+status;
}
if ( readBody ) {
me._response = xhr.exec('getResponse');
me._response = decodeURIComponent( me._response );
// flash 处理可能存在 bug, 没辙只能靠 js 了
// try {
// me._responseJson = xhr.exec('getResponseAsJson');
// } catch ( error ) {
p = function( s ) {
try {
if (window.JSON && window.JSON.parse) {
return JSON.parse(s);
}
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() {
var status = xhr.exec('getStatus'),err = status?'http-'+status:'http';
xhr.off();
me._xhr = null;
me.trigger( 'error', err );
});
me._xhr = xhr;
return xhr;
},
_setRequestHeader: function( xhr, headers ) {
$.each( headers, function( key, val ) {
xhr.exec( 'setRequestHeader', key, val );
});
}
});
});
/**
* @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( this.getRuid(), blob );
}
});
});
/**
* @fileOverview Md5 flash实现
*/
define('runtime/flash/md5',[
'runtime/flash/runtime'
], function( FlashRuntime ) {
return FlashRuntime.register( 'Md5', {
init: function() {
// do nothing.
},
loadFromBlob: function( blob ) {
return this.flashExec( 'Md5', 'loadFromBlob', blob.uid );
}
});
});
/**
* @fileOverview 完全版本。
*/
define('preset/all',[
'base',
// widgets
'widgets/filednd',
'widgets/filepaste',
'widgets/filepicker',
'widgets/image',
'widgets/queue',
'widgets/runtime',
'widgets/upload',
'widgets/validator',
'widgets/md5',
// runtimes
// html5
'runtime/html5/blob',
'runtime/html5/dnd',
'runtime/html5/filepaste',
'runtime/html5/filepicker',
'runtime/html5/imagemeta/exif',
'runtime/html5/androidpatch',
'runtime/html5/image',
'runtime/html5/transport',
'runtime/html5/md5',
// flash
'runtime/flash/filepicker',
'runtime/flash/image',
'runtime/flash/transport',
'runtime/flash/blob',
'runtime/flash/md5'
], function( Base ) {
return Base;
});
define('webuploader',[
'preset/all'
], function( preset ) {
return preset;
});
return require('webuploader');
});
================================================
FILE: dist/webuploader.withoutimage.js
================================================
/*! 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 错误信息
*/
define('lib/dnd',[
'base',
'mediator',
'runtime/client'
], function( Base, Mediator, RuntimeClent ) {
var $ = Base.$;
function DragAndDrop( opts ) {
opts = this.options = $.extend({}, DragAndDrop.options, opts );
opts.container = $( opts.container );
if ( !opts.container.length ) {
return;
}
RuntimeClent.call( this, 'DragAndDrop' );
}
DragAndDrop.options = {
accept: null,
disableGlobalDnd: false
};
Base.inherits( RuntimeClent, {
constructor: DragAndDrop,
init: function() {
var me = this;
me.connectRuntime( me.options, function() {
me.exec('init');
me.trigger('ready');
});
}
});
Mediator.installTo( DragAndDrop.prototype );
return DragAndDrop;
});
/**
* @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 DragAndDrop Widget。
*/
define('widgets/filednd',[
'base',
'uploader',
'lib/dnd',
'widgets/widget'
], function( Base, Uploader, Dnd ) {
var $ = Base.$;
Uploader.options.dnd = '';
/**
* @property {Selector} [dnd=undefined] 指定Drag And Drop拖拽的容器,如果不指定,则不启动。
* @namespace options
* @for Uploader
*/
/**
* @property {Selector} [disableGlobalDnd=false] 是否禁掉整个页面的拖拽功能,如果不禁用,图片拖进来的时候会默认被浏览器打开。
* @namespace options
* @for Uploader
*/
/**
* @event dndAccept
* @param {DataTransferItemList} items DataTransferItem
* @description 阻止此事件可以拒绝某些类型的文件拖入进来。目前只有 chrome 提供这样的 API,且只能通过 mime-type 验证。
* @for Uploader
*/
return Uploader.register({
name: 'dnd',
init: function( opts ) {
if ( !opts.dnd ||
this.request('predict-runtime-type') !== 'html5' ) {
return;
}
var me = this,
deferred = Base.Deferred(),
options = $.extend({}, {
disableGlobalDnd: opts.disableGlobalDnd,
container: opts.dnd,
accept: opts.accept
}),
dnd;
this.dnd = dnd = new Dnd( options );
dnd.once( 'ready', deferred.resolve );
dnd.on( 'drop', function( files ) {
me.request( 'add-file', [ files ]);
});
// 检测文件是否全部允许添加。
dnd.on( 'accept', function( items ) {
return me.owner.trigger( 'dndAccept', items );
});
dnd.init();
return deferred.promise();
},
destroy: function() {
this.dnd && this.dnd.destroy();
}
});
});
/**
* @fileOverview 错误信息
*/
define('lib/filepaste',[
'base',
'mediator',
'runtime/client'
], function( Base, Mediator, RuntimeClent ) {
var $ = Base.$;
function FilePaste( opts ) {
opts = this.options = $.extend({}, opts );
opts.container = $( opts.container || document.body );
RuntimeClent.call( this, 'FilePaste' );
}
Base.inherits( RuntimeClent, {
constructor: FilePaste,
init: function() {
var me = this;
me.connectRuntime( me.options, function() {
me.exec('init');
me.trigger('ready');
});
}
});
Mediator.installTo( FilePaste.prototype );
return FilePaste;
});
/**
* @fileOverview 组件基类。
*/
define('widgets/filepaste',[
'base',
'uploader',
'lib/filepaste',
'widgets/widget'
], function( Base, Uploader, FilePaste ) {
var $ = Base.$;
/**
* @property {Selector} [paste=undefined] 指定监听paste事件的容器,如果不指定,不启用此功能。此功能为通过粘贴来添加截屏的图片。建议设置为`document.body`.
* @namespace options
* @for Uploader
*/
return Uploader.register({
name: 'paste',
init: function( opts ) {
if ( !opts.paste ||
this.request('predict-runtime-type') !== 'html5' ) {
return;
}
var me = this,
deferred = Base.Deferred(),
options = $.extend({}, {
container: opts.paste,
accept: opts.accept
}),
paste;
this.paste = paste = new FilePaste( options );
paste.once( 'ready', deferred.resolve );
paste.on( 'paste', function( files ) {
me.owner.request( 'add-file', [ files ]);
});
paste.init();
return deferred.promise();
},
destroy: function() {
this.paste && this.paste.destroy();
}
});
});
/**
* @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/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} 指定选择文件的按钮容器,不指定则不创建按钮。
* * `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 文件属性封装
*/
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 );
};
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;
// 如果有暂停的,则续传
$.each( me.pool, function( _, v ) {
var file = v.file;
if ( file.getStatus() === Status.INTERRUPT ) {
file.setStatus( Status.PROGRESS );
me._trigged = false;
v.transport && v.transport.send();
}
});
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._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 ) {
var totalPercent = 0,
uploaded = 0;
// 可能没有abort掉,progress还是执行进来了。
// if ( !file.blocks ) {
// return;
// }
totalPercent = block.percentage = percentage;
if ( block.chunks > 1 ) { // 计算文件的整体速度。
$.each( file.blocks, function( _, v ) {
uploaded += (v.percentage || 0) * (v.end - v.start);
});
totalPercent = uploaded / file.size;
}
owner.trigger( 'uploadProgress', file, totalPercent || 0 );
});
// 用来询问,是否返回的结果是有错误的。
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 );
});
}
});
});
/**
* @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 Html5Runtime
*/
define('runtime/html5/runtime',[
'base',
'runtime/runtime',
'runtime/compbase'
], function( Base, Runtime, CompBase ) {
var type = 'html5',
components = {};
function Html5Runtime() {
var pool = {},
me = this,
destroy = this.destroy;
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;
if ( components[ comp ] ) {
instance = pool[ uid ] = pool[ uid ] ||
new components[ comp ]( client, me );
if ( instance[ fn ] ) {
return instance[ fn ].apply( instance, args );
}
}
};
me.destroy = function() {
// @todo 删除池子中的所有实例
return destroy && destroy.apply( this, arguments );
};
}
Base.inherits( Runtime, {
constructor: Html5Runtime,
// 不需要连接其他程序,直接执行callback
init: function() {
var me = this;
setTimeout(function() {
me.trigger('ready');
}, 1 );
}
});
// 注册Components
Html5Runtime.register = function( name, component ) {
var klass = components[ name ] = Base.inherits( CompBase, component );
return klass;
};
// 注册html5运行时。
// 只有在支持的前提下注册。
if ( window.Blob && window.FileReader && window.DataView ) {
Runtime.addRuntime( type, Html5Runtime );
}
return Html5Runtime;
});
/**
* @fileOverview Blob Html实现
*/
define('runtime/html5/blob',[
'runtime/html5/runtime',
'lib/blob'
], function( Html5Runtime, Blob ) {
return Html5Runtime.register( 'Blob', {
slice: function( start, end ) {
var blob = this.owner.source,
slice = blob.slice || blob.webkitSlice || blob.mozSlice;
blob = slice.call( blob, start, end );
return new Blob( this.getRuid(), blob );
}
});
});
/**
* @fileOverview FilePaste
*/
define('runtime/html5/dnd',[
'base',
'runtime/html5/runtime',
'lib/file'
], function( Base, Html5Runtime, File ) {
var $ = Base.$,
prefix = 'webuploader-dnd-';
return Html5Runtime.register( 'DragAndDrop', {
init: function() {
var elem = this.elem = this.options.container;
this.dragEnterHandler = Base.bindFn( this._dragEnterHandler, this );
this.dragOverHandler = Base.bindFn( this._dragOverHandler, this );
this.dragLeaveHandler = Base.bindFn( this._dragLeaveHandler, this );
this.dropHandler = Base.bindFn( this._dropHandler, this );
this.dndOver = false;
elem.on( 'dragenter', this.dragEnterHandler );
elem.on( 'dragover', this.dragOverHandler );
elem.on( 'dragleave', this.dragLeaveHandler );
elem.on( 'drop', this.dropHandler );
if ( this.options.disableGlobalDnd ) {
$( document ).on( 'dragover', this.dragOverHandler );
$( document ).on( 'drop', this.dropHandler );
}
},
_dragEnterHandler: function( e ) {
var me = this,
denied = me._denied || false,
items;
e = e.originalEvent || e;
if ( !me.dndOver ) {
me.dndOver = true;
// 注意只有 chrome 支持。
items = e.dataTransfer.items;
if ( items && items.length ) {
me._denied = denied = !me.trigger( 'accept', items );
}
me.elem.addClass( prefix + 'over' );
me.elem[ denied ? 'addClass' :
'removeClass' ]( prefix + 'denied' );
}
e.dataTransfer.dropEffect = denied ? 'none' : 'copy';
return false;
},
_dragOverHandler: function( e ) {
// 只处理框内的。
var parentElem = this.elem.parent().get( 0 );
if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) {
return false;
}
clearTimeout( this._leaveTimer );
this._dragEnterHandler.call( this, e );
return false;
},
_dragLeaveHandler: function() {
var me = this,
handler;
handler = function() {
me.dndOver = false;
me.elem.removeClass( prefix + 'over ' + prefix + 'denied' );
};
clearTimeout( me._leaveTimer );
me._leaveTimer = setTimeout( handler, 100 );
return false;
},
_dropHandler: function( e ) {
var me = this,
ruid = me.getRuid(),
parentElem = me.elem.parent().get( 0 ),
dataTransfer, data;
// 只处理框内的。
if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) {
return false;
}
e = e.originalEvent || e;
dataTransfer = e.dataTransfer;
// 如果是页面内拖拽,还不能处理,不阻止事件。
// 此处 ie11 下会报参数错误,
try {
data = dataTransfer.getData('text/html');
} catch( err ) {
}
if ( data ) {
return;
}
me._getTansferFiles( dataTransfer, function( results ) {
me.trigger( 'drop', $.map( results, function( file ) {
return new File( ruid, file );
}) );
});
me.dndOver = false;
me.elem.removeClass( prefix + 'over' );
return false;
},
// 如果传入 callback 则去查看文件夹,否则只管当前文件夹。
_getTansferFiles: function( dataTransfer, callback ) {
var results = [],
promises = [],
items, files, file, item, i, len, canAccessFolder;
items = dataTransfer.items;
files = dataTransfer.files;
canAccessFolder = !!(items && items[ 0 ].webkitGetAsEntry);
for ( i = 0, len = files.length; i < len; i++ ) {
file = files[ i ];
item = items && items[ i ];
if ( canAccessFolder && item.webkitGetAsEntry().isDirectory ) {
promises.push( this._traverseDirectoryTree(
item.webkitGetAsEntry(), results ) );
} else {
results.push( file );
}
}
Base.when.apply( Base, promises ).done(function() {
if ( !results.length ) {
return;
}
callback( results );
});
},
_traverseDirectoryTree: function( entry, results ) {
var deferred = Base.Deferred(),
me = this;
if ( entry.isFile ) {
entry.file(function( file ) {
results.push( file );
deferred.resolve();
});
} else if ( entry.isDirectory ) {
entry.createReader().readEntries(function( entries ) {
var len = entries.length,
promises = [],
arr = [], // 为了保证顺序。
i;
for ( i = 0; i < len; i++ ) {
promises.push( me._traverseDirectoryTree(
entries[ i ], arr ) );
}
Base.when.apply( Base, promises ).then(function() {
results.push.apply( results, arr );
deferred.resolve();
}, deferred.reject );
});
}
return deferred.promise();
},
destroy: function() {
var elem = this.elem;
// 还没 init 就调用 destroy
if (!elem) {
return;
}
elem.off( 'dragenter', this.dragEnterHandler );
elem.off( 'dragover', this.dragOverHandler );
elem.off( 'dragleave', this.dragLeaveHandler );
elem.off( 'drop', this.dropHandler );
if ( this.options.disableGlobalDnd ) {
$( document ).off( 'dragover', this.dragOverHandler );
$( document ).off( 'drop', this.dropHandler );
}
}
});
});
/**
* @fileOverview FilePaste
*/
define('runtime/html5/filepaste',[
'base',
'runtime/html5/runtime',
'lib/file'
], function( Base, Html5Runtime, File ) {
return Html5Runtime.register( 'FilePaste', {
init: function() {
var opts = this.options,
elem = this.elem = opts.container,
accept = '.*',
arr, i, len, item;
// accetp的mimeTypes中生成匹配正则。
if ( opts.accept ) {
arr = [];
for ( i = 0, len = opts.accept.length; i < len; i++ ) {
item = opts.accept[ i ].mimeTypes;
item && arr.push( item );
}
if ( arr.length ) {
accept = arr.join(',');
accept = accept.replace( /,/g, '|' ).replace( /\*/g, '.*' );
}
}
this.accept = accept = new RegExp( accept, 'i' );
this.hander = Base.bindFn( this._pasteHander, this );
elem.on( 'paste', this.hander );
},
_pasteHander: function( e ) {
var allowed = [],
ruid = this.getRuid(),
items, item, blob, i, len;
e = e.originalEvent || e;
items = e.clipboardData.items;
for ( i = 0, len = items.length; i < len; i++ ) {
item = items[ i ];
if ( item.kind !== 'file' || !(blob = item.getAsFile()) ) {
continue;
}
allowed.push( new File( ruid, blob ) );
}
if ( allowed.length ) {
// 不阻止非文件粘贴(文字粘贴)的事件冒泡
e.preventDefault();
e.stopPropagation();
this.trigger( 'paste', allowed );
}
},
destroy: function() {
this.elem.off( 'paste', this.hander );
}
});
});
/**
* @fileOverview FilePicker
*/
define('runtime/html5/filepicker',[
'base',
'runtime/html5/runtime'
], function( Base, Html5Runtime ) {
var $ = Base.$;
return Html5Runtime.register( 'FilePicker', {
init: function() {
var container = this.getRuntime().getContainer(),
me = this,
owner = me.owner,
opts = me.options,
label = this.label = $( document.createElement('label') ),
input = this.input = $( document.createElement('input') ),
arr, i, len, mouseHandler;
input.attr( 'type', 'file' );
input.attr( 'name', opts.name );
input.addClass('webuploader-element-invisible');
label.on( 'click', function() {
input.trigger('click');
});
label.css({
opacity: 0,
width: '100%',
height: '100%',
display: 'block',
cursor: 'pointer',
background: '#ffffff'
});
if ( opts.multiple ) {
input.attr( 'multiple', 'multiple' );
}
// @todo Firefox不支持单独指定后缀
if ( opts.accept && opts.accept.length > 0 ) {
arr = [];
for ( i = 0, len = opts.accept.length; i < len; i++ ) {
arr.push( opts.accept[ i ].mimeTypes );
}
input.attr( 'accept', arr.join(',') );
}
container.append( input );
container.append( label );
mouseHandler = function( e ) {
owner.trigger( e.type );
};
input.on( 'change', function( e ) {
var fn = arguments.callee,
clone;
me.files = e.target.files;
// reset input
clone = this.cloneNode( true );
clone.value = null;
this.parentNode.replaceChild( clone, this );
input.off();
input = $( clone ).on( 'change', fn )
.on( 'mouseenter mouseleave', mouseHandler );
owner.trigger('change');
});
label.on( 'mouseenter mouseleave', mouseHandler );
},
getFiles: function() {
return this.files;
},
destroy: function() {
this.input.off();
this.label.off();
}
});
});
/**
* @fileOverview Transport
* @todo 支持chunked传输,优势:
* 可以将大文件分成小块,挨个传输,可以提高大文件成功率,当失败的时候,也只需要重传那小部分,
* 而不需要重头再传一次。另外断点续传也需要用chunked方式。
*/
define('runtime/html5/transport',[
'base',
'runtime/html5/runtime'
], function( Base, Html5Runtime ) {
var noop = Base.noop,
$ = Base.$;
return Html5Runtime.register( 'Transport', {
init: function() {
this._status = 0;
this._response = null;
},
send: function() {
var owner = this.owner,
opts = this.options,
xhr = this._initAjax(),
blob = owner._blob,
server = opts.server,
formData, binary, fr;
if ( opts.sendAsBinary ) {
server += (/\?/.test( server ) ? '&' : '?') +
$.param( owner._formData );
binary = blob.getSource();
} else {
formData = new FormData();
$.each( owner._formData, function( k, v ) {
formData.append( k, v );
});
formData.append( opts.fileVal, blob.getSource(),
opts.filename || owner._formData.name || '' );
}
if ( opts.withCredentials && 'withCredentials' in xhr ) {
xhr.open( opts.method, server, true );
xhr.withCredentials = true;
} else {
xhr.open( opts.method, server );
}
this._setRequestHeader( xhr, opts.headers );
if ( binary ) {
// 强制设置成 content-type 为文件流。
xhr.overrideMimeType &&
xhr.overrideMimeType('application/octet-stream');
// android直接发送blob会导致服务端接收到的是空文件。
// bug详情。
// https://code.google.com/p/android/issues/detail?id=39882
// 所以先用fileReader读取出来再通过arraybuffer的方式发送。
if ( Base.os.android ) {
fr = new FileReader();
fr.onload = function() {
xhr.send( this.result );
fr = fr.onload = null;
};
fr.readAsArrayBuffer( binary );
} else {
xhr.send( binary );
}
} else {
xhr.send( formData );
}
},
getResponse: function() {
return this._response;
},
getResponseAsJson: function() {
return this._parseJson( this._response );
},
getStatus: function() {
return this._status;
},
abort: function() {
var xhr = this._xhr;
if ( xhr ) {
xhr.upload.onprogress = noop;
xhr.onreadystatechange = noop;
xhr.abort();
this._xhr = xhr = null;
}
},
destroy: function() {
this.abort();
},
_initAjax: function() {
var me = this,
xhr = new XMLHttpRequest(),
opts = this.options;
if ( opts.withCredentials && !('withCredentials' in xhr) &&
typeof XDomainRequest !== 'undefined' ) {
xhr = new XDomainRequest();
}
xhr.upload.onprogress = function( e ) {
var percentage = 0;
if ( e.lengthComputable ) {
percentage = e.loaded / e.total;
}
return me.trigger( 'progress', percentage );
};
xhr.onreadystatechange = function() {
if ( xhr.readyState !== 4 ) {
return;
}
xhr.upload.onprogress = noop;
xhr.onreadystatechange = noop;
me._xhr = null;
me._status = xhr.status;
if ( xhr.status >= 200 && xhr.status < 300 ) {
me._response = xhr.responseText;
return me.trigger('load');
} else if ( xhr.status >= 500 && xhr.status < 600 ) {
me._response = xhr.responseText;
return me.trigger( 'error', 'server' );
}
return me.trigger( 'error', me._status ? 'http' : 'abort' );
};
me._xhr = xhr;
return xhr;
},
_setRequestHeader: function( xhr, headers ) {
$.each( headers, function( key, val ) {
xhr.setRequestHeader( key, val );
});
},
_parseJson: function( str ) {
var json;
try {
json = JSON.parse( str );
} catch ( ex ) {
json = {};
}
return json;
}
});
});
/**
* @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 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 没有图像处理的版本。
*/
define('preset/withoutimage',[
'base',
// widgets
'widgets/filednd',
'widgets/filepaste',
'widgets/filepicker',
'widgets/queue',
'widgets/runtime',
'widgets/upload',
'widgets/validator',
// runtimes
// html5
'runtime/html5/blob',
'runtime/html5/dnd',
'runtime/html5/filepaste',
'runtime/html5/filepicker',
'runtime/html5/transport',
// flash
'runtime/flash/filepicker',
'runtime/flash/transport'
], function( Base ) {
return Base;
});
define('webuploader',[
'preset/withoutimage'
], function( preset ) {
return preset;
});
return require('webuploader');
});
================================================
FILE: examples/cropper/cropper.css
================================================
/*!
* Cropper v0.3.2
* https://github.com/fengyuanchen/cropper
*
* Copyright 2014 Fengyuan Chen
* Released under the MIT license
*/
.cropper-container {
position: relative;
overflow: hidden;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
background-color: #fff;
-webkit-tap-highlight-color: transparent;
-webkit-touch-callout: none;
}
.cropper-container .cropper-modal {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: #000;
filter: alpha(opacity=50);
opacity: .5;
}
.cropper-container .cropper-dragger {
position: absolute;
top: 10%;
left: 10%;
width: 80%;
height: 80%;
}
.cropper-container .cropper-preview {
display: block;
width: 100%;
height: 100%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
overflow: hidden;
border-color: #69f;
border-color: rgba(51, 102, 255, .75);
border-style: solid;
border-width: 1px;
}
.cropper-container .cropper-dashed {
position: absolute;
display: block;
filter: alpha(opacity=50);
border: 0 dashed #fff;
opacity: .5;
}
.cropper-container .dashed-h {
top: 33.3%;
left: 0;
width: 100%;
height: 33.3%;
border-top-width: 1px;
border-bottom-width: 1px;
}
.cropper-container .dashed-v {
top: 0;
left: 33.3%;
width: 33.3%;
height: 100%;
border-right-width: 1px;
border-left-width: 1px;
}
.cropper-container .cropper-face,
.cropper-container .cropper-line,
.cropper-container .cropper-point {
position: absolute;
display: block;
width: 100%;
height: 100%;
filter: alpha(opacity=10);
opacity: .1;
}
.cropper-container .cropper-face {
top: 0;
left: 0;
cursor: move;
background-color: #fff;
}
.cropper-container .cropper-line {
background-color: #69f;
}
.cropper-container .line-e {
top: 0;
right: -2px;
width: 5px;
cursor: e-resize;
}
.cropper-container .line-n {
top: -2px;
left: 0;
height: 5px;
cursor: n-resize;
}
.cropper-container .line-w {
top: 0;
left: -2px;
width: 5px;
cursor: w-resize;
}
.cropper-container .line-s {
bottom: -2px;
left: 0;
height: 5px;
cursor: s-resize;
}
.cropper-container .cropper-point {
width: 5px;
height: 5px;
background-color: #69f;
filter: alpha(opacity=75);
opacity: .75;
}
.cropper-container .point-e {
top: 49%;
right: -2px;
cursor: e-resize;
}
.cropper-container .point-n {
top: -2px;
left: 49%;
cursor: n-resize;
}
.cropper-container .point-w {
top: 49%;
left: -2px;
cursor: w-resize;
}
.cropper-container .point-s {
bottom: -2px;
left: 49%;
cursor: s-resize;
}
.cropper-container .point-ne {
top: -2px;
right: -2px;
cursor: ne-resize;
}
.cropper-container .point-nw {
top: -2px;
left: -2px;
cursor: nw-resize;
}
.cropper-container .point-sw {
bottom: -2px;
left: -2px;
cursor: sw-resize;
}
.cropper-container .point-se {
right: -2px;
bottom: -2px;
width: 20px;
height: 20px;
cursor: se-resize;
filter: alpha(opacity=100);
opacity: 1;
}
.cropper-container .point-se:before {
position: absolute;
right: -50%;
bottom: -50%;
display: block;
width: 200%;
height: 200%;
content: " ";
background-color: #69f;
filter: alpha(opacity=0);
opacity: 0;
}
@media (min-width: 768px) {
.cropper-container .point-se {
width: 15px;
height: 15px;
}
}
@media (min-width: 992px) {
.cropper-container .point-se {
width: 10px;
height: 10px;
}
}
@media (min-width: 1200px) {
.cropper-container .point-se {
width: 5px;
height: 5px;
filter: alpha(opacity=75);
opacity: .75;
}
}
.cropper-hidden {
display: none !important;
}
================================================
FILE: examples/cropper/cropper.js
================================================
/*!
* Cropper v0.3.2
* https://github.com/fengyuanchen/cropper
*
* Copyright 2014 Fengyuan Chen
* Released under the MIT license
*/
(function(factory) {
if (typeof define === "function" && define.amd) {
// AMD. Register as anonymous module.
define(["jquery"], factory);
} else {
// Browser globals.
factory(jQuery);
}
}(function($) {
"use strict";
var $window = $(window),
Cropper = function(element, options) {
options = $.isPlainObject(options) ? options : {};
this.$image = $(element);
this.defaults = $.extend({}, Cropper.defaults, this.$image.data(), options);
this.init();
};
Cropper.prototype = {
construstor: Cropper,
init: function() {
this.setAspectRatio(this.defaults.aspectRatio);
this.render();
},
render: function(callback) {
var that = this,
$image = this.$image,
$clone,
src;
if (this.active) {
return;
}
if (this.$clone) {
this.$clone.remove(); // Remove the old clone
}
src = $image.attr("src"); // Don't use "prop"
$clone = $(' ');
$clone.on("load", function() {
var image;
$clone.off("load");
if (this.naturalWidth && this.naturalHeight) {
image = {
naturalHeight: this.naturalHeight,
naturalWidth: this.naturalWidth
};
} else {
Cropper.fn.size($clone, {
height: "auto",
width: "auto"
});
image = Cropper.fn.size($clone);
image = {
naturalHeight: image.height,
naturalWidth: image.width
};
}
Cropper.fn.size($clone, {
height: "100%",
width: "100%"
});
image.aspectRatio = image.naturalWidth / image.naturalHeight;
that.src = src;
that.image = image;
that.active = true;
that.createCropper();
});
if ($.isFunction(callback)) {
$image.on("ready.cropper", callback);
}
this.$clone = $clone;
$image.after($clone);
},
unrender: function() {
if (this.active) {
this.active = false;
this.removeCropper();
this.src = "";
this.image = null;
this.cropper = null;
this.dragger = null;
}
},
rerender: function() {
this.unrender();
this.render();
},
resize: function() {
clearTimeout(this.resizing);
this.resizing = setTimeout($.proxy(this.rerender, this), 200);
},
createCropper: function() {
this.$cropper = $(Cropper.template);
this.$dragger = this.$cropper.find(".cropper-dragger");
Cropper.fn.toggle(this.$image);
this.$image.after(this.$cropper);
this.$cropper.prepend(this.$clone);
if (!this.defaults.modal) {
Cropper.fn.toggle(this.$cropper.find(".cropper-modal"));
}
this.setPreview();
this.addListener();
},
removeCropper: function() {
this.removeListener();
this.$preview = null;
this.$clone.remove();
this.$clone = null;
this.$dragger = null;
this.$cropper.remove();
this.$cropper = null;
Cropper.fn.toggle(this.$image);
},
addListener: function() {
this.$cropper.bind("mousedown touchstart", $.proxy(this.dragstart, this));
this.$cropper.bind("mousemove touchmove", $.proxy(this.dragmove, this));
this.$cropper.bind("mouseup mouseleave touchend touchleave", $.proxy(this.dragend, this));
$window.on("resize", $.proxy(this.resize, this));
},
removeListener: function() {
this.$cropper.unbind("mousedown touchstart", this.dragstart);
this.$cropper.unbind("mousemove touchmove", this.dragmove);
this.$cropper.unbind("mouseup mouseleave touchend touchleave", this.dragend);
$window.off("resize", this.resize);
},
setPreview: function() {
var preview = this.defaults.preview;
this.$preview = this.$cropper.find(".cropper-preview");
if (typeof preview === "string" && preview.length > 0) {
this.$preview = this.$preview.add(preview);
}
this.$preview.html(' ');
this.setCropper();
},
setCropper: function() {
var $container = this.$image.parent(),
container = Cropper.fn.size($container),
image = this.image,
cropper;
if (((image.naturalWidth * container.height / image.naturalHeight) - container.width) >= 0) {
cropper = {
height: container.width / image.aspectRatio,
width: container.width,
left: 0
};
cropper.top = (container.height - cropper.height) / 2;
} else {
cropper = {
height: container.height,
width: container.height * image.aspectRatio,
top: 0
};
cropper.left = (container.width - cropper.width) / 2;
}
$.each(cropper, function(i, n) {
cropper[i] = Math.round(n);
});
image.height = cropper.height;
image.width = cropper.width;
image.ratio = image.width / image.naturalWidth;
Cropper.fn.position($container);
this.$cropper.css({
height: cropper.height,
left: cropper.left,
top: cropper.top,
width: cropper.width
});
this.cropper = cropper;
this.setDragger();
},
setDragger: function() {
var cropper = this.cropper,
// If not set, use the original aspect ratio of the image.
aspectRatio = this.defaults.aspectRatio || this.image.aspectRatio,
dragger;
if (((cropper.height * aspectRatio) - cropper.width) >= 0) {
dragger = {
height: cropper.width / aspectRatio,
width: cropper.width,
left: 0,
top: (cropper.height - (cropper.width / aspectRatio)) / 2,
maxWidth: cropper.width,
maxHeight: cropper.width / aspectRatio
};
} else {
dragger = {
height: cropper.height,
width: cropper.height * aspectRatio,
left: (cropper.width - (cropper.height * aspectRatio)) / 2,
top: 0,
maxHeight: cropper.height,
maxWidth: cropper.height * aspectRatio
};
}
dragger.height *= 0.8;
dragger.width *= 0.8;
dragger.left = (cropper.width - dragger.width) / 2;
dragger.top = (cropper.height - dragger.height) / 2;
this.dragger = Cropper.fn.round(dragger);
this.setData(this.defaults.data);
this.$image.trigger("ready.cropper").off("ready.cropper");
},
resetDragger: function() {
var dragger = this.dragger,
cropper = this.cropper;
dragger.width = dragger.width > dragger.maxWidth ? dragger.maxWidth : Math.abs(dragger.width);
dragger.height = dragger.height > dragger.maxHeight ? dragger.maxHeight : Math.abs(dragger.height);
dragger.maxLeft = cropper.width - dragger.width;
dragger.maxTop = cropper.height - dragger.height;
dragger.left = dragger.left < 0 ? 0 : dragger.left > dragger.maxLeft ? dragger.maxLeft : dragger.left;
dragger.top = dragger.top < 0 ? 0 : dragger.top > dragger.maxTop ? dragger.maxTop : dragger.top;
dragger = Cropper.fn.round(dragger);
this.$dragger.css({
height: dragger.height,
left: dragger.left,
top: dragger.top,
width: dragger.width
});
this.dragger = dragger;
this.preview();
this.output();
},
dragging: function() {
var direction = this.direction,
dragger = this.dragger,
aspectRatio = this.defaults.aspectRatio,
range = {
x: this.endX - this.startX,
y: this.endY - this.startY
};
if (aspectRatio) {
range.X = range.y * aspectRatio;
range.Y = range.x / aspectRatio;
}
switch (direction) {
// dragging
case "e":
dragger.width += range.x;
if (aspectRatio) {
dragger.height = dragger.width / aspectRatio;
dragger.top -= range.Y / 2;
}
if (dragger.width < 0) {
this.direction = "w";
dragger.width = 0;
}
break;
case "n":
dragger.height -= range.y;
dragger.top += range.y;
if (aspectRatio) {
dragger.width = dragger.height * aspectRatio;
dragger.left += range.X / 2;
}
if (dragger.height < 0) {
this.direction = "s";
dragger.height = 0;
}
break;
case "w":
dragger.width -= range.x;
dragger.left += range.x;
if (aspectRatio) {
dragger.height = dragger.width / aspectRatio;
dragger.top += range.Y / 2;
}
if (dragger.width < 0) {
this.direction = "e";
dragger.width = 0;
}
break;
case "s":
dragger.height += range.y;
if (aspectRatio) {
dragger.width = dragger.height * aspectRatio;
dragger.left -= range.X / 2;
}
if (dragger.height < 0) {
this.direction = "n";
dragger.height = 0;
}
break;
case "ne":
dragger.height -= range.y;
dragger.top += range.y;
if (aspectRatio) {
dragger.width = dragger.height * aspectRatio;
} else {
dragger.width += range.x;
}
if (dragger.height < 0) {
this.direction = "sw";
dragger.height = 0;
dragger.width = 0;
}
break;
case "nw":
dragger.height -= range.y;
dragger.top += range.y;
if (aspectRatio) {
dragger.width = dragger.height * aspectRatio;
dragger.left += range.X;
} else {
dragger.width -= range.x;
dragger.left += range.x;
}
if (dragger.height < 0) {
this.direction = "se";
dragger.height = 0;
dragger.width = 0;
}
break;
case "sw":
dragger.width -= range.x;
dragger.left += range.x;
if (aspectRatio) {
dragger.height = dragger.width / aspectRatio;
} else {
dragger.height += range.y;
}
if (dragger.width < 0) {
this.direction = "ne";
dragger.height = 0;
dragger.width = 0;
}
break;
case "se":
dragger.width += range.x;
if (aspectRatio) {
dragger.height = dragger.width / aspectRatio;
} else {
dragger.height += range.y;
}
if (dragger.width < 0) {
this.direction = "nw";
dragger.height = 0;
dragger.width = 0;
}
break;
// moving
default:
dragger.left += range.x;
dragger.top += range.y;
}
this.resetDragger();
this.startX = this.endX;
this.startY = this.endY;
},
output: function() {
this.defaults.done(this.getData());
},
preview: function() {
var that = this,
cropper = that.cropper,
dragger = that.dragger;
this.$preview.each(function() {
var $this = $(this),
ratio = $this.outerWidth() / dragger.width,
styles = {
height: cropper.height,
marginLeft: - dragger.left,
marginTop: - dragger.top,
width: cropper.width
};
$this.css({overflow: "hidden"});
$this.find("img").css(Cropper.fn.round(styles, function(n) {
return n * ratio;
}));
});
},
// Public methods
enable: function(callback) {
this.render(callback);
},
disable: function() {
this.unrender();
},
setAspectRatio: function(aspectRatio) {
if (aspectRatio === "auto" || ($.isNumeric(aspectRatio) && aspectRatio > 0)) {
this.defaults.aspectRatio = aspectRatio === "auto" ? NaN : aspectRatio;
if (this.active) {
this.setDragger();
}
}
},
setData: function(data) {
var cropper = this.cropper,
dragger = this.dragger,
aspectRatio = this.defaults.aspectRatio,
isNumber = function(n) {
return typeof n === "number";
};
if (!this.active) {
return;
}
if ($.isPlainObject(data) && !$.isEmptyObject(data)) {
data = Cropper.fn.transformData(data, this.image.ratio);
if (isNumber(data.x1) && data.x1 <= cropper.width) {
dragger.left = data.x1;
}
if (isNumber(data.y1) && data.y1 <= cropper.height) {
dragger.top = data.y1;
}
if (aspectRatio){
if (isNumber(data.width) && data.width <= cropper.width) {
dragger.width = data.width;
dragger.height = dragger.width / aspectRatio;
} else if (isNumber(data.height) && data.height <= cropper.height) {
dragger.height = data.height;
dragger.width = dragger.height * aspectRatio;
} else if (isNumber(data.x2) && data.x2 <= cropper.width) {
dragger.width = data.x2 - dragger.left;
dragger.height = dragger.width / aspectRatio;
} else if (isNumber(data.y2) && data.y2 <= cropper.height) {
dragger.height = data.y2 - dragger.top;
dragger.width = dragger.height * aspectRatio;
}
} else {
if (isNumber(data.width) && data.width <= cropper.width) {
dragger.width = data.width;
} else if (isNumber(data.x2) && data.x2 <= cropper.width) {
dragger.width = data.x2 - dragger.left;
}
if (isNumber(data.height) && data.height <= cropper.height) {
dragger.height = data.height;
} else if (isNumber(data.y2) && data.height <= cropper.height) {
dragger.height = data.y2 - dragger.top;
}
}
}
this.dragger = dragger;
this.resetDragger();
},
getData: function() {
var dragger = this.dragger,
data = {};
if (this.active) {
data = {
x1: dragger.left,
y1: dragger.top,
width: dragger.width,
height: dragger.height,
x2: dragger.left + dragger.width,
y2: dragger.top + dragger.height
};
data = Cropper.fn.transformData(data, (1 / this.image.ratio));
}
return data;
},
setImgSrc: function(src) {
if (typeof src === "string" && src.length > 0 && src !== this.src) {
this.$image.attr("src", src);
this.rerender();
}
},
getImgInfo: function() {
return this.image || {};
},
// Public events
dragstart: function(event) {
var touches = Cropper.fn.getOriginalEvent(event).touches,
e = event,
touching,
direction;
if (touches && touches.length === 1) {
e = touches[0];
this.touchId = e.identifier;
touching = true;
}
direction = $(e.target).data().direction;
if (Cropper.fn.isDirection(direction)) {
this.startX = e.pageX;
this.startY = e.pageY;
this.direction = direction;
this.$image.trigger("dragstart");
touching && event.preventDefault();
}
},
dragmove: function(event) {
var touches = Cropper.fn.getOriginalEvent(event).changedTouches,
e = event,
touching;
if (touches && touches.length === 1) {
e = touches[0];
touching = true;
if (e.identifier !== this.touchId) {
return;
}
}
if (this.direction) {
this.$image.trigger("dragmove");
touching && event.preventDefault();
this.endX = e.pageX;
this.endY = e.pageY;
this.dragging();
}
},
dragend: function(event) {
var touches = Cropper.fn.getOriginalEvent(event).changedTouches,
e = event,
touching;
if (touches && touches.length === 1) {
e = touches[0];
touching = true;
if (e.identifier !== this.touchId) {
return;
}
}
if (this.direction) {
this.direction = "";
this.$image.trigger("dragend");
touching && event.preventDefault();
}
}
};
// Common methods
Cropper.fn = {
toggle: function($e) {
$e.toggleClass("cropper-hidden");
},
position: function($e, option) {
var position = $e.css("position");
if (position === "static") {
$e.css("position", option || "relative");
}
},
size: function($e, options) {
if ($.isPlainObject(options)) {
$e.css(options);
} else {
return {
height: $e.height(),
width: $e.width()
};
}
},
round: function(data, fn) {
var value,
i;
for (i in data) {
value = data[i];
if (data.hasOwnProperty(i) && typeof value === "number") {
data[i] = Math.round($.isFunction(fn) ? fn(value) : value);
}
}
return data;
},
transformData: function(data, ratio) {
var that = this,
result = {};
$.each(data, function(i, n) {
if (that.isDataOption(i) && $.isNumeric(n) && n >= 0) {
result[i] = Math.round(n * ratio);
}
});
return result;
},
getOriginalEvent: function(event) {
if (event && typeof event.originalEvent !== "undefined") {
event = event.originalEvent;
}
return event;
},
isDataOption: function(s) {
return /^(x1|y1|x2|y2|width|height)$/i.test(s);
},
isDirection: function(s) {
return /^(\*|e|n|w|s|ne|nw|sw|se)$/i.test(s);
}
};
Cropper.template = [
'',
'
',
'
',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
' ',
'
',
'
'
].join("");
Cropper.defaults = {
aspectRatio: "auto",
data: {},
done: function(/* data */) {},
modal: true,
preview: ""
};
Cropper.setDefaults = function(options) {
$.extend(Cropper.defaults, options);
};
// Register as jQuery plugin
$.fn.cropper = function(options, settings) {
var result = this;
this.each(function() {
var $this = $(this),
data = $this.data("cropper");
if (!data) {
data = new Cropper(this, options);
$this.data("cropper", data);
}
if (typeof options === "string" && $.isFunction(data[options])) {
result = data[options](settings);
}
});
return (typeof result !== "undefined" ? result : this);
};
$.fn.cropper.Constructor = Cropper;
$.fn.cropper.setDefaults = Cropper.setDefaults;
$(function() {
$("img[cropper]").cropper();
});
}));
================================================
FILE: examples/cropper/index.html
================================================
WebUploader演示 - 带裁剪功能
================================================
FILE: examples/cropper/jquery.js
================================================
/*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license
*/(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" a ",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="
",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;
return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML=" ";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="
",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="
",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML=" ",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML=" ",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML=" ",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||st.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&>(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/\s*$/g,At={option:[1,""," "],legend:[1,""," "],area:[1,""," "],param:[1,""," "],thead:[1,""],tr:[2,""],col:[2,""],td:[3,""],_default:b.support.htmlSerialize?[0,"",""]:[1,"X","
"]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1>$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1>$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?""!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l)
}b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b("").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write(""),t.close(),n=ln(e,t),Pt.detach()),Gt[e]=n),n}function ln(e,t){var n=b(t.createElement(e)).appendTo(t.body),r=b.css(n[0],"display");return n.remove(),r}b.each(["height","width"],function(e,n){b.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(b.css(e,"display"))?b.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,i),i):0)}}}),b.support.opacity||(b.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=b.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===b.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),b(function(){b.support.reliableMarginRight||(b.cssHooks.marginRight={get:function(e,n){return n?b.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!b.support.pixelPosition&&b.fn.position&&b.each(["top","left"],function(e,n){b.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?b(e).position()[n]+"px":r):t}}})}),b.expr&&b.expr.filters&&(b.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!b.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||b.css(e,"display"))},b.expr.filters.visible=function(e){return!b.expr.filters.hidden(e)}),b.each({margin:"",padding:"",border:"Width"},function(e,t){b.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(b.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;b.fn.extend({serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=b.prop(this,"elements");return e?b.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!b(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Nt.test(e))}).map(function(e,t){var n=b(this).val();return null==n?null:b.isArray(n)?b.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),b.param=function(e,n){var r,i=[],o=function(e,t){t=b.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=b.ajaxSettings&&b.ajaxSettings.traditional),b.isArray(e)||e.jquery&&!b.isPlainObject(e))b.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(b.isArray(t))b.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==b.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}b.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){b.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),b.fn.hover=function(e,t){return this.mouseenter(e).mouseleave(t||e)};var mn,yn,vn=b.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Nn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Cn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=b.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=a.href}catch(Ln){yn=o.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[];if(b.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(u){var l;return o[u]=!0,b.each(e[u]||[],function(e,u){var c=u(n,r,i);return"string"!=typeof c||a||o[c]?a?!(l=c):t:(n.dataTypes.unshift(c),s(c),!1)}),l}return s(n.dataTypes[0])||!o["*"]&&s("*")}function Mn(e,n){var r,i,o=b.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&b.extend(!0,e,r),e}b.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,u=e.indexOf(" ");return u>=0&&(i=e.slice(u,e.length),e=e.slice(0,u)),b.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&b.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?b("").append(b.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},b.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){b.fn[t]=function(e){return this.on(t,e)}}),b.each(["get","post"],function(e,n){b[n]=function(e,r,i,o){return b.isFunction(r)&&(o=o||i,i=r,r=t),b.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),b.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Nn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Mn(Mn(e,b.ajaxSettings),t):Mn(b.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,u,l,c,p=b.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?b(f):b.event,h=b.Deferred(),g=b.Callbacks("once memory"),m=p.statusCode||{},y={},v={},x=0,T="canceled",N={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else N.always(e[N.status]);return this},abort:function(e){var t=e||T;return l&&l.abort(t),k(0,t),this}};if(h.promise(N).complete=g.add,N.success=N.done,N.error=N.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=b.trim(p.dataType||"*").toLowerCase().match(w)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?80:443))==(mn[3]||("http:"===mn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=b.param(p.data,p.traditional)),qn(An,p,n,N),2===x)return N;u=p.global,u&&0===b.active++&&b.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Cn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(b.lastModified[o]&&N.setRequestHeader("If-Modified-Since",b.lastModified[o]),b.etag[o]&&N.setRequestHeader("If-None-Match",b.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&N.setRequestHeader("Content-Type",p.contentType),N.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)N.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,N,p)===!1||2===x))return N.abort();T="abort";for(i in{success:1,error:1,complete:1})N[i](p[i]);if(l=qn(jn,p,n,N)){N.readyState=1,u&&d.trigger("ajaxSend",[N,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){N.abort("timeout")},p.timeout));try{x=1,l.send(y,k)}catch(C){if(!(2>x))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,C=n;2!==x&&(x=2,s&&clearTimeout(s),l=t,a=i||"",N.readyState=e>0?4:0,r&&(w=_n(p,N,r)),e>=200&&300>e||304===e?(p.ifModified&&(T=N.getResponseHeader("Last-Modified"),T&&(b.lastModified[o]=T),T=N.getResponseHeader("etag"),T&&(b.etag[o]=T)),204===e?(c=!0,C="nocontent"):304===e?(c=!0,C="notmodified"):(c=Fn(p,w),C=c.state,y=c.data,v=c.error,c=!v)):(v=C,(e||!C)&&(C="error",0>e&&(e=0))),N.status=e,N.statusText=(n||C)+"",c?h.resolveWith(f,[y,C,N]):h.rejectWith(f,[N,C,v]),N.statusCode(m),m=t,u&&d.trigger(c?"ajaxSuccess":"ajaxError",[N,p,c?y:v]),g.fireWith(f,[N,C]),u&&(d.trigger("ajaxComplete",[N,p]),--b.active||b.event.trigger("ajaxStop")))}return N},getScript:function(e,n){return b.get(e,t,n,"script")},getJSON:function(e,t,n){return b.get(e,t,n,"json")}});function _n(e,n,r){var i,o,a,s,u=e.contents,l=e.dataTypes,c=e.responseFields;for(s in c)s in r&&(n[c[s]]=r[s]);while("*"===l[0])l.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in u)if(u[s]&&u[s].test(o)){l.unshift(s);break}if(l[0]in r)a=l[0];else{for(s in r){if(!l[0]||e.converters[s+" "+l[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function Fn(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(i in e.converters)a[i.toLowerCase()]=e.converters[i];for(;r=u[++s];)if("*"!==r){if("*"!==l&&l!==r){if(i=a[l+" "+r]||a["* "+r],!i)for(n in a)if(o=n.split(" "),o[1]===r&&(i=a[l+" "+o[0]]||a["* "+o[0]])){i===!0?i=a[n]:a[n]!==!0&&(r=o[0],u.splice(s--,0,r));break}if(i!==!0)if(i&&e["throws"])t=i(t);else try{t=i(t)}catch(c){return{state:"parsererror",error:i?c:"No conversion from "+l+" to "+r}}}l=r}return{state:"success",data:t}}b.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return b.globalEval(e),e}}}),b.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),b.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=o.head||b("head")[0]||o.documentElement;return{send:function(t,i){n=o.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var On=[],Bn=/(=)\?(?=&|$)|\?\?/;b.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=On.pop()||b.expando+"_"+vn++;return this[e]=!0,e}}),b.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=b.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||b.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,On.push(o)),s&&b.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}b.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=b.ajaxSettings.xhr(),b.support.cors=!!Rn&&"withCredentials"in Rn,Rn=b.support.ajax=!!Rn,Rn&&b.ajaxTransport(function(n){if(!n.crossDomain||b.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,p;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=b.noop,$n&&delete Pn[a]),i)4!==u.readyState&&u.abort();else{p={},s=u.status,l=u.getAllResponseHeaders(),"string"==typeof u.responseText&&(p.text=u.responseText);try{c=u.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,l)},n.async?4===u.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},b(e).unload($n)),Pn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+x+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=Yn.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(b.cssNumber[e]?"":"px"),"px"!==r&&s){s=b.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,b.style(i.elem,e,s+r);while(u!==(u=i.cur()/a)&&1!==u&&--l)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=b.now()}function Zn(e,t){b.each(t,function(t,n){var r=(Qn[t]||[]).concat(Qn["*"]),i=0,o=r.length;for(;o>i;i++)if(r[i].call(e,t,n))return})}function er(e,t,n){var r,i,o=0,a=Gn.length,s=b.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;for(;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:b.extend({},t),opts:b.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=b.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(tr(c,l.opts.specialEasing);a>o;o++)if(r=Gn[o].call(l,e,c,l.opts))return r;return Zn(l,c),b.isFunction(l.opts.start)&&l.opts.start.call(e,l),b.fx.timer(b.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function tr(e,t){var n,r,i,o,a;for(i in e)if(r=b.camelCase(i),o=t[r],n=e[i],b.isArray(n)&&(o=n[1],n=e[i]=n[0]),i!==r&&(e[r]=n,delete e[i]),a=b.cssHooks[r],a&&"expand"in a){n=a.expand(n),delete e[r];for(i in n)i in e||(e[i]=n[i],t[i]=o)}else t[r]=o}b.Animation=b.extend(er,{tweener:function(e,t){b.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,u,l,c,p,f=this,d=e.style,h={},g=[],m=e.nodeType&&nn(e);n.queue||(c=b._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,p=c.empty.fire,c.empty.fire=function(){c.unqueued||p()}),c.unqueued++,f.always(function(){f.always(function(){c.unqueued--,b.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===b.css(e,"display")&&"none"===b.css(e,"float")&&(b.support.inlineBlockNeedsLayout&&"inline"!==un(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",b.support.shrinkWrapBlocks||f.always(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(i in t)if(a=t[i],Vn.exec(a)){if(delete t[i],u=u||"toggle"===a,a===(m?"hide":"show"))continue;g.push(i)}if(o=g.length){s=b._data(e,"fxshow")||b._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?b(e).show():f.done(function(){b(e).hide()}),f.done(function(){var t;b._removeData(e,"fxshow");for(t in h)b.style(e,t,h[t])});for(i=0;o>i;i++)r=g[i],l=f.createTween(r,m?s[r]:0),h[r]=s[r]||b.style(e,r),r in s||(s[r]=l.start,m&&(l.end=l.start,l.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}b.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(b.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?b.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=b.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){b.fx.step[e.prop]?b.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[b.cssProps[e.prop]]||b.cssHooks[e.prop])?b.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},b.each(["toggle","show","hide"],function(e,t){var n=b.fn[t];b.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),b.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=b.isEmptyObject(e),o=b.speed(t,n,r),a=function(){var t=er(this,b.extend({},e),o);a.finish=function(){t.stop(!0)},(i||b._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=b.timers,a=b._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&b.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=b._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=b.timers,a=r?r.length:0;for(n.finish=!0,b.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}b.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){b.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),b.speed=function(e,t,n){var r=e&&"object"==typeof e?b.extend({},e):{complete:n||!n&&t||b.isFunction(e)&&e,duration:e,easing:n&&t||t&&!b.isFunction(t)&&t};return r.duration=b.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in b.fx.speeds?b.fx.speeds[r.duration]:b.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){b.isFunction(r.old)&&r.old.call(this),r.queue&&b.dequeue(this,r.queue)},r},b.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},b.timers=[],b.fx=rr.prototype.init,b.fx.tick=function(){var e,n=b.timers,r=0;for(Xn=b.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||b.fx.stop(),Xn=t},b.fx.timer=function(e){e()&&b.timers.push(e)&&b.fx.start()},b.fx.interval=13,b.fx.start=function(){Un||(Un=setInterval(b.fx.tick,b.fx.interval))},b.fx.stop=function(){clearInterval(Un),Un=null},b.fx.speeds={slow:600,fast:200,_default:400},b.fx.step={},b.expr&&b.expr.filters&&(b.expr.filters.animated=function(e){return b.grep(b.timers,function(t){return e===t.elem}).length}),b.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){b.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,b.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},b.offset={setOffset:function(e,t,n){var r=b.css(e,"position");"static"===r&&(e.style.position="relative");var i=b(e),o=i.offset(),a=b.css(e,"top"),s=b.css(e,"left"),u=("absolute"===r||"fixed"===r)&&b.inArray("auto",[a,s])>-1,l={},c={},p,f;u?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),b.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(l.top=t.top-o.top+p),null!=t.left&&(l.left=t.left-o.left+f),"using"in t?t.using.call(e,l):i.css(l)}},b.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===b.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),b.nodeName(e[0],"html")||(n=e.offset()),n.top+=b.css(e[0],"borderTopWidth",!0),n.left+=b.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-b.css(r,"marginTop",!0),left:t.left-n.left-b.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.documentElement;while(e&&!b.nodeName(e,"html")&&"static"===b.css(e,"position"))e=e.offsetParent;return e||o.documentElement})}}),b.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);b.fn[e]=function(i){return b.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?b(a).scrollLeft():o,r?o:b(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return b.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}b.each({Height:"height",Width:"width"},function(e,n){b.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){b.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return b.access(this,function(n,r,i){var o;return b.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?b.css(n,r,s):b.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=b,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return b})})(window);
================================================
FILE: examples/cropper/style.css
================================================
/* ----------------Reset Css--------------------- */
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li,
fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, figcaption, figure, footer, header, hgroup, menu, nav, section, summary,
time, mark, audio, video, input {
margin: 0;
padding: 0;
border: none;
outline: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
html, body, form, fieldset, p, div, h1, h2, h3, h4, h5, h6 {
-webkit-text-size-adjust: none;
}
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
display: block;
}
body {
font-family: arial, sans-serif;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after, q:before, q:after {
content: '';
content: none;
}
ins {
text-decoration: none;
}
del {
text-decoration: line-through;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
/* ------------ */
#wrapper {
width: 980px;
margin: 0 auto;
margin: 1em;
width: auto;
}
.img-preview {
width: 160px;
height: 90px;
margin-top: 1em;
border: 1px solid #ccc;
}
.cropper-wraper {
position: relative;
}
.upload-btn {
background: #ffffff;
border: 1px solid #cfcfcf;
color: #565656;
padding: 10px 18px;
display: inline-block;
border-radius: 3px;
margin-left: 10px;
cursor: pointer;
font-size: 14px;
position: absolute;
right: 1em;
bottom: 2em;
}
.upload-btn:hover {
background: #f0f0f0;
}
================================================
FILE: examples/cropper/uploader.js
================================================
(function( factory ) {
if ( !window.jQuery ) {
alert('jQuery is required.')
}
jQuery(function() {
factory.call( null, jQuery );
});
})(function( $ ) {
// -----------------------------------------------------
// ------------ START ----------------------------------
// -----------------------------------------------------
// ---------------------------------
// --------- Uploader -------------
// ---------------------------------
var Uploader = (function() {
// -------setting-------
// 如果使用原始大小,超大的图片可能会出现 Croper UI 卡顿,所以这里建议先缩小后再crop.
var FRAME_WIDTH = 1600;
var _ = WebUploader;
var Uploader = _.Uploader;
var uploaderContainer = $('.uploader-container');
var uploader, file;
if ( !Uploader.support() ) {
alert( 'Web Uploader 不支持您的浏览器!');
throw new Error( 'WebUploader does not support the browser you are using.' );
}
// hook,
// 在文件开始上传前进行裁剪。
Uploader.register({
'before-send-file': 'cropImage'
}, {
cropImage: function( file ) {
var data = file._cropData,
image, deferred;
file = this.request( 'get-file', file );
deferred = _.Deferred();
image = new _.Lib.Image();
deferred.always(function() {
image.destroy();
image = null;
});
image.once( 'error', deferred.reject );
image.once( 'load', function() {
if (file._info)
{
image.resize( file._info.width, file._info.height );
}
});
image.once( 'complete', function() {
image.crop( data.x, data.y, data.width, data.height, data.scale );
var blob, size;
// 移动端 UC / qq 浏览器的无图模式下
// ctx.getImageData 处理大图的时候会报 Exception
// INDEX_SIZE_ERR: DOM Exception 1
try {
blob = image.getAsBlob(file.type);
size = file.size;
file.source = blob;
file.size = blob.size;
file.trigger( 'resize', blob.size, size );
deferred.resolve();
} catch ( e ) {
console.log( e );
// 出错了直接继续,让其上传原始图片
deferred.resolve();
}
});
file._info && image.info( file._info );
file._meta && image.meta( file._meta );
image.loadFromBlob( file.source );
return deferred.promise();
}
});
return {
init: function( selectCb ) {
uploader = new Uploader({
pick: {
id: '#filePicker',
multiple: false
},
runtimeOrder: 'flash',
// 设置用什么方式去生成缩略图。
thumb: {
quality: 70,
// 不允许放大
allowMagnify: false,
// 是否采用裁剪模式。如果采用这样可以避免空白内容。
crop: false
},
// 禁掉分块传输,默认是开起的。
chunked: false,
// 禁掉上传前压缩功能,因为会手动裁剪。
compress: false,
// fileSingleSizeLimit: 2 * 1024 * 1024,
server: '../../server/fileupload.php',
swf: '../../dist/Uploader.swf',
fileNumLimit: 1,
onError: function() {
var args = [].slice.call(arguments, 0);
alert(args.join('\n'));
}
});
uploader.on('fileQueued', function( _file ) {
file = _file;
uploader.makeThumb( file, function( error, src ) {
if ( error ) {
alert('不能预览');
return;
}
selectCb( src );
}, FRAME_WIDTH, 1 ); // 注意这里的 height 值是 1,被当成了 100% 使用。
});
},
crop: function( data ) {
var scale = Croper.getImageSize().width / file._info.width;
data.scale = scale;
file._cropData = {
x: data.x1,
y: data.y1,
width: data.width,
height: data.height,
scale: data.scale
};
},
upload: function() {
uploader.upload();
}
}
})();
// ---------------------------------
// --------- Crpper ---------------
// ---------------------------------
var Croper = (function() {
var container = $('.cropper-wraper');
var $image = container.find('.img-container img');
var btn = $('.upload-btn');
var isBase64Supported, callback;
$image.cropper({
aspectRatio: 16 / 9,
preview: ".img-preview",
done: function(data) {
// console.log(data);
}
});
function srcWrap( src, cb ) {
// we need to check this at the first time.
if (typeof isBase64Supported === 'undefined') {
(function() {
var data = new Image();
var support = true;
data.onload = data.onerror = function() {
if( this.width != 1 || this.height != 1 ) {
support = false;
}
}
data.src = src;
isBase64Supported = support;
})();
}
if ( isBase64Supported ) {
cb( src );
} else {
// otherwise we need server support.
// convert base64 to a file.
$.ajax('../../server/preview.php', {
method: 'POST',
data: src,
dataType:'json'
}).done(function( response ) {
if (response.result) {
cb( response.result );
} else {
alert("预览出错");
}
});
}
}
btn.on('click', function() {
callback && callback($image.cropper("getData"));
return false;
});
return {
setSource: function( src ) {
// 处理 base64 不支持的情况。
// 一般出现在 ie6-ie8
srcWrap( src, function( src ) {
$image.cropper("setImgSrc", src);
});
container.removeClass('webuploader-element-invisible');
return this;
},
getImageSize: function() {
var img = $image.get(0);
return {
width: img.naturalWidth,
height: img.naturalHeight
}
},
setCallback: function( cb ) {
callback = cb;
return this;
},
disable: function() {
$image.cropper("disable");
return this;
},
enable: function() {
$image.cropper("enable");
return this;
}
}
})();
// ------------------------------
// -----------logic--------------
// ------------------------------
var container = $('.uploader-container');
Uploader.init(function( src ) {
Croper.setSource( src );
// 隐藏选择按钮。
container.addClass('webuploader-element-invisible');
// 当用户选择上传的时候,开始上传。
Croper.setCallback(function( data ) {
Uploader.crop(data);
Uploader.upload();
});
});
// -----------------------------------------------------
// ------------ END ------------------------------------
// -----------------------------------------------------
});
================================================
FILE: examples/image-upload/index.html
================================================
WebUploader演示
================================================
FILE: examples/image-upload/jquery.js
================================================
/*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license
*/(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML="
a ",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="
",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="
",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;
return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML="
";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="
",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="
",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML="
",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML="
",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML="
",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||st.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&>(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/
\s*$/g,At={option:[1,""," "],legend:[1,""," "],area:[1,""," "],param:[1,""," "],thead:[1,""],tr:[2,""],col:[2,""],td:[3,""],_default:b.support.htmlSerialize?[0,"",""]:[1,"X","
"]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1>$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1>$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?""!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l)
}b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b("").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write(""),t.close(),n=ln(e,t),Pt.detach()),Gt[e]=n),n}function ln(e,t){var n=b(t.createElement(e)).appendTo(t.body),r=b.css(n[0],"display");return n.remove(),r}b.each(["height","width"],function(e,n){b.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(b.css(e,"display"))?b.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,i),i):0)}}}),b.support.opacity||(b.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=b.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===b.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),b(function(){b.support.reliableMarginRight||(b.cssHooks.marginRight={get:function(e,n){return n?b.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!b.support.pixelPosition&&b.fn.position&&b.each(["top","left"],function(e,n){b.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?b(e).position()[n]+"px":r):t}}})}),b.expr&&b.expr.filters&&(b.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!b.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||b.css(e,"display"))},b.expr.filters.visible=function(e){return!b.expr.filters.hidden(e)}),b.each({margin:"",padding:"",border:"Width"},function(e,t){b.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(b.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;b.fn.extend({serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=b.prop(this,"elements");return e?b.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!b(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Nt.test(e))}).map(function(e,t){var n=b(this).val();return null==n?null:b.isArray(n)?b.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),b.param=function(e,n){var r,i=[],o=function(e,t){t=b.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=b.ajaxSettings&&b.ajaxSettings.traditional),b.isArray(e)||e.jquery&&!b.isPlainObject(e))b.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(b.isArray(t))b.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==b.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}b.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){b.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),b.fn.hover=function(e,t){return this.mouseenter(e).mouseleave(t||e)};var mn,yn,vn=b.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Nn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Cn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=b.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=a.href}catch(Ln){yn=o.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[];if(b.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(u){var l;return o[u]=!0,b.each(e[u]||[],function(e,u){var c=u(n,r,i);return"string"!=typeof c||a||o[c]?a?!(l=c):t:(n.dataTypes.unshift(c),s(c),!1)}),l}return s(n.dataTypes[0])||!o["*"]&&s("*")}function Mn(e,n){var r,i,o=b.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&b.extend(!0,e,r),e}b.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,u=e.indexOf(" ");return u>=0&&(i=e.slice(u,e.length),e=e.slice(0,u)),b.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&b.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?b("").append(b.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},b.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){b.fn[t]=function(e){return this.on(t,e)}}),b.each(["get","post"],function(e,n){b[n]=function(e,r,i,o){return b.isFunction(r)&&(o=o||i,i=r,r=t),b.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),b.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Nn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Mn(Mn(e,b.ajaxSettings),t):Mn(b.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,u,l,c,p=b.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?b(f):b.event,h=b.Deferred(),g=b.Callbacks("once memory"),m=p.statusCode||{},y={},v={},x=0,T="canceled",N={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else N.always(e[N.status]);return this},abort:function(e){var t=e||T;return l&&l.abort(t),k(0,t),this}};if(h.promise(N).complete=g.add,N.success=N.done,N.error=N.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=b.trim(p.dataType||"*").toLowerCase().match(w)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?80:443))==(mn[3]||("http:"===mn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=b.param(p.data,p.traditional)),qn(An,p,n,N),2===x)return N;u=p.global,u&&0===b.active++&&b.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Cn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(b.lastModified[o]&&N.setRequestHeader("If-Modified-Since",b.lastModified[o]),b.etag[o]&&N.setRequestHeader("If-None-Match",b.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&N.setRequestHeader("Content-Type",p.contentType),N.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)N.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,N,p)===!1||2===x))return N.abort();T="abort";for(i in{success:1,error:1,complete:1})N[i](p[i]);if(l=qn(jn,p,n,N)){N.readyState=1,u&&d.trigger("ajaxSend",[N,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){N.abort("timeout")},p.timeout));try{x=1,l.send(y,k)}catch(C){if(!(2>x))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,C=n;2!==x&&(x=2,s&&clearTimeout(s),l=t,a=i||"",N.readyState=e>0?4:0,r&&(w=_n(p,N,r)),e>=200&&300>e||304===e?(p.ifModified&&(T=N.getResponseHeader("Last-Modified"),T&&(b.lastModified[o]=T),T=N.getResponseHeader("etag"),T&&(b.etag[o]=T)),204===e?(c=!0,C="nocontent"):304===e?(c=!0,C="notmodified"):(c=Fn(p,w),C=c.state,y=c.data,v=c.error,c=!v)):(v=C,(e||!C)&&(C="error",0>e&&(e=0))),N.status=e,N.statusText=(n||C)+"",c?h.resolveWith(f,[y,C,N]):h.rejectWith(f,[N,C,v]),N.statusCode(m),m=t,u&&d.trigger(c?"ajaxSuccess":"ajaxError",[N,p,c?y:v]),g.fireWith(f,[N,C]),u&&(d.trigger("ajaxComplete",[N,p]),--b.active||b.event.trigger("ajaxStop")))}return N},getScript:function(e,n){return b.get(e,t,n,"script")},getJSON:function(e,t,n){return b.get(e,t,n,"json")}});function _n(e,n,r){var i,o,a,s,u=e.contents,l=e.dataTypes,c=e.responseFields;for(s in c)s in r&&(n[c[s]]=r[s]);while("*"===l[0])l.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in u)if(u[s]&&u[s].test(o)){l.unshift(s);break}if(l[0]in r)a=l[0];else{for(s in r){if(!l[0]||e.converters[s+" "+l[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function Fn(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(i in e.converters)a[i.toLowerCase()]=e.converters[i];for(;r=u[++s];)if("*"!==r){if("*"!==l&&l!==r){if(i=a[l+" "+r]||a["* "+r],!i)for(n in a)if(o=n.split(" "),o[1]===r&&(i=a[l+" "+o[0]]||a["* "+o[0]])){i===!0?i=a[n]:a[n]!==!0&&(r=o[0],u.splice(s--,0,r));break}if(i!==!0)if(i&&e["throws"])t=i(t);else try{t=i(t)}catch(c){return{state:"parsererror",error:i?c:"No conversion from "+l+" to "+r}}}l=r}return{state:"success",data:t}}b.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return b.globalEval(e),e}}}),b.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),b.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=o.head||b("head")[0]||o.documentElement;return{send:function(t,i){n=o.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var On=[],Bn=/(=)\?(?=&|$)|\?\?/;b.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=On.pop()||b.expando+"_"+vn++;return this[e]=!0,e}}),b.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=b.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||b.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,On.push(o)),s&&b.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}b.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=b.ajaxSettings.xhr(),b.support.cors=!!Rn&&"withCredentials"in Rn,Rn=b.support.ajax=!!Rn,Rn&&b.ajaxTransport(function(n){if(!n.crossDomain||b.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,p;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=b.noop,$n&&delete Pn[a]),i)4!==u.readyState&&u.abort();else{p={},s=u.status,l=u.getAllResponseHeaders(),"string"==typeof u.responseText&&(p.text=u.responseText);try{c=u.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,l)},n.async?4===u.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},b(e).unload($n)),Pn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+x+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=Yn.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(b.cssNumber[e]?"":"px"),"px"!==r&&s){s=b.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,b.style(i.elem,e,s+r);while(u!==(u=i.cur()/a)&&1!==u&&--l)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=b.now()}function Zn(e,t){b.each(t,function(t,n){var r=(Qn[t]||[]).concat(Qn["*"]),i=0,o=r.length;for(;o>i;i++)if(r[i].call(e,t,n))return})}function er(e,t,n){var r,i,o=0,a=Gn.length,s=b.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;for(;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:b.extend({},t),opts:b.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=b.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(tr(c,l.opts.specialEasing);a>o;o++)if(r=Gn[o].call(l,e,c,l.opts))return r;return Zn(l,c),b.isFunction(l.opts.start)&&l.opts.start.call(e,l),b.fx.timer(b.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function tr(e,t){var n,r,i,o,a;for(i in e)if(r=b.camelCase(i),o=t[r],n=e[i],b.isArray(n)&&(o=n[1],n=e[i]=n[0]),i!==r&&(e[r]=n,delete e[i]),a=b.cssHooks[r],a&&"expand"in a){n=a.expand(n),delete e[r];for(i in n)i in e||(e[i]=n[i],t[i]=o)}else t[r]=o}b.Animation=b.extend(er,{tweener:function(e,t){b.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,u,l,c,p,f=this,d=e.style,h={},g=[],m=e.nodeType&&nn(e);n.queue||(c=b._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,p=c.empty.fire,c.empty.fire=function(){c.unqueued||p()}),c.unqueued++,f.always(function(){f.always(function(){c.unqueued--,b.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===b.css(e,"display")&&"none"===b.css(e,"float")&&(b.support.inlineBlockNeedsLayout&&"inline"!==un(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",b.support.shrinkWrapBlocks||f.always(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(i in t)if(a=t[i],Vn.exec(a)){if(delete t[i],u=u||"toggle"===a,a===(m?"hide":"show"))continue;g.push(i)}if(o=g.length){s=b._data(e,"fxshow")||b._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?b(e).show():f.done(function(){b(e).hide()}),f.done(function(){var t;b._removeData(e,"fxshow");for(t in h)b.style(e,t,h[t])});for(i=0;o>i;i++)r=g[i],l=f.createTween(r,m?s[r]:0),h[r]=s[r]||b.style(e,r),r in s||(s[r]=l.start,m&&(l.end=l.start,l.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}b.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(b.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?b.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=b.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){b.fx.step[e.prop]?b.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[b.cssProps[e.prop]]||b.cssHooks[e.prop])?b.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},b.each(["toggle","show","hide"],function(e,t){var n=b.fn[t];b.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),b.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=b.isEmptyObject(e),o=b.speed(t,n,r),a=function(){var t=er(this,b.extend({},e),o);a.finish=function(){t.stop(!0)},(i||b._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=b.timers,a=b._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&b.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=b._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=b.timers,a=r?r.length:0;for(n.finish=!0,b.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}b.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){b.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),b.speed=function(e,t,n){var r=e&&"object"==typeof e?b.extend({},e):{complete:n||!n&&t||b.isFunction(e)&&e,duration:e,easing:n&&t||t&&!b.isFunction(t)&&t};return r.duration=b.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in b.fx.speeds?b.fx.speeds[r.duration]:b.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){b.isFunction(r.old)&&r.old.call(this),r.queue&&b.dequeue(this,r.queue)},r},b.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},b.timers=[],b.fx=rr.prototype.init,b.fx.tick=function(){var e,n=b.timers,r=0;for(Xn=b.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||b.fx.stop(),Xn=t},b.fx.timer=function(e){e()&&b.timers.push(e)&&b.fx.start()},b.fx.interval=13,b.fx.start=function(){Un||(Un=setInterval(b.fx.tick,b.fx.interval))},b.fx.stop=function(){clearInterval(Un),Un=null},b.fx.speeds={slow:600,fast:200,_default:400},b.fx.step={},b.expr&&b.expr.filters&&(b.expr.filters.animated=function(e){return b.grep(b.timers,function(t){return e===t.elem}).length}),b.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){b.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,b.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},b.offset={setOffset:function(e,t,n){var r=b.css(e,"position");"static"===r&&(e.style.position="relative");var i=b(e),o=i.offset(),a=b.css(e,"top"),s=b.css(e,"left"),u=("absolute"===r||"fixed"===r)&&b.inArray("auto",[a,s])>-1,l={},c={},p,f;u?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),b.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(l.top=t.top-o.top+p),null!=t.left&&(l.left=t.left-o.left+f),"using"in t?t.using.call(e,l):i.css(l)}},b.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===b.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),b.nodeName(e[0],"html")||(n=e.offset()),n.top+=b.css(e[0],"borderTopWidth",!0),n.left+=b.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-b.css(r,"marginTop",!0),left:t.left-n.left-b.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.documentElement;while(e&&!b.nodeName(e,"html")&&"static"===b.css(e,"position"))e=e.offsetParent;return e||o.documentElement})}}),b.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);b.fn[e]=function(i){return b.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?b(a).scrollLeft():o,r?o:b(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return b.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}b.each({Height:"height",Width:"width"},function(e,n){b.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){b.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return b.access(this,function(n,r,i){var o;return b.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?b.css(n,r,s):b.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=b,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return b})})(window);
================================================
FILE: examples/image-upload/style.css
================================================
/* ----------------Reset Css--------------------- */
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li,
fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, figcaption, figure, footer, header, hgroup, menu, nav, section, summary,
time, mark, audio, video, input {
margin: 0;
padding: 0;
border: none;
outline: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
html, body, form, fieldset, p, div, h1, h2, h3, h4, h5, h6 {
-webkit-text-size-adjust: none;
}
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
display: block;
}
body {
font-family: arial, sans-serif;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after, q:before, q:after {
content: '';
content: none;
}
ins {
text-decoration: none;
}
del {
text-decoration: line-through;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
/* ------------ */
#wrapper {
width: 980px;
margin: 0 auto;
margin: 1em;
width: auto;
}
#container {
border: 1px solid #dadada;
color: #838383;
font-size: 12px;
margin-top: 10px;
background-color: #FFF;
}
#uploader .queueList {
margin: 20px;
}
.element-invisible {
position: absolute !important;
clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
clip: rect(1px,1px,1px,1px);
}
#uploader .placeholder {
border: 3px dashed #e6e6e6;
min-height: 238px;
padding-top: 158px;
text-align: center;
background: url(./image.png) center 93px no-repeat;
color: #cccccc;
font-size: 18px;
position: relative;
}
#uploader .placeholder .webuploader-pick {
font-size: 18px;
background: #00b7ee;
border-radius: 3px;
line-height: 44px;
padding: 0 30px;
color: #fff;
display: inline-block;
margin: 20px auto;
cursor: pointer;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
}
#uploader .placeholder .webuploader-pick-hover {
background: #00a2d4;
}
#uploader .placeholder .flashTip {
color: #666666;
font-size: 12px;
position: absolute;
width: 100%;
text-align: center;
bottom: 20px;
}
#uploader .placeholder .flashTip a {
color: #0785d1;
text-decoration: none;
}
#uploader .placeholder .flashTip a:hover {
text-decoration: underline;
}
#uploader .placeholder.webuploader-dnd-over {
border-color: #999999;
}
#uploader .placeholder.webuploader-dnd-over.webuploader-dnd-denied {
border-color: red;
}
#uploader .filelist {
list-style: none;
margin: 0;
padding: 0;
}
#uploader .filelist:after {
content: '';
display: block;
width: 0;
height: 0;
overflow: hidden;
clear: both;
}
#uploader .filelist li {
width: 110px;
height: 110px;
background: url(./bg.png) no-repeat;
text-align: center;
margin: 0 8px 20px 0;
position: relative;
display: inline;
float: left;
overflow: hidden;
font-size: 12px;
}
#uploader .filelist li p.log {
position: relative;
top: -45px;
}
#uploader .filelist li p.title {
position: absolute;
top: 0;
left: 0;
width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow : ellipsis;
top: 5px;
text-indent: 5px;
text-align: left;
}
#uploader .filelist li p.progress {
position: absolute;
width: 100%;
bottom: 0;
left: 0;
height: 8px;
overflow: hidden;
z-index: 50;
}
#uploader .filelist li p.progress span {
display: none;
overflow: hidden;
width: 0;
height: 100%;
background: #1483d8 url(./progress.png) repeat-x;
-webit-transition: width 200ms linear;
-moz-transition: width 200ms linear;
-o-transition: width 200ms linear;
-ms-transition: width 200ms linear;
transition: width 200ms linear;
-webkit-animation: progressmove 2s linear infinite;
-moz-animation: progressmove 2s linear infinite;
-o-animation: progressmove 2s linear infinite;
-ms-animation: progressmove 2s linear infinite;
animation: progressmove 2s linear infinite;
-webkit-transform: translateZ(0);
}
@-webkit-keyframes progressmove {
0% {
background-position: 0 0;
}
100% {
background-position: 17px 0;
}
}
@-moz-keyframes progressmove {
0% {
background-position: 0 0;
}
100% {
background-position: 17px 0;
}
}
@keyframes progressmove {
0% {
background-position: 0 0;
}
100% {
background-position: 17px 0;
}
}
#uploader .filelist li p.imgWrap {
position: relative;
z-index: 2;
line-height: 110px;
vertical-align: middle;
overflow: hidden;
width: 110px;
height: 110px;
-webkit-transform-origin: 50% 50%;
-moz-transform-origin: 50% 50%;
-o-transform-origin: 50% 50%;
-ms-transform-origin: 50% 50%;
transform-origin: 50% 50%;
-webit-transition: 200ms ease-out;
-moz-transition: 200ms ease-out;
-o-transition: 200ms ease-out;
-ms-transition: 200ms ease-out;
transition: 200ms ease-out;
}
#uploader .filelist li img {
width: 100%;
}
#uploader .filelist li p.error {
background: #f43838;
color: #fff;
position: absolute;
bottom: 0;
left: 0;
height: 28px;
line-height: 28px;
width: 100%;
z-index: 100;
}
#uploader .filelist li .success {
display: block;
position: absolute;
left: 0;
bottom: 0;
height: 40px;
width: 100%;
z-index: 200;
background: url(./success.png) no-repeat right bottom;
}
#uploader .filelist div.file-panel {
position: absolute;
height: 0;
filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#80000000', endColorstr='#80000000')\0;
background: rgba( 0, 0, 0, 0.5 );
width: 100%;
top: 0;
left: 0;
overflow: hidden;
z-index: 300;
}
#uploader .filelist div.file-panel span {
width: 24px;
height: 24px;
display: inline;
float: right;
text-indent: -9999px;
overflow: hidden;
background: url(./icons.png) no-repeat;
margin: 5px 1px 1px;
cursor: pointer;
}
#uploader .filelist div.file-panel span.rotateLeft {
background-position: 0 -24px;
}
#uploader .filelist div.file-panel span.rotateLeft:hover {
background-position: 0 0;
}
#uploader .filelist div.file-panel span.rotateRight {
background-position: -24px -24px;
}
#uploader .filelist div.file-panel span.rotateRight:hover {
background-position: -24px 0;
}
#uploader .filelist div.file-panel span.cancel {
background-position: -48px -24px;
}
#uploader .filelist div.file-panel span.cancel:hover {
background-position: -48px 0;
}
#uploader .statusBar {
height: 63px;
border-top: 1px solid #dadada;
padding: 0 20px;
line-height: 63px;
vertical-align: middle;
position: relative;
}
#uploader .statusBar .progress {
border: 1px solid #1483d8;
width: 198px;
background: #fff;
height: 18px;
position: relative;
display: inline-block;
text-align: center;
line-height: 20px;
color: #6dbfff;
position: relative;
margin-right: 10px;
}
#uploader .statusBar .progress span.percentage {
width: 0;
height: 100%;
left: 0;
top: 0;
background: #1483d8;
position: absolute;
}
#uploader .statusBar .progress span.text {
position: relative;
z-index: 10;
}
#uploader .statusBar .info {
display: inline-block;
font-size: 14px;
color: #666666;
}
#uploader .statusBar .btns {
position: absolute;
top: 10px;
right: 20px;
line-height: 40px;
}
#filePicker2 {
display: inline-block;
float: left;
}
#uploader .statusBar .btns .webuploader-pick,
#uploader .statusBar .btns .uploadBtn,
#uploader .statusBar .btns .uploadBtn.state-uploading,
#uploader .statusBar .btns .uploadBtn.state-paused {
background: #ffffff;
border: 1px solid #cfcfcf;
color: #565656;
padding: 0 18px;
display: inline-block;
border-radius: 3px;
margin-left: 10px;
cursor: pointer;
font-size: 14px;
float: left;
}
#uploader .statusBar .btns .webuploader-pick-hover,
#uploader .statusBar .btns .uploadBtn:hover,
#uploader .statusBar .btns .uploadBtn.state-uploading:hover,
#uploader .statusBar .btns .uploadBtn.state-paused:hover {
background: #f0f0f0;
}
#uploader .statusBar .btns .uploadBtn {
background: #00b7ee;
color: #fff;
border-color: transparent;
}
#uploader .statusBar .btns .uploadBtn:hover {
background: #00a2d4;
}
#uploader .statusBar .btns .uploadBtn.disabled {
pointer-events: none;
opacity: 0.6;
}
================================================
FILE: examples/image-upload/upload.js
================================================
(function( $ ){
// 当domReady的时候开始初始化
$(function() {
var $wrap = $('#uploader'),
// 图片容器
$queue = $( '
' )
.appendTo( $wrap.find( '.queueList' ) ),
// 状态栏,包括进度和控制按钮
$statusBar = $wrap.find( '.statusBar' ),
// 文件总体选择信息。
$info = $statusBar.find( '.info' ),
// 上传按钮
$upload = $wrap.find( '.uploadBtn' ),
// 没选择文件之前的内容。
$placeHolder = $wrap.find( '.placeholder' ),
$progress = $statusBar.find( '.progress' ).hide(),
// 添加的文件数量
fileCount = 0,
// 添加的文件总大小
fileSize = 0,
// 优化retina, 在retina下这个值是2
ratio = window.devicePixelRatio || 1,
// 缩略图大小
thumbnailWidth = 110 * ratio,
thumbnailHeight = 110 * ratio,
// 可能有pedding, ready, uploading, confirm, done.
state = 'pedding',
// 所有文件的进度信息,key为file id
percentages = {},
// 判断浏览器是否支持图片的base64
isSupportBase64 = ( function() {
var data = new Image();
var support = true;
data.onload = data.onerror = function() {
if( this.width != 1 || this.height != 1 ) {
support = false;
}
}
data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
return support;
} )(),
// 检测是否已经安装flash,检测flash的版本
flashVersion = ( function() {
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 );
} )(),
supportTransition = (function(){
var s = document.createElement('p').style,
r = 'transition' in s ||
'WebkitTransition' in s ||
'MozTransition' in s ||
'msTransition' in s ||
'OTransition' in s;
s = null;
return r;
})(),
// WebUploader实例
uploader;
if ( !WebUploader.Uploader.support('flash') && WebUploader.browser.ie ) {
// flash 安装了但是版本过低。
if (flashVersion) {
(function(container) {
window['expressinstallcallback'] = function( state ) {
switch(state) {
case 'Download.Cancelled':
alert('您取消了更新!')
break;
case 'Download.Failed':
alert('安装失败')
break;
default:
alert('安装已成功,请刷新!');
break;
}
delete window['expressinstallcallback'];
};
var swf = './expressInstall.swf';
// insert flash object
var html = '
' +
' ' +
' ' +
' ' +
' ';
container.html(html);
})($wrap);
// 压根就没有安转。
} else {
$wrap.html('
');
}
return;
} else if (!WebUploader.Uploader.support()) {
alert( 'Web Uploader 不支持您的浏览器!');
return;
}
// 实例化
uploader = WebUploader.create({
pick: {
id: '#filePicker',
label: '点击选择图片'
},
formData: {
uid: 123
},
dnd: '#uploader .queueList',
paste: '#uploader',
swf: '../../dist/Uploader.swf',
chunked: false,
chunkSize: 512 * 1024,
server: '../../server/fileupload.php',
// runtimeOrder: 'flash',
// accept: {
// title: 'Images',
// extensions: 'gif,jpg,jpeg,bmp,png',
// mimeTypes: 'image/*'
// },
// 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候,把图片打开。
disableGlobalDnd: true,
fileNumLimit: 300,
fileSizeLimit: 200 * 1024 * 1024, // 200 M
fileSingleSizeLimit: 50 * 1024 * 1024 // 50 M
});
// 拖拽时不接受 js, txt 文件。
uploader.on( 'dndAccept', function( items ) {
var denied = false,
len = items.length,
i = 0,
// 修改js类型
unAllowed = 'text/plain;application/javascript ';
for ( ; i < len; i++ ) {
// 如果在列表里面
if ( ~unAllowed.indexOf( items[ i ].type ) ) {
denied = true;
break;
}
}
return !denied;
});
uploader.on('dialogOpen', function() {
console.log('here');
});
// uploader.on('filesQueued', function() {
// uploader.sort(function( a, b ) {
// if ( a.name < b.name )
// return -1;
// if ( a.name > b.name )
// return 1;
// return 0;
// });
// });
// 添加“添加文件”的按钮,
uploader.addButton({
id: '#filePicker2',
label: '继续添加'
});
uploader.on('ready', function() {
window.uploader = uploader;
});
// 当有文件添加进来时执行,负责view的创建
function addFile( file ) {
var $li = $( '
' +
'' + file.name + '
' +
'
'+
'
' +
' ' ),
$btns = $('
' +
'删除 ' +
'向右旋转 ' +
'向左旋转
').appendTo( $li ),
$prgress = $li.find('p.progress span'),
$wrap = $li.find( 'p.imgWrap' ),
$info = $('
'),
showError = function( code ) {
switch( code ) {
case 'exceed_size':
text = '文件大小超出';
break;
case 'interrupt':
text = '上传暂停';
break;
default:
text = '上传失败,请重试';
break;
}
$info.text( text ).appendTo( $li );
};
if ( file.getStatus() === 'invalid' ) {
showError( file.statusText );
} else {
// @todo lazyload
$wrap.text( '预览中' );
uploader.makeThumb( file, function( error, src ) {
var img;
if ( error ) {
$wrap.text( '不能预览' );
return;
}
if( isSupportBase64 ) {
img = $('
');
$wrap.empty().append( img );
} else {
$.ajax('../../server/preview.php', {
method: 'POST',
data: src,
dataType:'json'
}).done(function( response ) {
if (response.result) {
img = $('
');
$wrap.empty().append( img );
} else {
$wrap.text("预览出错");
}
});
}
}, thumbnailWidth, thumbnailHeight );
percentages[ file.id ] = [ file.size, 0 ];
file.rotation = 0;
}
file.on('statuschange', function( cur, prev ) {
if ( prev === 'progress' ) {
$prgress.hide().width(0);
} else if ( prev === 'queued' ) {
$li.off( 'mouseenter mouseleave' );
$btns.remove();
}
// 成功
if ( cur === 'error' || cur === 'invalid' ) {
console.log( file.statusText );
showError( file.statusText );
percentages[ file.id ][ 1 ] = 1;
} else if ( cur === 'interrupt' ) {
showError( 'interrupt' );
} else if ( cur === 'queued' ) {
$info.remove();
$prgress.css('display', 'block');
percentages[ file.id ][ 1 ] = 0;
} else if ( cur === 'progress' ) {
$info.remove();
$prgress.css('display', 'block');
} else if ( cur === 'complete' ) {
$prgress.hide().width(0);
$li.append( '
' );
}
$li.removeClass( 'state-' + prev ).addClass( 'state-' + cur );
});
$li.on( 'mouseenter', function() {
$btns.stop().animate({height: 30});
});
$li.on( 'mouseleave', function() {
$btns.stop().animate({height: 0});
});
$btns.on( 'click', 'span', function() {
var index = $(this).index(),
deg;
switch ( index ) {
case 0:
uploader.removeFile( file );
return;
case 1:
file.rotation += 90;
break;
case 2:
file.rotation -= 90;
break;
}
if ( supportTransition ) {
deg = 'rotate(' + file.rotation + 'deg)';
$wrap.css({
'-webkit-transform': deg,
'-mos-transform': deg,
'-o-transform': deg,
'transform': deg
});
} else {
$wrap.css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ (~~((file.rotation/90)%4 + 4)%4) +')');
// use jquery animate to rotation
// $({
// rotation: rotation
// }).animate({
// rotation: file.rotation
// }, {
// easing: 'linear',
// step: function( now ) {
// now = now * Math.PI / 180;
// var cos = Math.cos( now ),
// sin = Math.sin( now );
// $wrap.css( 'filter', "progid:DXImageTransform.Microsoft.Matrix(M11=" + cos + ",M12=" + (-sin) + ",M21=" + sin + ",M22=" + cos + ",SizingMethod='auto expand')");
// }
// });
}
});
$li.appendTo( $queue );
}
// 负责view的销毁
function removeFile( file ) {
var $li = $('#'+file.id);
delete percentages[ file.id ];
updateTotalProgress();
$li.off().find('.file-panel').off().end().remove();
}
function updateTotalProgress() {
var loaded = 0,
total = 0,
spans = $progress.children(),
percent;
$.each( percentages, function( k, v ) {
total += v[ 0 ];
loaded += v[ 0 ] * v[ 1 ];
} );
percent = total ? loaded / total : 0;
spans.eq( 0 ).text( Math.round( percent * 100 ) + '%' );
spans.eq( 1 ).css( 'width', Math.round( percent * 100 ) + '%' );
updateStatus();
}
function updateStatus() {
var text = '', stats;
if ( state === 'ready' ) {
text = '选中' + fileCount + '张图片,共' +
WebUploader.formatSize( fileSize ) + '。';
} else if ( state === 'confirm' ) {
stats = uploader.getStats();
if ( stats.uploadFailNum ) {
text = '已成功上传' + stats.successNum+ '张照片至XX相册,'+
stats.uploadFailNum + '张照片上传失败,
重新上传 失败图片或
忽略 '
}
} else {
stats = uploader.getStats();
text = '共' + fileCount + '张(' +
WebUploader.formatSize( fileSize ) +
'),已上传' + stats.successNum + '张';
if ( stats.uploadFailNum ) {
text += ',失败' + stats.uploadFailNum + '张';
}
}
$info.html( text );
}
function setState( val ) {
var file, stats;
if ( val === state ) {
return;
}
$upload.removeClass( 'state-' + state );
$upload.addClass( 'state-' + val );
state = val;
switch ( state ) {
case 'pedding':
$placeHolder.removeClass( 'element-invisible' );
$queue.hide();
$statusBar.addClass( 'element-invisible' );
uploader.refresh();
break;
case 'ready':
$placeHolder.addClass( 'element-invisible' );
$( '#filePicker2' ).removeClass( 'element-invisible');
$queue.show();
$statusBar.removeClass('element-invisible');
uploader.refresh();
break;
case 'uploading':
$( '#filePicker2' ).addClass( 'element-invisible' );
$progress.show();
$upload.text( '暂停上传' );
break;
case 'paused':
$progress.show();
$upload.text( '继续上传' );
break;
case 'confirm':
$progress.hide();
$( '#filePicker2' ).removeClass( 'element-invisible' );
$upload.text( '开始上传' );
stats = uploader.getStats();
if ( stats.successNum && !stats.uploadFailNum ) {
setState( 'finish' );
return;
}
break;
case 'finish':
stats = uploader.getStats();
if ( stats.successNum ) {
alert( '上传成功' );
} else {
// 没有成功的图片,重设
state = 'done';
location.reload();
}
break;
}
updateStatus();
}
uploader.onUploadProgress = function( file, percentage ) {
var $li = $('#'+file.id),
$percent = $li.find('.progress span');
$percent.css( 'width', percentage * 100 + '%' );
percentages[ file.id ][ 1 ] = percentage;
updateTotalProgress();
};
uploader.onFileQueued = function( file ) {
fileCount++;
fileSize += file.size;
if ( fileCount === 1 ) {
$placeHolder.addClass( 'element-invisible' );
$statusBar.show();
}
addFile( file );
setState( 'ready' );
updateTotalProgress();
};
uploader.onFileDequeued = function( file ) {
fileCount--;
fileSize -= file.size;
if ( !fileCount ) {
setState( 'pedding' );
}
removeFile( file );
updateTotalProgress();
};
uploader.on( 'all', function( type ) {
var stats;
switch( type ) {
case 'uploadFinished':
setState( 'confirm' );
break;
case 'startUpload':
setState( 'uploading' );
break;
case 'stopUpload':
setState( 'paused' );
break;
}
});
uploader.onError = function( code ) {
alert( 'Eroor: ' + code );
};
$upload.on('click', function() {
if ( $(this).hasClass( 'disabled' ) ) {
return false;
}
if ( state === 'ready' ) {
uploader.upload();
} else if ( state === 'paused' ) {
uploader.upload();
} else if ( state === 'uploading' ) {
uploader.stop();
}
});
$info.on( 'click', '.retry', function() {
uploader.retry();
} );
$info.on( 'click', '.ignore', function() {
alert( 'todo' );
} );
$upload.addClass( 'state-' + state );
updateTotalProgress();
});
})( jQuery );
================================================
FILE: examples/md5-demo/index.html
================================================
WebUploader演示 - 带裁剪功能
console 会影响 md5 时间的计算,所以在测试 md5 速度的时候,把 console 关了
================================================
FILE: examples/md5-demo/script.js
================================================
(function($) {
$(function() {
var log = (function() {
var dom = $('#log');
return function( str ) {
dom.append('
' + str + '
')
}
})();
WebUploader.create({
pick: '#filePicker'
}).on('fileQueued', function( file ) {
var start = +new Date();
// 返回的是 promise 对象
this.md5File(file, 0, 1 * 1024 * 1024)
// 可以用来监听进度
.progress(function(percentage) {
// console.log('Percentage:', percentage);
})
// 处理完成后触发
.then(function(ret) {
// console.log('md5:', ret);
var end = +new Date();
log('HTML5: md5 ' + file.name + ' cost ' + (end - start) + 'ms get value: ' + ret);
});
});
WebUploader.create({
pick: '#filePicker2',
swf: '../../dist/Uploader.swf',
runtimeOrder: 'flash'
}).on('fileQueued', function( file ) {
var start = +new Date();
// 返回的是 promise 对象
this.md5File(file, 0, 1 * 1024 * 1024)
// 可以用来监听进度
.progress(function(percentage) {
// console.log('Percentage:', percentage);
})
// 处理完成后触发
.then(function(ret) {
// console.log('md5:', ret);
var end = +new Date();
log('Flash: md5 ' + file.name + ' cost ' + (end - start) + 'ms get value: ' + ret);
});
});
});
})(jQuery);
================================================
FILE: examples/requirejs/app.js
================================================
requirejs.config({
baseUrl: '../../dist',
paths: {
jquery: '../examples/image-upload/jquery'
}
});
require([ 'webuploader.flashonly' ], function( WebUploader ) {
// 当domReady的时候开始初始化
$(function() {
var $wrap = $('#uploader'),
// 图片容器
$queue = $( '
' )
.appendTo( $wrap.find( '.queueList' ) ),
// 状态栏,包括进度和控制按钮
$statusBar = $wrap.find( '.statusBar' ),
// 文件总体选择信息。
$info = $statusBar.find( '.info' ),
// 上传按钮
$upload = $wrap.find( '.uploadBtn' ),
// 没选择文件之前的内容。
$placeHolder = $wrap.find( '.placeholder' ),
$progress = $statusBar.find( '.progress' ).hide(),
// 添加的文件数量
fileCount = 0,
// 添加的文件总大小
fileSize = 0,
// 优化retina, 在retina下这个值是2
ratio = window.devicePixelRatio || 1,
// 缩略图大小
thumbnailWidth = 110 * ratio,
thumbnailHeight = 110 * ratio,
// 可能有pedding, ready, uploading, confirm, done.
state = 'pedding',
// 所有文件的进度信息,key为file id
percentages = {},
supportTransition = (function(){
var s = document.createElement('p').style,
r = 'transition' in s ||
'WebkitTransition' in s ||
'MozTransition' in s ||
'msTransition' in s ||
'OTransition' in s;
s = null;
return r;
})(),
// WebUploader实例
uploader;
// 实例化
uploader = WebUploader.create({
pick: {
id: '#filePicker',
label: '点击选择图片'
},
dnd: '#dndArea',
paste: '#uploader',
swf: '../../dist/Uploader.swf',
chunked: true,
// runtimeOrder: 'flash',
sendAsBinary: true,
server: '../../server/fileupload.php',
// server: 'http://liaoxuezhi.fe.baidu.com/webupload/fileupload.php',
// server: 'http://www.2betop.net/fileupload.php',
fileNumLimit: 300,
fileSizeLimit: 200 * 1024 * 1024, // 200 M
fileSingleSizeLimit: 50 * 1024 * 1024 // 50 M
});
// 添加“添加文件”的按钮,
uploader.addButton({
id: '#filePicker2',
label: '继续添加'
});
// 当有文件添加进来时执行,负责view的创建
function addFile( file ) {
var $li = $( '
' +
'' + file.name + '
' +
'
'+
'
' +
' ' ),
$btns = $('
' +
'删除 ' +
'向右旋转 ' +
'向左旋转
').appendTo( $li ),
$prgress = $li.find('p.progress span'),
$wrap = $li.find( 'p.imgWrap' ),
$info = $('
'),
showError = function( code ) {
switch( code ) {
case 'exceed_size':
text = '文件大小超出';
break;
case 'interrupt':
text = '上传暂停';
break;
default:
text = '上传失败,请重试';
break;
}
$info.text( text ).appendTo( $li );
};
if ( file.getStatus() === 'invalid' ) {
showError( file.statusText );
} else {
// @todo lazyload
$wrap.text( '预览中' );
uploader.makeThumb( file, function( error, src ) {
if ( error ) {
$wrap.text( '不能预览' );
return;
}
var img = $('
');
$wrap.empty().append( img );
}, thumbnailWidth, thumbnailHeight );
percentages[ file.id ] = [ file.size, 0 ];
file.rotation = 0;
}
file.on('statuschange', function( cur, prev ) {
if ( prev === 'progress' ) {
$prgress.hide().width(0);
} else if ( prev === 'queued' ) {
$li.off( 'mouseenter mouseleave' );
$btns.remove();
}
// 成功
if ( cur === 'error' || cur === 'invalid' ) {
console.log( file.statusText );
showError( file.statusText );
percentages[ file.id ][ 1 ] = 1;
} else if ( cur === 'interrupt' ) {
showError( 'interrupt' );
} else if ( cur === 'queued' ) {
percentages[ file.id ][ 1 ] = 0;
} else if ( cur === 'progress' ) {
$info.remove();
$prgress.css('display', 'block');
} else if ( cur === 'complete' ) {
$li.append( '
' );
}
$li.removeClass( 'state-' + prev ).addClass( 'state-' + cur );
});
$li.on( 'mouseenter', function() {
$btns.stop().animate({height: 30});
});
$li.on( 'mouseleave', function() {
$btns.stop().animate({height: 0});
});
$btns.on( 'click', 'span', function() {
var index = $(this).index(),
deg;
switch ( index ) {
case 0:
uploader.removeFile( file );
return;
case 1:
file.rotation += 90;
break;
case 2:
file.rotation -= 90;
break;
}
if ( supportTransition ) {
deg = 'rotate(' + file.rotation + 'deg)';
$wrap.css({
'-webkit-transform': deg,
'-mos-transform': deg,
'-o-transform': deg,
'transform': deg
});
} else {
$wrap.css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ (~~((file.rotation/90)%4 + 4)%4) +')');
// use jquery animate to rotation
// $({
// rotation: rotation
// }).animate({
// rotation: file.rotation
// }, {
// easing: 'linear',
// step: function( now ) {
// now = now * Math.PI / 180;
// var cos = Math.cos( now ),
// sin = Math.sin( now );
// $wrap.css( 'filter', "progid:DXImageTransform.Microsoft.Matrix(M11=" + cos + ",M12=" + (-sin) + ",M21=" + sin + ",M22=" + cos + ",SizingMethod='auto expand')");
// }
// });
}
});
$li.appendTo( $queue );
}
// 负责view的销毁
function removeFile( file ) {
var $li = $('#'+file.id);
delete percentages[ file.id ];
updateTotalProgress();
$li.off().find('.file-panel').off().end().remove();
}
function updateTotalProgress() {
var loaded = 0,
total = 0,
spans = $progress.children(),
percent;
$.each( percentages, function( k, v ) {
total += v[ 0 ];
loaded += v[ 0 ] * v[ 1 ];
} );
percent = total ? loaded / total : 0;
spans.eq( 0 ).text( Math.round( percent * 100 ) + '%' );
spans.eq( 1 ).css( 'width', Math.round( percent * 100 ) + '%' );
updateStatus();
}
function updateStatus() {
var text = '', stats;
if ( state === 'ready' ) {
text = '选中' + fileCount + '张图片,共' +
WebUploader.formatSize( fileSize ) + '。';
} else if ( state === 'confirm' ) {
stats = uploader.getStats();
if ( stats.uploadFailNum ) {
text = '已成功上传' + stats.successNum+ '张照片至XX相册,'+
stats.uploadFailNum + '张照片上传失败,
重新上传 失败图片或
忽略 '
}
} else {
stats = uploader.getStats();
text = '共' + fileCount + '张(' +
WebUploader.formatSize( fileSize ) +
'),已上传' + stats.successNum + '张';
if ( stats.uploadFailNum ) {
text += ',失败' + stats.uploadFailNum + '张';
}
}
$info.html( text );
}
function setState( val ) {
var file, stats;
if ( val === state ) {
return;
}
$upload.removeClass( 'state-' + state );
$upload.addClass( 'state-' + val );
state = val;
switch ( state ) {
case 'pedding':
$placeHolder.removeClass( 'element-invisible' );
$queue.hide();
$statusBar.addClass( 'element-invisible' );
uploader.refresh();
break;
case 'ready':
$placeHolder.addClass( 'element-invisible' );
$( '#filePicker2' ).removeClass( 'element-invisible');
$queue.show();
$statusBar.removeClass('element-invisible');
uploader.refresh();
break;
case 'uploading':
$( '#filePicker2' ).addClass( 'element-invisible' );
$progress.show();
$upload.text( '暂停上传' );
break;
case 'paused':
$progress.show();
$upload.text( '继续上传' );
break;
case 'confirm':
$progress.hide();
$upload.text( '开始上传' ).addClass( 'disabled' );
stats = uploader.getStats();
if ( stats.successNum && !stats.uploadFailNum ) {
setState( 'finish' );
return;
}
break;
case 'finish':
stats = uploader.getStats();
if ( stats.successNum ) {
alert( '上传成功' );
} else {
// 没有成功的图片,重设
state = 'done';
location.reload();
}
break;
}
updateStatus();
}
uploader.onUploadProgress = function( file, percentage ) {
var $li = $('#'+file.id),
$percent = $li.find('.progress span');
$percent.css( 'width', percentage * 100 + '%' );
percentages[ file.id ][ 1 ] = percentage;
updateTotalProgress();
};
uploader.onFileQueued = function( file ) {
fileCount++;
fileSize += file.size;
if ( fileCount === 1 ) {
$placeHolder.addClass( 'element-invisible' );
$statusBar.show();
}
addFile( file );
setState( 'ready' );
updateTotalProgress();
};
uploader.onFileDequeued = function( file ) {
fileCount--;
fileSize -= file.size;
if ( !fileCount ) {
setState( 'pedding' );
}
removeFile( file );
updateTotalProgress();
};
uploader.on( 'all', function( type ) {
var stats;
switch( type ) {
case 'uploadFinished':
setState( 'confirm' );
break;
case 'startUpload':
setState( 'uploading' );
break;
case 'stopUpload':
setState( 'paused' );
break;
}
});
uploader.onError = function( code ) {
alert( 'Eroor: ' + code );
};
$upload.on('click', function() {
if ( $(this).hasClass( 'disabled' ) ) {
return false;
}
if ( state === 'ready' ) {
uploader.upload();
} else if ( state === 'paused' ) {
uploader.upload();
} else if ( state === 'uploading' ) {
uploader.stop();
}
});
$info.on( 'click', '.retry', function() {
uploader.retry();
} );
$info.on( 'click', '.ignore', function() {
alert( 'todo' );
} );
$upload.addClass( 'state-' + state );
updateTotalProgress();
});
});
================================================
FILE: examples/requirejs/index.html
================================================
WebUploader演示
================================================
FILE: examples/requirejs/require.js
================================================
/*
RequireJS 2.1.10 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
Available via the MIT or new BSD license.
see: http://github.com/jrburke/requirejs for details
*/
var requirejs,require,define;
(function(ca){function G(b){return"[object Function]"===N.call(b)}function H(b){return"[object Array]"===N.call(b)}function v(b,c){if(b){var d;for(d=0;d
this.depCount&&!this.defined){if(G(c)){if(this.events.error&&this.map.isDefine||h.onError!==da)try{f=i.execCb(b,c,e,f)}catch(d){a=d}else f=i.execCb(b,c,e,f);this.map.isDefine&&void 0===f&&((e=this.module)?f=e.exports:this.usingExports&&
(f=this.exports));if(a)return a.requireMap=this.map,a.requireModules=this.map.isDefine?[this.map.id]:null,a.requireType=this.map.isDefine?"define":"require",w(this.error=a)}else f=c;this.exports=f;if(this.map.isDefine&&!this.ignore&&(p[b]=f,h.onResourceLoad))h.onResourceLoad(i,this.map,this.depMaps);y(b);this.defined=!0}this.defining=!1;this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0)}}else this.fetch()}},callPlugin:function(){var a=
this.map,b=a.id,d=m(a.prefix);this.depMaps.push(d);r(d,"defined",t(this,function(f){var d,g;g=j(ba,this.map.id);var J=this.map.name,u=this.map.parentMap?this.map.parentMap.name:null,p=i.makeRequire(a.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){if(f.normalize&&(J=f.normalize(J,function(a){return c(a,u,!0)})||""),f=m(a.prefix+"!"+J,this.map.parentMap),r(f,"defined",t(this,function(a){this.init([],function(){return a},null,{enabled:!0,ignore:!0})})),g=j(k,f.id)){this.depMaps.push(f);
if(this.events.error)g.on("error",t(this,function(a){this.emit("error",a)}));g.enable()}}else g?(this.map.url=i.nameToUrl(g),this.load()):(d=t(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),d.error=t(this,function(a){this.inited=!0;this.error=a;a.requireModules=[b];B(k,function(a){0===a.map.id.indexOf(b+"_unnormalized")&&y(a.map.id)});w(a)}),d.fromText=t(this,function(f,c){var g=a.name,J=m(g),k=O;c&&(f=c);k&&(O=!1);q(J);s(l.config,b)&&(l.config[g]=l.config[b]);try{h.exec(f)}catch(j){return w(C("fromtexteval",
"fromText eval for "+b+" failed: "+j,j,[b]))}k&&(O=!0);this.depMaps.push(J);i.completeLoad(g);p([g],d)}),f.load(a.name,p,d,l))}));i.enable(d,this);this.pluginMaps[d.id]=d},enable:function(){W[this.map.id]=this;this.enabling=this.enabled=!0;v(this.depMaps,t(this,function(a,b){var c,f;if("string"===typeof a){a=m(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap);this.depMaps[b]=a;if(c=j(K,a.id)){this.depExports[b]=c(this);return}this.depCount+=1;r(a,"defined",t(this,function(a){this.defineDep(b,
a);this.check()}));this.errback&&r(a,"error",t(this,this.errback))}c=a.id;f=k[c];!s(K,c)&&(f&&!f.enabled)&&i.enable(a,this)}));B(this.pluginMaps,t(this,function(a){var b=j(k,a.id);b&&!b.enabled&&i.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){v(this.events[a],function(a){a(b)});"error"===a&&delete this.events[a]}};i={config:l,contextName:b,registry:k,defined:p,urlFetched:T,defQueue:A,Module:$,makeModuleMap:m,
nextTick:h.nextTick,onError:w,configure:function(a){a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/");var b=l.shim,c={paths:!0,bundles:!0,config:!0,map:!0};B(a,function(a,b){c[b]?(l[b]||(l[b]={}),V(l[b],a,!0,!0)):l[b]=a});a.bundles&&B(a.bundles,function(a,b){v(a,function(a){a!==b&&(ba[a]=b)})});a.shim&&(B(a.shim,function(a,c){H(a)&&(a={deps:a});if((a.exports||a.init)&&!a.exportsFn)a.exportsFn=i.makeShimExports(a);b[c]=a}),l.shim=b);a.packages&&v(a.packages,function(a){var b,
a="string"===typeof a?{name:a}:a;b=a.name;a.location&&(l.paths[b]=a.location);l.pkgs[b]=a.name+"/"+(a.main||"main").replace(ja,"").replace(R,"")});B(k,function(a,b){!a.inited&&!a.map.unnormalized&&(a.map=m(b))});if(a.deps||a.callback)i.require(a.deps||[],a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(ca,arguments));return b||a.exports&&ea(a.exports)}},makeRequire:function(a,e){function g(f,c,d){var j,l;e.enableBuildCallback&&(c&&G(c))&&(c.__requireJsBuild=
!0);if("string"===typeof f){if(G(c))return w(C("requireargs","Invalid require call"),d);if(a&&s(K,f))return K[f](k[a.id]);if(h.get)return h.get(i,f,a,g);j=m(f,a,!1,!0);j=j.id;return!s(p,j)?w(C("notloaded",'Module name "'+j+'" has not been loaded yet for context: '+b+(a?"":". Use require([])"))):p[j]}M();i.nextTick(function(){M();l=q(m(null,a));l.skipMap=e.skipMap;l.init(f,c,d,{enabled:!0});D()});return g}e=e||{};V(g,{isBrowser:z,toUrl:function(b){var e,d=b.lastIndexOf("."),g=b.split("/")[0];if(-1!==
d&&(!("."===g||".."===g)||1g.attachEvent.toString().indexOf("[native code"))&&!Z?(O=!0,g.attachEvent("onreadystatechange",b.onScriptLoad)):
(g.addEventListener("load",b.onScriptLoad,!1),g.addEventListener("error",b.onScriptError,!1)),g.src=d,M=g,D?y.insertBefore(g,D):y.appendChild(g),M=null,g;if(fa)try{importScripts(d),b.completeLoad(c)}catch(j){b.onError(C("importscripts","importScripts failed for "+c+" at "+d,j,[c]))}};z&&!r.skipDataMain&&U(document.getElementsByTagName("script"),function(b){y||(y=b.parentNode);if(L=b.getAttribute("data-main"))return q=L,r.baseUrl||(E=q.split("/"),q=E.pop(),Q=E.length?E.join("/")+"/":"./",r.baseUrl=
Q),q=q.replace(R,""),h.jsExtRegExp.test(q)&&(q=L),r.deps=r.deps?r.deps.concat(q):[q],!0});define=function(b,c,d){var g,h;"string"!==typeof b&&(d=c,c=b,b=null);H(c)||(d=c,c=null);!c&&G(d)&&(c=[],d.length&&(d.toString().replace(la,"").replace(ma,function(b,d){c.push(d)}),c=(1===d.length?["require"]:["require","exports","module"]).concat(c)));if(O){if(!(g=M))P&&"interactive"===P.readyState||U(document.getElementsByTagName("script"),function(b){if("interactive"===b.readyState)return P=b}),g=P;g&&(b||
(b=g.getAttribute("data-requiremodule")),h=F[g.getAttribute("data-requirecontext")])}(h?h.defQueue:S).push([b,c,d])};define.amd={jQuery:!0};h.exec=function(b){return eval(b)};h(r)}})(this);
================================================
FILE: flash/.actionScriptProperties
================================================
================================================
FILE: flash/.project
================================================
Uploader
com.adobe.flexbuilder.project.flexbuilder
com.adobe.flexbuilder.project.actionscriptnature
bin-debug
2
/Users/liaoxuezhi/www/webuploader/dist
bin-release
2
/Library/WebServer/www/webuploader/dist
bin-release1
2
/Users/liaoxuezhi/www/webuploader/dist
================================================
FILE: flash/.settings/org.eclipse.core.resources.prefs
================================================
#Fri Oct 25 17:23:15 CST 2013
eclipse.preferences.version=1
encoding/=utf-8
================================================
FILE: flash/Uploader.iml
================================================
================================================
FILE: flash/src/ComponentFactory.as
================================================
package
{
import com.Blob;
import com.File;
import com.FilePicker;
import com.FileReader;
import com.FileReaderSync;
import com.Image;
import com.Md5;
import com.XMLHttpRequest;
import com.errors.RuntimeError;
import flash.system.ApplicationDomain;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedSuperclassName;
public class ComponentFactory
{
FilePicker, Blob, File, FileReader, FileReaderSync, Image, XMLHttpRequest, Md5;
private var _registry:Object = {};
public function add(uid:String, comp:*) : void
{
if (_registry.hasOwnProperty(uid)) {
throw new RuntimeError(RuntimeError.COMP_CONFLICT);
}
_registry[uid] = comp;
}
public function remove(uid:String) : Boolean
{
if (!_registry.hasOwnProperty(uid)) {
return false;
}
delete _registry.uid;
return true;
}
public function get(uid:String) : *
{
return _registry.hasOwnProperty(uid) ? _registry[uid] : false;
}
public function create(uploader:Uploader, uid:String, compName:String) : *
{
var compFQName:String, compClass:Class, exType:String, comp:*;
compFQName = "com." + compName;
if (ApplicationDomain.currentDomain.hasDefinition(compFQName)) {
compClass = getDefinitionByName(compFQName) as Class;
comp = new compClass;
// if object dispatches events attach event listeners (@see for example FileInput for the interface)
if (compClass.dispatches) {
for (exType in compClass.dispatches) {
// new context required to handle this properly
(function(type:String, exType:String) : void {
comp.addEventListener(type, function(e:*) : void {
uploader.onComponentEvent(uid, e, exType);
});
}(compClass.dispatches[exType], /*compName + '::' + */exType));
}
}
// Moxie.log([uid, compName]);
// if component is descendant of the Sprite, add it to the stage
if (/Sprite$/.test(getQualifiedSuperclassName(comp))) {
uploader.addChild(comp);
}
if (_registry.hasOwnProperty(uid)) {
throw new RuntimeError(RuntimeError.COMP_CONFLICT);
}
return (_registry[uid] = comp);
} else {
throw new RuntimeError(RuntimeError.NOT_SUPPORTED_ERR);
}
}
}
}
================================================
FILE: flash/src/Uploader.as
================================================
package
{
import com.errors.RuntimeError;
import com.events.OProgressEvent;
import com.utils.Utils;
import com.utils.Zhenpin;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.external.ExternalInterface;
import flash.system.Security;
import flash.ui.ContextMenu;
import flash.ui.ContextMenuItem;
import flash.utils.getQualifiedClassName;
// import cmodule.as3_jpeg_wrapper.CLibInit;
[SWF(width='500', height='500')]
public class Uploader extends Sprite
{
public static var uid:String;
private var jsReciver:String = "Uploader.reciver";
// private static var clib:Object;
public static var compFactory:ComponentFactory;
/**
* Main constructor for the Uploader class.
*/
public function Uploader()
{
if (stage) {
_init();
} else {
addEventListener(Event.ADDED_TO_STAGE, _init);
}
}
/**
* Initialization event handler.
*
* @param e Event object.
*/
private function _init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, _init);
// Allow scripting on swf loaded from another domain
Security.allowDomain("*");
// var loader:CLibInit = new CLibInit();
// clib = loader.init();
// Align and scale stage
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.EXACT_FIT;
var menu:ContextMenu = new ContextMenu();
menu.hideBuiltInItems();
menu.customItems.push(new ContextMenuItem("webuploader v1.0"));//???preprocessor.xml, antä¼???¨æ??°æ??????
this.contextMenu = menu;
var params:Object = stage.loaderInfo.parameters;
// Setup id
Uploader.uid = Utils.sanitize(params["uid"]);
// Event dispatcher
if (params.hasOwnProperty("jsreciver") && /^[\w\.]+$/.test(params["jsreciver"])) {
jsReciver = params["jsreciver"];
}
// 整个很重要,用来增加as贞频的。
// 整个很重要,用来增加as贞频的。
try {
Zhenpin.start();
} catch (err:*) {
_fireEvent(Uploader.uid, err);
}
//ExternalInterface.marshallExceptions = true; // propagate AS exceptions to JS and vice-versa
ExternalInterface.addCallback('exec', exec);
// initialize component factory
Uploader.compFactory = new ComponentFactory;
_fireEvent(Uploader.uid + "::Ready");
}
public function exec(uid:String, compName:String, action:String, args:* = null) : *
{
// Uploader.log(arguments);
uid = Utils.sanitize(uid); // make it safe
var comp:* = Uploader.compFactory.get(uid),
ret:*;
// WebUploader.log([compName, action]);
try {
if ( action == 'destroy' ) {
if ( comp.hasOwnProperty(action) ) {
ret = comp[action].apply(comp, args as Array);
}
Uploader.compFactory.remove(uid);
// Uploader.log(['destory', compName, uid]);
return ret;
} else if (!comp) {
comp = Uploader.compFactory.create(this, uid, compName);
}
// execute the action if available
if (comp.hasOwnProperty(action)) {
// Uploader.log([uid, compName, action, args]);
ret = comp[action].apply(comp, args as Array);
// Uploader.log([uid, compName, action, args, ret]);
return ret;
}
} catch(err:*) { // re-route exceptions thrown by components (TODO: check marshallExceptions feature)
// Uploader.log([ getQualifiedClassName(err), compName, action]);
_fireEvent(uid + "::Exception", { name: getQualifiedClassName(err).replace(/^[^:*]::/, ''), code: err.errorID });
}
}
/**
* Intercept component events and do some operations if required
*
* @param uid String unique identifier of the component throwing the event
* @param e mixed Event object
* @param exType String event type in WebUploader format
*/
public function onComponentEvent(uid:String, e:*, exType:String) : void
{
var evt:Object = {};
switch (e.type)
{
case ProgressEvent.PROGRESS:
case OProgressEvent.PROGRESS:
evt.loaded = e.bytesLoaded;
evt.total = e.bytesTotal;
break;
}
evt.type = [uid, exType].join('::');
// Uploader.log([uid, exType, e.hasOwnProperty('data') ? e.data : null]);
_fireEvent(evt, e.hasOwnProperty('data') ? e.data : null);
}
// public static function encodeJpeg(ba:ByteArray, width:uint, height:uint, quality:uint=90 ):ByteArray{
// return clib.write_jpeg_file(ba, width, height, 3, 2, quality);
// }
/**
* Fires an event from the flash movie out to the page level JS.
*
* @param uid String unique identifier of the component throwing the event
* @param type Name of event to fire.
* @param obj Object with optional data.
*/
private function _fireEvent(evt:*, obj:Object = null):void {
try {
ExternalInterface.call(jsReciver, evt, obj);
} catch(err:*) {
Uploader.log(err);
//_fireEvent("Exception", { name: 'RuntimeError', message: 4 });
// throwing an exception would be better here
}
}
public static function log(obj:*) : void {
ExternalInterface.call('console.log', obj);
}
}
}
================================================
FILE: flash/src/com/Blob.as
================================================
package com
{
import com.utils.Buffer;
import flash.net.FileReference;
import flash.utils.ByteArray;
import com.utils.Utils;
public class Blob
{
private var _uid:String;
public function get uid() : String {
return _uid;
}
private var _size:Number;
public function get size() : Number {
return _size;
}
private var _type:String = '';
public function get type() : String {
if (_type !== '') {
return _type;
}
// if source is not a FileReference return default name
if (!isFileRef()) {
return _type;
}
// otherwise return original name
return ''; //_sources[0].buffer.fileRef.type;
}
// cumulative size of all the sources this blob is part of
public function get realSize() : uint {
var src:Object, size:uint = 0;
for each (src in _sources) {
size += src.buffer.size;
}
return size;
}
// cumulative size of all preloaded sources this blob is part of
public function get cachedSize() : uint {
var src:Object, size:uint = 0;
for each (src in _sources) {
if (!src.buffer.data) {
continue;
}
size += src.buffer.data.length;
}
return size;
}
public var _sources:Array = [];
protected var _pointer:Number = 0;
public function Blob(sources:Array, properties:* = null)
{
for each (var source:* in sources) {
if (source is FileReference) {
_sources.push({
buffer: new Buffer(source),
start: 0,
end: source.size
});
_pointer += source.size;
} else if (source is ByteArray) {
_sources.push({
buffer: new Buffer(source),
start: 0,
end: source.length
});
_pointer += source.length;
} else if (source is Blob) {
// increment reference counters for associated buffers
for (var i:uint = 0, max:uint = source._sources.length; i < max; i++) {
source._sources[i].buffer.refs++;
}
// simply copy over the sources
_sources.push.apply(source._sources);
_pointer += source.size;
} else if (source.hasOwnProperty('buffer') && source.buffer is Buffer) {
_sources.push({
buffer: source.buffer,
start: source.start,
end: source.end
});
_pointer += source.end - source.start;
}
}
if (properties is String) {
_type = properties;
} else if (properties is Object && properties.hasOwnProperty('type')) {
_type = properties.type;
}
_size = _pointer;
_uid = Utils.guid('uid_');
}
public function slice(... args) : Object
{
var blob:Blob = _slice.apply(null, args);
Uploader.compFactory.add(blob.uid, blob);
return blob.toObject();
}
private function _slice(... args) : Blob {
var src:Object,
start:int = args[0] || 0,
end:int = args[1] || _size,
contentType:String = args[2] || '',
size:uint, offset:uint = 0,
sources:Array = [];
if (start > end) {
return new Blob([], contentType);
}
for (var i:uint = 0, length:uint = _sources.length; i < length; i++) {
src = _sources[i];
size = src.end - src.start;
if (start > offset + size) { // start is outside of the current source's boundaries
continue;
}
// Moxie.log([src.start, src.end, start, end, size]);
sources.push({
buffer: src.buffer,
start: src.start + start - offset,
end: Math.min(src.end, end)
});
offset += size;
break;
}
if (i == length || offset > end) {
return new Blob(sources, contentType);
}
// loop for the end otherwise
for (; i < length; src = _sources[i], i++) {
offset += src.end - src.start;
if (offset < end) {
sources.push(src);
} else {
sources.push({
buffer: src.buffer,
start: src.start,
end: src.end - (offset - end)
});
break; // we have found the end
}
}
return new Blob(sources, contentType);
}
public function isEmpty() : Boolean {
return !this._sources.length;
}
public function isFileRef() : Boolean
{
return false; // Blob as a rule contains only part of the source
}
private var _isLoading:Boolean =false;
public function isLoading() : Boolean {
return _isLoading;
}
public function setLoading(val:Boolean):void {
_isLoading = val;
}
public function getFileRef() : FileReference {
if (isFileRef()) {
return _sources[0].buffer.fileRef;
}
return null;
}
public function toObject() : Object
{
return {
uid: uid,
ruid: Uploader.uid,
size: size,
type: type
};
}
public function purge() : void
{
for each (var src:Object in _sources) {
src.buffer.purge();
}
}
public function destroy() : void
{
for each (var src:Object in _sources) {
if (--src.buffer.refs <= 0) {
src.buffer.destroy();
}
}
Uploader.compFactory.remove(_uid);
}
}
}
================================================
FILE: flash/src/com/File.as
================================================
package com
{
import com.utils.Utils;
public class File extends Blob
{
private var _name:String = '';
public function get name() : String {
if (_name !== '') {
return _name;
}
// if source is not a FileReference return default name
if (!isFileRef()) {
return uid;
}
// otherwise return original name
return _sources[0].buffer.fileRef.name;
}
private var _lastModifiedDate:Date;
public function get lastModifiedDate() : Date {
if (!isFileRef()) {
return new Date();
}
return _sources[0].buffer.fileRef.modificationDate;
}
public function File(sources:Array, properties:* = null)
{
if (properties is Object && properties.hasOwnProperty('name')) {
_name = properties.name;
}
super(sources, properties);
}
public override function isFileRef() : Boolean
{
return !!(_sources.length === 1 && _sources[0].buffer.fileRef);
}
public override function toObject() : Object
{
return Utils.extend(super.toObject(), {
name: name,
lastModifiedDate: lastModifiedDate
});
}
}
}
================================================
FILE: flash/src/com/FilePicker.as
================================================
package com
{
import com.events.FilePickerEvent;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.net.FileFilter;
import flash.net.FileReference;
import flash.net.FileReferenceList;
import com.utils.Utils;
public class FilePicker extends Sprite
{
public static var dispatches:Object = { // hash of events dispatched by this class
"Cancel": FilePickerEvent.CANCEL,
"Change": FilePickerEvent.SELECT,
"DialogOpen": FilePickerEvent.OPEN,
"MouseEnter": MouseEvent.ROLL_OVER,
"MouseLeave": MouseEvent.ROLL_OUT,
"MouseDown": MouseEvent.MOUSE_DOWN,
"MouseUp": MouseEvent.MOUSE_UP
};
public static var stageOccupied:Boolean = false;
protected var _options:Object = {};
protected var _disabled:Boolean = false;
protected var _filters:Array = null;
protected var _picker:*;
protected var _button:Sprite;
protected var _files:Array = [];
public function init(options:Object = null) : void {
_options = Utils.extend({
name: 'Filedata',
multiple: false,
accept: null
}, options);
if (_options.accept !== null) {
_filters = [];
for (var i:int = 0; i < _options.accept.length; i++) {
_filters.push(new FileFilter(
_options.accept[i].title,
'*.' + _options.accept[i].extensions.replace(/,/g, ";*.")
));
}
}
_button = new Sprite;
_button.graphics.beginFill(0x000000, 0); // Fill with transparent color
_button.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
_button.graphics.endFill();
_button.buttonMode = true;
_button.useHandCursor = true;
_button.addEventListener(MouseEvent.CLICK, onClick);
_button.addEventListener(MouseEvent.ROLL_OVER, onEvent);
_button.addEventListener(MouseEvent.ROLL_OUT, onEvent);
_button.addEventListener(MouseEvent.MOUSE_DOWN, onEvent);
_button.addEventListener(MouseEvent.MOUSE_UP, onEvent);
addChild(_button);
}
public function disable(disabled:Boolean = true) : void {
_disabled = disabled;
_button.useHandCursor = !disabled;
}
public function destroy() : void {
}
private function onEvent(e:MouseEvent) : void {
e.stopPropagation();
if (_disabled) {
return;
}
dispatchEvent(e);
}
private function onClick(e:MouseEvent) : void {
if (_disabled) {
return;
}
_picker = _options.multiple ? new FileReferenceList : new FileReference;
_picker.addEventListener(Event.CANCEL, onDialogEvent);
_picker.addEventListener(Event.SELECT, onDialogEvent);
_picker.browse(_filters);
dispatchEvent(new FilePickerEvent(FilePickerEvent.OPEN));
}
public function getFiles() : Array {
var files:Array = [];
for each (var file:File in _files) {
Uploader.compFactory.add(file.uid, file);
files.push(file.toObject());
}
return files;
}
private function onDialogEvent(e:Event) : void {
_picker.removeEventListener(Event.CANCEL, onDialogEvent);
_picker.removeEventListener(Event.SELECT, onDialogEvent);
switch (e.type) {
case Event.CANCEL:
dispatchEvent(new FilePickerEvent(FilePickerEvent.CANCEL));
break;
case Event.SELECT:
var fileRefList:Array = [];
if (!_options.multiple) {
fileRefList.push(_picker);
} else {
fileRefList = _picker.fileList;
}
_files = [];
for (var i:uint = 0; i < fileRefList.length; i++) {
_files.push(new File([fileRefList[i]]));
}
dispatchEvent(new FilePickerEvent(FilePickerEvent.SELECT));
break;
}
}
}
}
================================================
FILE: flash/src/com/FileReader.as
================================================
package com
{
import com.errors.DOMError;
import com.events.OErrorEvent;
import com.events.OProgressEvent;
import com.utils.Base64;
import com.utils.Buffer;
import com.utils.OEventDispatcher;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.net.FileReference;
import flash.utils.ByteArray;
public class FileReader extends OEventDispatcher
{
// events dispatched by this class
public static var dispatches:Object = {
"LoadStart": Event.OPEN,
"Progress": OProgressEvent.PROGRESS,
"Load": Event.COMPLETE,
"Error": OErrorEvent.ERROR
};
public static const EMPTY:int = 0;
public static const LOADING:int = 1;
public static const DONE:int = 2;
public var readyState:int = FileReader.EMPTY;
public var result:*;
private var _blob:*;
private var _index:int = 0;
private var _position:int = 0;
private var _src:Object;
private var _sizeRatio:Number = 1;
private var _notCachedSize:uint = 0;
private var _op:String;
private var _ba:ByteArray = new ByteArray;
private var _str:String;
public function readAsByteArray(blob:*) : void {
_op = "asByteArray";
_read(blob);
}
public function readAsBase64(blob:*) : void {
_str = '';
_op = "asBase64";
_read(blob);
}
public function abort() : void {
if (this.readyState !== FileReader.LOADING) {
return;
}
if (_src && _src.buffer.fileRef) {
_src.buffer.fileRef.cancel();
_removeAllEventListeners(_src.dataObject.fileRef);
}
clear();
this.readyState = FileReader.DONE;
}
public function clear() : void {
if (this.result is ByteArray) {
this.result.clear();
} else if (this.result is String) {
this.result = '';
}
this.result = null;
}
private function _read(blob:*) : void {
if (typeof blob === 'string') {
blob = Uploader.compFactory.get(blob);
}
if (!blob || !(blob is Blob) || blob.isEmpty()) {
dispatchEvent(new OErrorEvent(OErrorEvent.ERROR, DOMError.NOT_FOUND_ERR));
return;
}
if (this.readyState === FileReader.LOADING) {
dispatchEvent(new OErrorEvent(OErrorEvent.ERROR, DOMError.SECURITY_ERR)); // should be invalid state
return;
}
_blob = blob;
_sizeRatio = _blob.size / _blob.realSize;
_notCachedSize = _blob.realSize - _blob.cachedSize;
this.readyState = FileReader.LOADING;
dispatchEvent(new Event(Event.OPEN));
_ba.clear();
_index = 0;
_src = blob._sources[_index++];
// this will run recursively until all DataSources are read and concatenated into _ba
_loadSource();
}
private function _loadSource() : void {
var buffer:Buffer = _src.buffer;
if (this.readyState != FileReader.LOADING) { // it might have been aborted by now
return;
}
if (buffer.data && buffer.data.length) {
onComplete({ // mimic event object structure
type: Event.COMPLETE,
target: {
data: buffer.data
}
});
} else if (buffer.fileRef) {
_blob.setLoading(true);
buffer.fileRef.addEventListener(ProgressEvent.PROGRESS, onProgress);
buffer.fileRef.addEventListener(Event.COMPLETE, onComplete);
buffer.fileRef.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
buffer.fileRef.load();
} else {
onIOError({
type: IOErrorEvent.IO_ERROR,
target: {}
});
}
}
private function onProgress(e:ProgressEvent) : void {
var bytesLoaded:*;
e.stopPropagation();
// hold the value within the size of the blob
bytesLoaded = Math.floor((e.bytesLoaded + _position) * _sizeRatio);
// Moxie.log([bytesLoaded, _blob.size]);
dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS, false, false, bytesLoaded, _blob.size));
}
private function onIOError(e:*) : void {
this.readyState = FileReader.DONE;
clear();
_removeAllEventListeners(e.target);
dispatchEvent(new OErrorEvent(OErrorEvent.ERROR, DOMError.NOT_READABLE_ERR));
}
private function onComplete(e:*) : void {
var length:Number, data:ByteArray;
this.readyState = FileReader.DONE;
if (e.target is FileReference) { // this func might be called directly
_removeAllEventListeners(e.target);
}
length = _src.end - _src.start;
data = e.target.data;
data.position = _src.start;
data.readBytes(_ba, 0, length);
_position += length;
_index++;
if (_blob._sources[_index]) {
_src = _blob._sources[_index];
_loadSource();
} else if (_position === _blob.size) {
_finalize(); // we've reached the end, send the blob data out
}
}
private function _removeAllEventListeners(target:*) : void {
_blob.setLoading(false);
target.removeEventListener(ProgressEvent.PROGRESS, onProgress);
target.removeEventListener(Event.COMPLETE, onComplete);
target.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
}
private function _finalize() : void {
switch (_op) {
case 'asByteArray':
this.result = _ba;
_ba = null;
break;
case 'asBase64':
_toBase64();
this.result = _str;
_ba.clear(); // we won't be needing this one in this case anymore
_str = null;
break;
}
dispatchEvent(new Event(Event.COMPLETE));
}
private function _toBase64() : void {
var base64:String, chunk_size:uint, chunk:ByteArray, length:uint, loaded:uint;
// by this moment _ba should be populated with binary data
if (!_ba.length) {
return;
}
chunk_size = 204798; // bytes, should divide by three
chunk = new ByteArray;
length = _ba.length;
loaded = 0;
_ba.position = 0;
while (_ba.bytesAvailable > 0) {
if (chunk_size > _ba.bytesAvailable) {
chunk_size = _ba.bytesAvailable; // last chunk might be small
}
_ba.readBytes(chunk, 0, chunk_size);
loaded += chunk_size;
base64 = Base64.encode(chunk);
_str += base64;
chunk.clear();
dispatchEvent(new OProgressEvent(OProgressEvent.PROGRESS, (loaded < length ? loaded : length), length, base64));
}
}
}
}
================================================
FILE: flash/src/com/FileReaderSync.as
================================================
package com
{
import com.errors.DOMError;
import com.utils.Base64;
import flash.utils.ByteArray;
public class FileReaderSync
{
public function readAsBase64(blob:*) : String {
var ba:ByteArray = _read(blob);
return Base64.encode(ba);
}
private function _read(blob:*) : ByteArray {
var src:Object,
ba:ByteArray = new ByteArray;
if (typeof blob === 'string') {
blob = Uploader.compFactory.get(blob);
}
if (!blob || !(blob is Blob) || blob.isEmpty()) {
throw new DOMError(DOMError.NOT_FOUND_ERR);
}
for each (src in blob._sources) {
if (src.buffer.isEmpty()) {
break;
}
src.buffer.data.position = src.start;
src.buffer.data.readBytes(ba, 0, src.end - src.start);
}
return ba;
}
}
}
================================================
FILE: flash/src/com/Image.as
================================================
package com
{
import com.errors.ImageError;
import com.events.ODataEvent;
import com.events.OErrorEvent;
import com.events.OProgressEvent;
import com.image.BMP;
import com.image.GIF;
import com.image.ImageEditor;
import com.image.JPEG;
import com.image.JPEGEncoder;
import com.image.PNG;
import com.utils.BMPDecoder;
import com.utils.Base64;
import com.utils.OEventDispatcher;
import com.utils.Utils;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.IBitmapDrawable;
import flash.display.Loader;
import flash.display.PNGEncoderOptions;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.geom.Matrix;
import flash.system.System;
import flash.utils.ByteArray;
import flash.geom.Rectangle;
import flash.geom.Point;
public class Image extends OEventDispatcher
{
// events dispatched by this class
public static var dispatches:Object = {
"Progress": OProgressEvent.PROGRESS,
"Complete": ODataEvent.DATA,
"Load": Event.COMPLETE,
"Error": OErrorEvent.ERROR
};
private var _orientation:uint = 1;
private var _bd:BitmapData;
private var _ba:ByteArray;
private var _meta:Object;
private var _info:Object;
private var _img:*;
public var type:String = 'image/jpeg';
public var quality:uint = 70;
public var _crop:Boolean = true;
public var allowMagnify:Boolean = true;
public var preserveHeaders:Boolean = false;
public function init( options:Object = null ):void {
Utils.extend(this, options, true);
if (options.hasOwnProperty("crop")){
_crop = options["crop"];
}
}
public function loadFromBlob( blob:* = null ):void {
var fr:FileReader;
if (typeof blob === 'string') {
blob = Uploader.compFactory.get(blob);
}
if (!blob) {
dispatchEvent(new OErrorEvent(OErrorEvent.ERROR, ImageError.WRONG_FORMAT));
return;
}
fr = new FileReader;
fr.addEventListener(ProgressEvent.PROGRESS, function(e:ProgressEvent) : void {
dispatchEvent(new OProgressEvent(OProgressEvent.PROGRESS, e.bytesLoaded, e.bytesTotal));
});
fr.addEventListener(Event.COMPLETE, function(e:Event) : void {
fr.removeAllEventsListeners();
_loadFromByteArray(fr.result);
dispatchEvent( new Event(Event.COMPLETE) );
});
fr.readAsByteArray(blob);
}
public function info( val:Object = null):Object {
if ( val ) {
_info = val;
}
return _info;
}
public function meta( val:Object = null):Object {
if ( val ) {
_meta = val;
}
return _meta;
}
private function _loadFromByteArray( ba:ByteArray ):void {
if ( !_info ) {
if (JPEG.test(ba)) {
_img = new JPEG(ba);
_meta = _img.metaInfo();
_img.extractHeaders();
} else if (PNG.test(ba)) {
_img = new PNG(ba);
} else if ( GIF.test(ba) ) {
_img = new GIF( ba );
} else if ( BMP.test(ba) ) {
_img = new BMP( ba );
} else {
dispatchEvent(new OErrorEvent(OErrorEvent.ERROR, ImageError.WRONG_FORMAT));
return;
}
_info = _img.info();
} else if ( _info.type === 'image/jpeg' ) {
_img = new JPEG( ba );
_img.extractHeaders();
}
type = _info.type;
_ba = ba;
}
public function resize( width:Number = 110, height:Number = 110 ):void {
var naturalWidth:uint, naturalHeight:uint;
type = _info.type;
naturalWidth = _info.width;
naturalHeight = _info.height;
// take into account Orientation tag
if (type == 'image/jpeg' && _meta.hasOwnProperty('tiff') && _meta.tiff.hasOwnProperty('Orientation')) {
_orientation = parseInt(_meta.tiff.Orientation, 10);
}
if ([5,6,7,8].indexOf(_orientation) !== -1) { // values that have different orientation
// 交互宽度和高度值
width ^= height;
height ^= width;
width ^= height;
}
var selector:Function, scale:Number;
selector = _crop ? Math.max : Math.min;
scale = selector( width / naturalWidth, height / naturalHeight );
if ( !allowMagnify && scale > 1 ) {
scale = 1;
}
var destWidth:uint, destHeight:uint;
destWidth = naturalWidth * scale;
destHeight = naturalHeight * scale;
var matrix:Matrix = new Matrix;
matrix.scale( scale, scale );
if ( destWidth > width ) {
matrix.translate(-Math.round((destWidth - width) / 2), 0);
}
if ( destHeight > height ) {
matrix.translate( 0, -Math.round(( destHeight - height) / 2));
}
_bd = new BitmapData( Math.min( width, destWidth), Math.min( height, destHeight) );
if ( type == 'image/bmp' ) {
var decoder:BMPDecoder = new BMPDecoder();
var bmp:Bitmap = new Bitmap( decoder.decode( _ba ) );
// draw preloaded data onto the prepared BitmapData
_bd.draw(bmp, matrix, null, null, null, true);
dispatchEvent(new ODataEvent(ODataEvent.DATA));
return;
}
var loader:Loader = new Loader;
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event) : void {
loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, arguments.callee);
// draw preloaded data onto the prepared BitmapData
_bd.draw(e.target.content as IBitmapDrawable, matrix, null, null, null, true);
loader.unload();
_ba.clear();
dispatchEvent(new ODataEvent(ODataEvent.DATA));
});
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function(e:*) : void {
dispatchEvent(new OErrorEvent(OErrorEvent.ERROR, 2));
_ba.clear();
_bd.dispose();
loader.unload();
});
try {
loader.loadBytes(_ba);
} catch (ex:*) {
Uploader.log([ex]);
}
}
public function crop( x:Number = 0, y:Number = 0, width:Number = 110, height:Number = 110, scale:Number = 1 ):void {
var croppedBD:BitmapData = new BitmapData(width, height);
croppedBD.copyPixels(_bd, new Rectangle(x, y, width, height), new Point(0, 0));
_bd.dispose();
_bd = croppedBD
}
public function getAsDataUrl( _type:String = null):String {
_type = _type || type;
var ba:ByteArray = _encodeBitmapData( _bd, _type );
return 'data:' + _type + ';base64,' + Base64.encode( ba );
}
public function getAsBlob( _type:String = null):Object {
_type = _type || type;
var blob:Blob = new Blob([_encodeBitmapData( _bd, _type )], { type: _type });
Uploader.compFactory.add(blob.uid, blob);
return blob.toObject();
}
public function destroy():void {
if (_bd) {
_bd.dispose();
_bd = null;
}
// one call to mark any dereferenced objects and sweep away old marks,
flash.system.System.gc();
// ...and the second to now sweep away marks from the first call.
flash.system.System.gc();
}
private function _encodeBitmapData( bd:BitmapData, type:String ):ByteArray {
var encoder:JPEGEncoder, ba:ByteArray;
// todo 支持其他格式。
if ( type === 'image/png' ) {
ba = bd.encode(bd.rect, new PNGEncoderOptions());
} else {
if (type == 'image/jpeg' && !preserveHeaders ) {
bd = _rotateToOrientation(_orientation, bd);
}
encoder = new JPEGEncoder( quality );
ba = encoder.encode(bd);
if (_img && _img is JPEG) {
// strip off any headers that might be left by encoder, etc
_img.stripHeaders(ba);
// restore the original headers if requested
if (preserveHeaders) {
_img.insertHeaders(ba);
_img.updateDimensions(bd.width, bd.height);
}
}
}
return ba;
}
private function _rotateToOrientation(orientation:uint, bd:BitmapData) : BitmapData
{
var imageEditor:ImageEditor = new ImageEditor(bd);
switch (orientation) {
case 2:
// horizontal flip
imageEditor.modify("flipH");
break;
case 3:
// 180 rotate left
imageEditor.modify("rotate", 180);
break;
case 4:
// vertical flip
imageEditor.modify("flipV");
break;
case 5:
// vertical flip + 90 rotate right
imageEditor.modify("flipV");
imageEditor.modify("rotate", 90);
break;
case 6:
// 90 rotate right
imageEditor.modify("rotate", 90);
break;
case 7:
// horizontal flip + 90 rotate right
imageEditor.modify("flipH");
imageEditor.modify("rotate", 90);
break;
case 8:
// 90 rotate left
imageEditor.modify("rotate", -90);
break;
}
imageEditor.commit();
bd.dispose();
_bd = imageEditor.bitmapData;
imageEditor.purge();
return _bd;
}
}
}
================================================
FILE: flash/src/com/Md5.as
================================================
package com
{
import com.errors.ImageError;
import com.events.ODataEvent;
import com.events.OErrorEvent;
import com.events.OProgressEvent;
import com.utils.OEventDispatcher;
import com.utils.Utils;
import flash.events.Event;
import flash.events.ProgressEvent;
import flash.system.System;
import flash.utils.ByteArray;
import cmodule.stringecho.CLibInit;
public class Md5 extends OEventDispatcher
{
// events dispatched by this class
public static var dispatches:Object = {
"Progress": OProgressEvent.PROGRESS,
"Complete": ODataEvent.DATA,
"Load": Event.COMPLETE,
"Error": OErrorEvent.ERROR
};
private static var ci:Object;
private var ret:String;
public function init( options:Object = null ):void {
Utils.extend(this, options, true);
}
public function loadFromBlob( blob:* = null ):void {
var fr:FileReader;
if (typeof blob === 'string') {
blob = Uploader.compFactory.get(blob);
}
if (!blob) {
dispatchEvent(new OErrorEvent(OErrorEvent.ERROR, ImageError.WRONG_FORMAT));
return;
}
fr = new FileReader;
fr.addEventListener(ProgressEvent.PROGRESS, function(e:ProgressEvent) : void {
dispatchEvent(new OProgressEvent(OProgressEvent.PROGRESS, e.bytesLoaded, e.bytesTotal));
});
fr.addEventListener(Event.COMPLETE, function(e:Event) : void {
fr.removeAllEventsListeners();
dispatchEvent(new Event(Event.COMPLETE));
_loadFromByteArray(fr.result);
dispatchEvent(new Event(ODataEvent.DATA));
});
fr.readAsByteArray(blob);
}
public function getResult():String {
return ret;
}
private function _loadFromByteArray( ba:ByteArray ):void {
if (!ci) {
ci = new CLibInit().init();
}
ret = ci.md5BytesMethod(ba);
}
public function destroy():void {
// one call to mark any dereferenced objects and sweep away old marks,
flash.system.System.gc();
// ...and the second to now sweep away marks from the first call.
flash.system.System.gc();
}
}
}
================================================
FILE: flash/src/com/XMLHttpRequest.as
================================================
package com
{
import com.adobe.serialization.json.JSON;
import com.errors.RuntimeError;
import com.events.OErrorEvent;
import com.events.OProgressEvent;
import com.utils.Buffer;
import com.utils.URLStreamProgress;
import com.utils.Utils;
import flash.events.DataEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.FileReference;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLRequestMethod;
import flash.net.URLStream;
import flash.utils.ByteArray;
import flash.utils.clearTimeout;
import flash.utils.setTimeout;
public class XMLHttpRequest extends EventDispatcher
{
// events dispatched by this class
public static var dispatches:Object = {
"LoadStart": Event.OPEN,
"Progress": OProgressEvent.PROGRESS,
"UploadProgress": ProgressEvent.PROGRESS,
"Load": Event.COMPLETE,
"Error": OErrorEvent.ERROR
};
public static const UNSENT:uint = 0;
public static const OPENED:uint = 1;
public static const HEADERS_RECEIVED:uint = 2;
public static const LOADING:uint = 3;
public static const DONE:uint = 4;
public static const ABORTED:uint = 5;
private var _methods:Object = {
'GET': URLRequestMethod.GET,
'POST': URLRequestMethod.POST
};
private var _options:Object;
private var _multipart:Boolean = false;
private var _headers:Object = {};
private var _blob:*;
private var _blobName:String;
private var _blobFieldName:String = 'Filedata';
private var _postData:Array = [];
private var _conn:*;
private var _response:ByteArray;
private var _status:int;
private var _readyState:uint = XMLHttpRequest.UNSENT;
private var _onCompleteTimeout:uint = 0;
private var _notCachedSize:uint = 0;
public function append(name:String, value:*) : void
{
_multipart = true;
if (name == 'Filename') { // Flash will add this by itself, so we need to omit potential duplicate
return;
}
_postData.push([name, value]);
}
public function appendBlob(name:String, blob:*, fileName:String = null) : void
{
_multipart = true;
_blobName = fileName || 'blob' + new Date().getTime();
if (typeof blob === 'string') {
blob = Uploader.compFactory.get(blob);
if (!fileName && blob is File && blob.hasOwnProperty('name')) {
_blobName = blob.name;
}
}
_blob = blob;
_blobFieldName = name;
}
public function setRequestHeader(name:String, value:String) : void
{
_headers[name] = value;
}
public function send(meta:Object, blob:* = null) : void
{
if (_blob) {
blob = _blob;
}
meta.method = meta.method.toUpperCase();
_options = meta;
if (typeof blob === 'string') {
blob = Uploader.compFactory.get(blob);
if (blob is File && blob.hasOwnProperty('name')) {
_blobName = blob.name;
}
}
// Uploader.log(["forceUrlStream is : ", _options.forceURLStream]);
if (blob && _options.method == 'POST') {
if (_multipart && blob.isFileRef() && Utils.isEmptyObj(_headers) && (!meta.hasOwnProperty("forceURLStream") || !meta.forceURLStream)) {
_uploadFileRef(blob);
} else {
_preloadBlob(blob, _doURLStreamRequest);
}
} else {
_doURLStreamRequest();
}
}
public function getResponseAsBlob() : Object
{
var blob:Blob;
if (!_response) {
return null;
}
blob = new File([_response], { name: _options.url.replace(/^.+?\/([\w\-\.]+)$/, '$1').toLowerCase() });
Uploader.compFactory.add(blob.uid, blob);
return blob.toObject();
}
public function _getResponse():String {
var ret:String;
if ( !_response ) {
return '';
}
_response.position = 0;
ret = _response.readUTFBytes(_response.length);
return ret;
}
public function getResponse():String {
return encodeURIComponent(_getResponse());
}
public function getResponseAsJson() : Object
{
var ret:Object;
try {
var str:String = _getResponse();
if (!str || !str.match(/^\s*{/)) {
return {};
}
ret = com.adobe.serialization.json.JSON.decode(str);
} catch( e:Error ) {
ret = {};
}
return ret;
}
public function getStatus() : int
{
return _status;
}
public function abort() : void
{
// mark as aborted in order to be handled as soon as possible
_readyState = XMLHttpRequest.ABORTED;
if (_conn is FileReference) {
_conn.cancel();
} else if (_conn is URLStream && _conn.connected) {
_conn.close();
}
removeEventListeners(_conn);
_conn = null;
}
private function onOpen() : void {
dispatchEvent(new Event(Event.OPEN));
}
private function onProgress(e:ProgressEvent) : void {
dispatchEvent(new OProgressEvent(OProgressEvent.PROGRESS, e.bytesLoaded, e.bytesTotal));
}
private function onUploadProgress(e:ProgressEvent):void {
dispatchEvent(e);
}
private function onUploadComplete(e:*) : void {
if (_onCompleteTimeout) {
clearTimeout(_onCompleteTimeout);
}
// if status still equal to zero, than we are ok
if (_status == 0) {
_status = 200;
}
// save response
_response = new ByteArray;
if (_conn is FileReference && e.hasOwnProperty('data')) {
_response.writeUTFBytes(e.data);
} else if (_conn is URLStream) {
_conn.readBytes(_response);
}
// Uploader.log(["here", getResponse()]);
removeEventListeners(e.target);
_readyState = XMLHttpRequest.DONE;
dispatchEvent(new Event(Event.COMPLETE));
}
private function onComplete(e:*) : void {
// give upload complete event a chance to fire
_onCompleteTimeout = setTimeout(onUploadComplete, 500, e);
}
// The httpStatus event is dispatched only for upload failures.
private function onStatus(e:HTTPStatusEvent) : void {
_status = e.status;
}
private function onIOError(e:IOErrorEvent) : void {
if (_status == 0) { // httpStatus might have already set status to some failure code (according to livedocs)
_status = 404; // assume that request succeeded, but url was wrong
}
onUploadComplete(e);
}
private function onError(e:*) : void {
removeEventListeners(e.target);
_readyState = XMLHttpRequest.DONE;
dispatchEvent(new OErrorEvent(OErrorEvent.ERROR));
}
private function removeEventListeners(target:*) : void {
// some of these event handlers may not even be attached, but we try to remove them all for simplicity
target.removeEventListener(Event.OPEN, onOpen);
target.removeEventListener(ProgressEvent.PROGRESS, onProgress);
target.removeEventListener(ProgressEvent.PROGRESS, onUploadProgress);
target.removeEventListener(Event.COMPLETE, onComplete);
target.removeEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onUploadComplete);
target.removeEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
target.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
target.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
}
private function _uploadFileRef(blob:Blob) : void
{
var request:URLRequest, queryString:Array = [], param:Array;
request = new URLRequest();
request.method = URLRequestMethod.POST;
request.url = _options.url;
for each (param in _postData) {
queryString.push(encodeURIComponent(param[0]) + '=' + encodeURIComponent(param[1]));
}
request.data = queryString.join('&');
_conn = blob.getFileRef();
_readyState = XMLHttpRequest.OPENED;
if (blob.isLoading()) {
_conn.addEventListener(Event.COMPLETE, function( e:Event = null ):void {
_conn.removeEventListener(Event.COMPLETE, arguments.callee);
doUpload();
});
} else {
doUpload();
}
function doUpload():void {
_conn.addEventListener(Event.COMPLETE, onComplete);
_conn.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onUploadComplete);
_conn.addEventListener(ProgressEvent.PROGRESS, onUploadProgress);
_conn.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
_conn.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
_conn.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
// _conn.addEventListener(Event.OPEN, onOpen); doesn't fire, ideas?
onOpen(); // trigger it manually
_readyState = XMLHttpRequest.LOADING;
_conn.upload(request, _blobFieldName, false);
}
}
private function _preloadBlob(blob:*, callback:Function) : void
{
var fr:FileReader = new FileReader;
fr.addEventListener(Event.OPEN, function(e:Event) : void {
if (_readyState == XMLHttpRequest.ABORTED) {
fr.abort();
}
});
fr.addEventListener(ProgressEvent.PROGRESS, function(e:ProgressEvent) : void {
if (_readyState == XMLHttpRequest.ABORTED) {
fr.abort();
}
});
fr.addEventListener(Event.COMPLETE, function() : void {
fr.removeAllEventsListeners();
if (_readyState == XMLHttpRequest.ABORTED) {
fr.abort();
} else {
callback(fr.result);
}
});
//_notCachedSize = blob.realSize - blob.cachedSize;
_readyState = XMLHttpRequest.OPENED;
onOpen(); // trigger it manually
fr.readAsByteArray(blob);
}
private function _doURLStreamRequest(ba:ByteArray = null) : void
{
if (_readyState == XMLHttpRequest.ABORTED) {
return;
}
var request:URLRequest,
progress:URLStreamProgress,
start:Date, end:Date; // we are going to measure upload time for each piece of data and make correction to the progress watch
request = new URLRequest(_options.url);
// set custom headers if required
if (!Utils.isEmptyObj(_headers)) {
for (var name:String in _headers) {
request.requestHeaders.push(new URLRequestHeader(name, _headers[name]));
}
}
// only GET/POST is supported at the moment
if (['POST', 'GET'].indexOf(_options.method) === -1) {
dispatchEvent(new OErrorEvent(OErrorEvent.ERROR, RuntimeError.SYNTAX_ERR));
return;
}
request.method = _methods[_options.method];
if (_multipart) {
request.data = _formatAsMultipart(ba, request);
} else if (ba) {
// set content-type manually
if (!_headers['content-type']) { // if it wasn't already set above
request.requestHeaders.push(new URLRequestHeader("content-type", _options.mimeType));
}
request.data = ba;
}
_conn = new URLStream;
_conn.addEventListener(ProgressEvent.PROGRESS, onProgress);
_conn.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
_conn.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
_conn.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
if (ba) {
progress = new URLStreamProgress({ url: _options.url });
progress.addEventListener(ProgressEvent.PROGRESS, function( e:ProgressEvent ):void{
if ( _readyState == XMLHttpRequest.ABORTED ) {
progress.stop();
progress.removeAllEventsListeners();
} else {
onUploadProgress(e);
}
});
progress.addEventListener(Event.OPEN, function() : void {
start = new Date;
_conn.load(request);
});
_conn.addEventListener(Event.COMPLETE, function(e:Event) : void {
progress.stop();
progress.removeAllEventsListeners();
// correlate upload speed
end = new Date;
URLStreamProgress.calculateSpeed(request.data.length, end.time - start.time);
onComplete(e);
});
progress.start(request.data.length);
}
else {
_conn.addEventListener(Event.COMPLETE, onComplete);
onOpen(); // trigger it manually
_conn.load(request);
}
_readyState = XMLHttpRequest.LOADING;
}
private function _formatAsMultipart(ba:ByteArray, request:URLRequest) : ByteArray
{
var boundary:String = '----webuploaderboundary' + new Date().getTime(),
dashdash:String = '--', crlf:String = '\r\n',
tmpBa:ByteArray, param:Array;
tmpBa = new ByteArray;
request.requestHeaders.push(new URLRequestHeader("Content-Type", 'multipart/form-data; boundary=' + boundary));
for each (param in _postData) {
tmpBa.writeUTFBytes(
dashdash + boundary + crlf +
'Content-Disposition: form-data; name="' + param[0] + '"' + crlf + crlf +
param[1] + crlf
);
}
// append file if available
if (ba) {
tmpBa.writeUTFBytes(
dashdash + boundary + crlf +
'Content-Disposition: form-data; name="' + _blobFieldName + '"; filename="' + _blobName + '"' + crlf +
'Content-Type: ' + _options.mimeType + crlf + crlf
);
tmpBa.writeBytes(ba, 0, ba.length);
ba.clear();
tmpBa.writeUTFBytes(crlf);
}
// wrap it up
tmpBa.writeUTFBytes(dashdash + boundary + dashdash + crlf);
return tmpBa;
}
}
}
================================================
FILE: flash/src/com/errors/DOMError.as
================================================
package com.errors
{
public class DOMError extends Error
{
public static const NOT_FOUND_ERR:uint = 1;
public static const SECURITY_ERR:uint = 2;
public static const ABORT_ERR:uint = 3;
public static const NOT_READABLE_ERR:uint = 4;
public static const ENCODING_ERR:uint = 5;
public function DOMError(id:int = 0) {
super("", id);
}
}
}
================================================
FILE: flash/src/com/errors/ImageError.as
================================================
package com.errors
{
public class ImageError
{
public static const WRONG_FORMAT:uint = 0;
public static const OUT_OF_DIMENSIONS:uint = 1;
}
}
================================================
FILE: flash/src/com/errors/RuntimeError.as
================================================
package com.errors
{
public class RuntimeError extends Error
{
public static const NOT_INIT_ERR:uint = 1;
public static const NOT_SUPPORTED_ERR:uint = 9;
public static const JS_ERR:uint = 4;
public static const OUT_OF_MEMORY:uint = 5;
public static const INVALID_STATE_ERR:uint = 11;
public static const SYNTAX_ERR:uint = 12;
public static const COMP_CONFLICT:uint = 23;
public function RuntimeError(id:* = 0) {
super("", id);
}
}
}
================================================
FILE: flash/src/com/events/FilePickerEvent.as
================================================
package com.events
{
import flash.events.Event;
public class FilePickerEvent extends Event
{
public static const SELECT:String = 'filepickerselect';
public static const CANCEL:String = 'filepickercancel';
public static const OPEN:String = 'filepickeropen';
public var data:*;
public function FilePickerEvent(type:String, data:* = false)
{
this.data = data;
super(type, false, false);
}
}
}
================================================
FILE: flash/src/com/events/ImageEvent.as
================================================
package com.events
{
import flash.events.Event;
public class ImageEvent extends Event
{
public static const RESIZE:String = 'imageresize';
public var data:*;
public function ImageEvent(type:String, data:* = null)
{
this.data = data;
super(type, bubbles, cancelable);
}
public override function clone() : Event {
return new ImageEvent(type, data);
}
}
}
================================================
FILE: flash/src/com/events/ODataEvent.as
================================================
package com.events
{
import flash.events.Event;
public class ODataEvent extends Event
{
public static const DATA:String = 'webuploaderdata';
public var data:*;
public function ODataEvent(type:String, data:* = null)
{
this.data = data;
super(type, bubbles, cancelable);
}
public override function clone() : Event {
return new ODataEvent(type, data);
}
}
}
================================================
FILE: flash/src/com/events/OErrorEvent.as
================================================
package com.events
{
import flash.events.Event;
public class OErrorEvent extends Event
{
public static const ERROR:String = 'moxieerror';
public var code:uint;
public function OErrorEvent(type:String, code:int = 0) {
this.code = code;
super(type, true, false);
}
public override function clone() : Event {
return new OErrorEvent(type, code);
}
}
}
================================================
FILE: flash/src/com/events/OProgressEvent.as
================================================
package com.events
{
import flash.events.Event;
import flash.events.ProgressEvent;
public class OProgressEvent extends ProgressEvent
{
public static const PROGRESS:String = 'webuploaderprogress';
public var data:*;
public function OProgressEvent(type:String, bytesLoaded:uint = 0, bytesTotal:uint = 0, data:* = null)
{
this.data = data;
super(type, true, false, bytesLoaded, bytesTotal);
}
public override function clone() : Event {
return new OProgressEvent(type, bytesLoaded, bytesTotal, data);
}
}
}
================================================
FILE: flash/src/com/events/URLStreamProgressEvent.as
================================================
package com.events
{
import flash.events.Event;
public class URLStreamProgressEvent extends Event
{
public static const PROBE_COMPLETE:String = 'probecomplete';
public function URLStreamProgressEvent(type:String)
{
super(type, false, false);
}
public override function clone() : Event {
return new URLStreamProgressEvent(type);
}
}
}
================================================
FILE: flash/src/com/image/BMP.as
================================================
/**
* Copyright 2011, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
package com.image
{
import com.utils.BinaryReader;
import flash.utils.ByteArray;
public class BMP
{
public static const MIME:String = 'image/bmp';
protected var _br:BinaryReader;
public function BMP(binData:ByteArray)
{
_br = new BinaryReader;
_br.init(binData);
}
static public function test(binData:ByteArray) : Boolean
{
var sign:Array = [ 66, 77 ];
for (var i:int = sign.length - 1; i >= 0 ; i--) {
if (binData[i] != sign[i]) {
return false;
}
}
return true;
}
public function info() : Object
{
var a:uint = _br.BYTE(18),
b:uint = _br.BYTE(19),
c:uint = _br.BYTE(22),
d:uint = _br.BYTE(23);
return {
width: b * 256 + a,
height: d * 256 + c,
type: BMP.MIME
}
}
public function metaInfo() : Object
{
return {};
}
public function purge() : void
{
_br.clear();
}
}
}
================================================
FILE: flash/src/com/image/ExifParser.as
================================================
/**
* Copyright 2011, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
package com.image {
import flash.events.EventDispatcher;
import flash.external.ExternalInterface;
import flash.utils.ByteArray;
import com.utils.BinaryReader;
public class ExifParser extends EventDispatcher {
private var data:BinaryReader = new BinaryReader();
private var Tiff:Object;
private var offsets:Object = {
tiffHeader : 10
};
private var tags:Object = {
tiff: {
0x0112: 'Orientation',
0x010E: 'ImageDescription',
0x010F: 'Make',
0x0110: 'Model',
0x0131: 'Software',
0x8769: 'ExifIFDPointer',
0x8825: 'GPSInfoIFDPointer'
},
exif: {
0x9000: 'ExifVersion',
0xA001: 'ColorSpace',
0xA002: 'PixelXDimension',
0xA003: 'PixelYDimension',
0x9003: 'DateTimeOriginal',
0x829A: 'ExposureTime',
0x829D: 'FNumber',
0x8827: 'ISOSpeedRatings',
0x9201: 'ShutterSpeedValue',
0x9202: 'ApertureValue' ,
0x9207: 'MeteringMode',
0x9208: 'LightSource',
0x9209: 'Flash',
0x920A: 'FocalLength',
0xA402: 'ExposureMode',
0xA403: 'WhiteBalance',
0xA406: 'SceneCaptureType',
0xA404: 'DigitalZoomRatio',
0xA408: 'Contrast',
0xA409: 'Saturation',
0xA40A: 'Sharpness'
},
gps: {
0x0000: 'GPSVersionID',
0x0001: 'GPSLatitudeRef',
0x0002: 'GPSLatitude',
0x0003: 'GPSLongitudeRef',
0x0004: 'GPSLongitude'
}
},
tagDescs:Object = {
'ColorSpace': {
1: 'sRGB',
0: 'Uncalibrated'
},
'MeteringMode': {
0: 'Unknown',
1: 'Average',
2: 'CenterWeightedAverage',
3: 'Spot',
4: 'MultiSpot',
5: 'Pattern',
6: 'Partial',
255: 'Other'
},
'LightSource': {
1: 'Daylight',
2: 'Fliorescent',
3: 'Tungsten',
4: 'Flash',
9: 'Fine weather',
10: 'Cloudy weather',
11: 'Shade',
12: 'Daylight fluorescent (D 5700 - 7100K)',
13: 'Day white fluorescent (N 4600 -5400K)',
14: 'Cool white fluorescent (W 3900 - 4500K)',
15: 'White fluorescent (WW 3200 - 3700K)',
17: 'Standard light A',
18: 'Standard light B',
19: 'Standard light C',
20: 'D55',
21: 'D65',
22: 'D75',
23: 'D50',
24: 'ISO studio tungsten',
255: 'Other'
},
'Flash': {
0x0000: 'Flash did not fire.',
0x0001: 'Flash fired.',
0x0005: 'Strobe return light not detected.',
0x0007: 'Strobe return light detected.',
0x0009: 'Flash fired, compulsory flash mode',
0x000D: 'Flash fired, compulsory flash mode, return light not detected',
0x000F: 'Flash fired, compulsory flash mode, return light detected',
0x0010: 'Flash did not fire, compulsory flash mode',
0x0018: 'Flash did not fire, auto mode',
0x0019: 'Flash fired, auto mode',
0x001D: 'Flash fired, auto mode, return light not detected',
0x001F: 'Flash fired, auto mode, return light detected',
0x0020: 'No flash function',
0x0041: 'Flash fired, red-eye reduction mode',
0x0045: 'Flash fired, red-eye reduction mode, return light not detected',
0x0047: 'Flash fired, red-eye reduction mode, return light detected',
0x0049: 'Flash fired, compulsory flash mode, red-eye reduction mode',
0x004D: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected',
0x004F: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light detected',
0x0059: 'Flash fired, auto mode, red-eye reduction mode',
0x005D: 'Flash fired, auto mode, return light not detected, red-eye reduction mode',
0x005F: 'Flash fired, auto mode, return light detected, red-eye reduction mode'
},
'ExposureMode': {
0: 'Auto exposure',
1: 'Manual exposure',
2: 'Auto bracket'
},
'WhiteBalance': {
0: 'Auto white balance',
1: 'Manual white balance'
},
'SceneCaptureType': {
0: 'Standard',
1: 'Landscape',
2: 'Portrait',
3: 'Night scene'
},
'Contrast': {
0: 'Normal',
1: 'Soft',
2: 'Hard'
},
'Saturation': {
0: 'Normal',
1: 'Low saturation',
2: 'High saturation'
},
'Sharpness': {
0: 'Normal',
1: 'Soft',
2: 'Hard'
},
// GPS related
'GPSLatitudeRef': {
N: 'North latitude',
S: 'South latitude'
},
'GPSLongitudeRef': {
E: 'East longitude',
W: 'West longitude'
}
};
public function init(segment:ByteArray):Boolean {
// Reset internal data
offsets = {
tiffHeader: 10
};
if (!segment || !segment.length) {
return false;
}
data.init(segment);
// Check if that's APP1 and that it has EXIF
if (data.SHORT(0) === 0xFFE1 && data.STRING(4, 4).toUpperCase() === "EXIF") {
return getIFDOffsets();
}
return false;
}
public function TIFF():Object {
return Tiff;
}
public function EXIF():Object {
var Exif:Object;
if (!offsets.hasOwnProperty('exifIFD')) {
return null;
}
try { // survive invalid offsets
Exif = extractTags(offsets['exifIFD'], tags.exif);
} catch (ex:Error) {
return null;
}
// fix formatting of some tags
if (Exif.hasOwnProperty('ExifVersion') && Exif.ExifVersion is Array) {
for (var i:uint = 0, exifVersion:String = ''; i < Exif.ExifVersion.length; i++) {
exifVersion += String.fromCharCode(Exif.ExifVersion[i]);
}
Exif.ExifVersion = exifVersion;
}
return Exif;
}
public function GPS():Object {
var Gps:Object;
if (!offsets.hasOwnProperty('gpsIFD')) {
return null;
}
try { // survive invalid offsets
Gps = extractTags(offsets['gpsIFD'], tags.gps);
} catch (ex:Error) {
return null;
}
if (Gps.hasOwnProperty('GPSVersionID') && Gps.GPSVersionID is Array) {
Gps.GPSVersionID = Gps.GPSVersionID.join('.');
}
return Gps;
}
public function setExif(tag:String, value:*) : Boolean {
// Right now only setting of width/height is possible
if (tag !== 'PixelXDimension' && tag !== 'PixelYDimension') return false;
return setTag('exif', tag, value);
}
public function getBinary():ByteArray {
return data.SEGMENT();
}
private function isJPEG():Boolean {
return data.SHORT(0) == 0xFFD8;
}
private function getIFDOffsets():Boolean {
var idx:uint = offsets.tiffHeader;
// Set read order of multi-byte data
data.II(data.SHORT(idx) == 0x4949);
// Check if always present bytes are indeed present
if (data.SHORT(idx+=2) !== 0x002A) {
return false;
}
offsets['IFD0'] = offsets.tiffHeader + data.LONG(idx += 2);
Tiff = extractTags(offsets['IFD0'], tags.tiff);
if (Tiff.hasOwnProperty('ExifIFDPointer')) {
offsets['exifIFD'] = offsets.tiffHeader + Tiff.ExifIFDPointer;
delete Tiff.ExifIFDPointer;
}
if (Tiff.hasOwnProperty('GPSInfoIFDPointer')) {
offsets['gpsIFD'] = offsets.tiffHeader + Tiff.GPSInfoIFDPointer;
delete Tiff.GPSInfoIFDPointer;
}
return true;
}
private function extractTags(IFD_offset:int, tags2extract:Object):Object {
var length:uint, i:uint, ii:uint,
tag:String, type:uint, count:uint, tagOffset:uint, offset:uint, value:*,
values:Array = [], hash:Object = {};
length = data.SHORT(IFD_offset);
for (i = 0; i < length; i++) {
// Set binary reader pointer to beginning of the next tag
offset = tagOffset = IFD_offset + 12 * i + 2;
tag = tags2extract[data.SHORT(offset)];
if (!tag) {
continue; // Not the tag we requested
}
type = data.SHORT(offset+=2);
count = data.LONG(offset+=2);
offset += 4;
values = [];
switch (type) {
case 1: // BYTE
case 7: // UNDEFINED
if (count > 4) {
offset = data.LONG(offset) + offsets.tiffHeader;
}
for (ii = 0; ii < count; ii++) {
values[ii] = data.BYTE(offset + ii);
}
break;
case 2: // STRING
if (count > 4) {
offset = data.LONG(offset) + offsets.tiffHeader;
}
hash[tag] = data.STRING(offset, count - 1);
continue;
case 3: // SHORT
if (count > 2) {
offset = data.LONG(offset) + offsets.tiffHeader;
}
for (ii = 0; ii < count; ii++) {
values[ii] = data.SHORT(offset + ii*2);
}
break;
case 4: // LONG
if (count > 1) {
offset = data.LONG(offset) + offsets.tiffHeader;
}
for (ii = 0; ii < count; ii++) {
values[ii] = data.LONG(offset + ii*4);
}
break;
case 5: // RATIONAL
offset = data.LONG(offset) + offsets.tiffHeader;
for (ii = 0; ii < count; ii++) {
values[ii] = data.LONG(offset + ii*4) / data.LONG(offset + ii*4 + 4);
}
break;
case 9: // SLONG
offset = data.LONG(offset) + offsets.tiffHeader;
for (ii = 0; ii < count; ii++) {
values[ii] = data.SLONG(offset + ii*4);
}
break;
case 10: // SRATIONAL
offset = data.LONG(offset) + offsets.tiffHeader;
for (ii = 0; ii < count; ii++) {
values[ii] = data.SLONG(offset + ii*4) / data.SLONG(offset + ii*4 + 4);
}
break;
default:
continue;
}
value = (count == 1 ? values[0] : values);
if (tagDescs.hasOwnProperty(tag) && typeof value != 'object') {
hash[tag] = tagDescs[tag][value];
} else {
hash[tag] = value;
}
}
return hash;
}
// At the moment only setting of simple (LONG) values, that do not require offset recalculation, is supported
private function setTag(ifd:String, tag:*, value:*) : Boolean {
var offset:*, length:uint, tagOffset:uint, valueOffset:uint = 0, hex:*;
// If tag name passed translate into hex key
if (tag is String) {
var tmpTags:Object = tags[ifd.toLowerCase()];
for (hex in tmpTags) {
if (tmpTags[hex] === tag) {
tag = hex;
break;
}
}
}
offset = offsets[ifd.toLowerCase() + 'IFD'];
if (offset === null) {
return false;
}
length = data.SHORT(offset);
for (var i:uint = 0; i < length; i++) {
tagOffset = offset + 12 * i + 2;
if (data.SHORT(tagOffset) == tag) {
valueOffset = tagOffset + 8;
break;
}
}
if (!valueOffset) return false;
data.LONG(valueOffset, value);
return true;
}
public function purge() : void {
data.clear();
}
}
}
================================================
FILE: flash/src/com/image/GIF.as
================================================
/**
* Copyright 2011, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
package com.image
{
import com.utils.BinaryReader;
import flash.utils.ByteArray;
public class GIF
{
public static const MIME:String = 'image/gif';
protected var _br:BinaryReader;
public function GIF(binData:ByteArray)
{
_br = new BinaryReader;
_br.init(binData);
}
static public function test(binData:ByteArray) : Boolean
{
var sign:Array = [ 71, 73, 70 ];
for (var i:int = sign.length - 1; i >= 0 ; i--) {
if (binData[i] != sign[i]) {
return false;
}
}
return true;
}
public function info() : Object
{
var a:uint = _br.BYTE(6),
b:uint = _br.BYTE(7),
c:uint = _br.BYTE(8),
d:uint = _br.BYTE(9);
return {
width: b * 256 + a,
height: d * 256 + c,
type: GIF.MIME
}
}
public function metaInfo() : Object
{
return {};
}
public function purge() : void
{
_br.clear();
}
}
}
================================================
FILE: flash/src/com/image/ImageEditor.as
================================================
package com.image
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.filters.BlurFilter;
import flash.filters.ColorMatrixFilter;
import flash.filters.ConvolutionFilter;
import flash.geom.ColorTransform;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
import com.image.ascb.filters.ColorMatrixArrays;
import com.image.ascb.filters.ConvolutionMatrixArrays;
public class ImageEditor
{
private var _history:Array = [];
private var _historyIndex:int = -1;
private var _lastReleaseIndex:int = 0;
private var _bdOriginal:BitmapData;
private var _bd:BitmapData;
public function get bitmapData() : BitmapData {
return (_bd ? _bd : _bdOriginal).clone();
}
private var _crop:Rectangle = null;
private var _matrix:Matrix = new Matrix();
private var _commitAfterEveryModify:Boolean = false;
public function ImageEditor(bd:BitmapData)
{
_bdOriginal = bd.clone();
}
public function modify(op:String, ... args) : void
{
if (canRedo()) {
_history.length = _historyIndex + 1; // discard extra redoable ops
}
_history.push({
'op': op,
'args': args
});
if (_commitAfterEveryModify) {
commit();
}
_historyIndex++;
}
public function commit() : void
{
_doModifications(_lastReleaseIndex, _historyIndex); // do only incremental modifications if possible
_lastReleaseIndex = _historyIndex;
_matrix = new Matrix();
}
public function canUndo() : Boolean
{
return !!_history.length;
}
public function canRedo() : Boolean
{
return _historyIndex < _history.length;
}
public function undo() : void
{
if (canUndo()) {
_historyIndex--;
if (_historyIndex < _lastReleaseIndex) {
_lastReleaseIndex = 0;
if (_bd) {
_bd.dispose();
_bd = null;
}
_matrix = new Matrix();
}
}
}
public function redo() : void
{
if (canRedo()) {
_historyIndex++;
}
}
public function purge() : void
{
if (_bd) {
_bd.dispose();
}
_bdOriginal.dispose();
}
protected function _doModifications(start:int, end:int) : void
{
if (!_bd) {
_bd = _bdOriginal.clone();
}
var mod:Object;
for (var i:int = start; i <= end; i++) {
mod = _history[i];
if (typeof(this[mod.op]) == 'function') {
this[mod.op].apply(null, mod.args);
}
}
_draw();
}
protected function rotate(angle:Number) : void
{
_matrix.translate(-_bd.width/2,-_bd.height/2);
_matrix.rotate(angle / 180 * Math.PI);
_matrix.translate(_bd.width/2,_bd.height/2);
}
protected function flipH() : void
{
_matrix.scale(-1, 1);
_matrix.translate(_bd.width, 0);
}
protected function flipV() : void
{
_matrix.scale(1, -1);
_matrix.translate(0, _bd.height);
}
protected function resize(w:Number, h:Number) : void
{
_matrix.scale(w / _bd.width, h / _bd.height);
}
protected function crop(rect:Rectangle) : void
{
}
protected function sharpen() : void
{
applyConvolution(ConvolutionMatrixArrays.SHARPEN);
}
protected function emboss() : void
{
applyConvolution(ConvolutionMatrixArrays.EMBOSS);
}
protected function grayscale() : void
{
applyColorMatrix(ColorMatrixArrays.GRAYSCALE);
}
protected function sepia() : void
{
applyColorMatrix(ColorMatrixArrays.SEPIA);
}
protected function invert() : void
{
applyColorMatrix(ColorMatrixArrays.DIGITAL_NEGATIVE);
}
protected function brightness(value:int) : void
{
applyColorMatrix(ColorMatrixArrays.getBrightnessArray(Math.floor(255 * value)));
}
protected function contrast(value:Number) : void
{
applyColorMatrix(ColorMatrixArrays.getContrastArray(value));
}
protected function saturate(value:Number) : void
{
applyColorMatrix(ColorMatrixArrays.getSaturationArray(value));
}
protected function blur(value:Number = 0.02, quality:int = 1) : void
{
if (!_bd) {
_bd = _bdOriginal.clone();
}
value = Math.floor(255 * value);
if (value & 1) {
value--; // even values are processed faster
}
_bd.applyFilter(_bd, _bd.rect, new Point(0, 0), new BlurFilter(value, value, quality));
}
protected function applyConvolution(matrix:Array, devisor:Number = 1.0) : void
{
if (!_bd) {
_bd = _bdOriginal.clone();
}
_bd.applyFilter(_bd, _bd.rect, new Point(0, 0), new ConvolutionFilter(3, 3, matrix, devisor));
}
protected function applyColorMatrix(matrix:Array) : void
{
if (!_bd) {
_bd = _bdOriginal.clone();
}
_bd.applyFilter(_bd, _bd.rect, new Point(0, 0), new ColorMatrixFilter(matrix));
}
private function _draw() : void
{
// Finding the four corners of the bounfing box after transformation
var tl:Point = _matrix.transformPoint(new Point(0, 0));
var tr:Point = _matrix.transformPoint(new Point(_bd.width, 0));
var bl:Point = _matrix.transformPoint(new Point(0, _bd.height));
var br:Point = _matrix.transformPoint(new Point(_bd.width, _bd.height));
// Calculating "who" is "where"
var top:Number = Math.min(tl.y, tr.y, bl.y, br.y);
var bottom:Number = Math.max(tl.y, tr.y, bl.y, br.y);
var left:Number = Math.min(tl.x, tr.x, bl.x, br.x);
var right:Number = Math.max(tl.x, tr.x, bl.x, br.x);
// Ajusting final position
_matrix.translate(-left, -top);
// Calculating the size of the new BitmapData
var width:Number = right - left;
var height:Number = bottom - top;
// Creating and drawing (with transformation)
var result:BitmapData = new BitmapData(width, height);
result.draw(_bd, _matrix);
_bd.dispose();
_bd = result;
}
}
}
================================================
FILE: flash/src/com/image/JPEG.as
================================================
/**
* Copyright 2011, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
package com.image
{
import flash.utils.ByteArray;
import com.utils.BinaryReader;
import com.image.ExifParser;
public class JPEG
{
public static const MIME:String = 'image/jpeg';
protected var _headers:Array = [];
protected var _br:BinaryReader;
public function JPEG(binData:ByteArray)
{
_br = new BinaryReader;
_br.init(binData);
}
static public function test(binData:ByteArray) : Boolean
{
var sign:Array = [ 255, 216 ];
for (var i:int = sign.length - 1; i >= 0 ; i--) {
if (binData[i] != sign[i]) {
return false;
}
}
return true;
}
public function info() : Object
{
var idx:uint = 0, marker:uint, length:uint;
// examine all through the end, since some images might have very large APP segments
while (idx <= _br.length) {
marker = _br.SHORT(idx += 2);
if (marker >= 0xFFC0 && marker <= 0xFFC3) { // SOFn
idx += 5; // marker (2 bytes) + length (2 bytes) + Sample precision (1 byte)
return {
height: _br.SHORT(idx),
width: _br.SHORT(idx += 2),
type: JPEG.MIME
};
}
length = _br.SHORT(idx += 2);
idx += length - 2;
}
return null;
}
public function metaInfo() : Object
{
var exifParser:ExifParser, headers:Array,
meta:Object = {}, exif:Object, gps:Object, tiff:Object;
headers = getHeaders('app1');
if (headers.length) {
exifParser = new ExifParser;
if (exifParser.init(headers[0])) {
tiff = exifParser.TIFF();
if (tiff) {
meta['tiff'] = tiff;
}
exif = exifParser.EXIF();
if (exif) {
meta['exif'] = exif;
}
gps = exifParser.GPS();
if (gps) {
meta['gps'] = gps;
}
exifParser.purge();
}
}
return meta;
}
public function extractHeaders() : Array
{
var idx:uint, marker:uint, length:uint;
idx = 2;
while (idx <= _br.length) {
marker = _br.SHORT(idx);
// omit RST (restart) markers
if (marker >= 0xFFD0 && marker <= 0xFFD7) {
idx += 2;
continue;
}
// no headers allowed after SOS marker
if (marker === 0xFFDA || marker === 0xFFD9) {
break;
}
length = _br.SHORT(idx + 2) + 2;
// APPn marker detected
if (marker >= 0xFFE1 && marker <= 0xFFEF) {
_headers.push({
hex: marker,
name: 'APP' + (marker & 0x000F),
start: idx,
length: length,
segment: _br.SEGMENT(idx, length)
});
}
idx += length;
}
return _headers;
}
public function stripHeaders(binData:ByteArray) : void
{
var img:JPEG = new JPEG(binData), headers:Array, br:BinaryReader = new BinaryReader();
img.extractHeaders();
headers = img.getHeaders();
img.purge();
if (headers.length) {
br.init(binData);
for (var i:int = headers.length - 1; i >= 0; i--) {
br.SEGMENT(headers[i].start, headers[i].length, null);
}
binData.clear();
binData.writeBytes(br.SEGMENT());
br.clear();
}
}
public function getHeaders(name:String = null) : Array
{
var headers:Array, array:Array = [];
headers = _headers.length ? _headers : extractHeaders();
if (!name) {
return headers;
}
for (var i:uint = 0, max:uint = headers.length; i < max; i++) {
if (headers[i].name === name.toUpperCase()) {
array.push(headers[i].segment);
}
}
return array;
}
public function setHeaders(name:String, segment:*) : void
{
var array:Array = [];
if (segment is ByteArray) {
array.push(segment);
} else {
array = segment;
}
for (var i:uint = 0, ii:uint = 0, max:uint = _headers.length; i < max; i++) {
if (_headers[i].name === name.toUpperCase()) {
_headers[i].segment = array[ii];
_headers[i].length = array[ii].length;
ii++;
}
if (ii >= array.length) break;
}
}
public function updateDimensions(width:uint, height:uint) : void
{
var exifParser:ExifParser, headers:Array;
headers = getHeaders('app1');
if (headers.length) {
exifParser = new ExifParser;
if (exifParser.init(headers[0])) {
exifParser.setExif('PixelXDimension', width);
exifParser.setExif('PixelYDimension', height);
setHeaders('app1', exifParser.getBinary());
}
exifParser.purge();
}
}
public function insertHeaders(binData:ByteArray, headers:Array = null) : void
{
var idx:uint, br:BinaryReader = new BinaryReader;
if (!headers || !headers.length) {
headers = _headers;
}
br.init(binData);
// Check if data is jpeg
if (br.SHORT(0) !== 0xFFD8) {
throw new Error("Invalid JPEG");
}
if (headers.length) {
idx = br.SHORT(2) == 0xFFE0 ? 4 + br.SHORT(4) : 2;
for (var i:uint = 0, max:uint = headers.length; i < max; i++) {
br.SEGMENT(idx, 0, headers[i].segment);
idx += headers[i].length;
}
}
binData.clear();
binData.writeBytes(br.SEGMENT());
br.clear();
}
public function purge() : void
{
_br.clear();
}
}
}
================================================
FILE: flash/src/com/image/JPEGEncoder.as
================================================
package com.image
{
/*
*
* MUCH (4x) faster version of jpeg encoder. Use instead of com.adobe.images.JPGEncoder
*
* taken from bytearray.org/?p=775, created by Thibault Imbert
**/
import flash.display.BitmapData;
import flash.utils.ByteArray;
public final class JPEGEncoder
{
// Static table initialization
private const ZigZag:Vector. = Vector.([
0, 1, 5, 6,14,15,27,28,
2, 4, 7,13,16,26,29,42,
3, 8,12,17,25,30,41,43,
9,11,18,24,31,40,44,53,
10,19,23,32,39,45,52,54,
20,22,33,38,46,51,55,60,
21,34,37,47,50,56,59,61,
35,36,48,49,57,58,62,63
]);
private var YTable:Vector. = new Vector.(64, true);
private var UVTable:Vector. = new Vector.(64, true);
private var outputfDCTQuant:Vector. = new Vector.(64, true);
private var fdtbl_Y:Vector. = new Vector.(64, true);
private var fdtbl_UV:Vector. = new Vector.(64, true);
private var sf:int;
private const aasf:Vector. = Vector.([
1.0, 1.387039845, 1.306562965, 1.175875602,
1.0, 0.785694958, 0.541196100, 0.275899379
]);
private var YQT:Vector. = Vector.([
16, 11, 10, 16, 24, 40, 51, 61,
12, 12, 14, 19, 26, 58, 60, 55,
14, 13, 16, 24, 40, 57, 69, 56,
14, 17, 22, 29, 51, 87, 80, 62,
18, 22, 37, 56, 68,109,103, 77,
24, 35, 55, 64, 81,104,113, 92,
49, 64, 78, 87,103,121,120,101,
72, 92, 95, 98,112,100,103, 99
]);
private const UVQT:Vector. = Vector.([
17, 18, 24, 47, 99, 99, 99, 99,
18, 21, 26, 66, 99, 99, 99, 99,
24, 26, 56, 99, 99, 99, 99, 99,
47, 66, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99
]);
private function initQuantTables(sf:int):void
{
var i:int;
const I64:int = 64;
const I8:int = 8;
for (i = 0; i < I64; ++i)
{
var t:int = int((YQT[i]*sf+50)*0.01);
if (t < 1) {
t = 1;
} else if (t > 255) {
t = 255;
}
YTable[ZigZag[i]] = t;
}
for (i = 0; i < I64; i++)
{
var u:int = int((UVQT[i]*sf+50)*0.01);
if (u < 1) {
u = 1;
} else if (u > 255) {
u = 255;
}
UVTable[ZigZag[i]] = u;
}
i = 0;
for (var row:int = 0; row < I8; ++row)
{
for (var col:int = 0; col < I8; ++col)
{
fdtbl_Y[i] = (1 / (YTable [ZigZag[i]] * aasf[row] * aasf[col] * I8));
fdtbl_UV[i] = (1 / (UVTable[ZigZag[i]] * aasf[row] * aasf[col] * I8));
i++;
}
}
}
private var YDC_HT:Vector.;
private var UVDC_HT:Vector.;
private var YAC_HT:Vector.;
private var UVAC_HT:Vector.;
private function computeHuffmanTbl(nrcodes:Vector., std_table:Vector.):Vector.
{
var codevalue:int = 0;
var pos_in_table:int = 0;
var HT:Vector. = new Vector.(251, true);
var bitString:BitString;
for (var k:int=1; k<=16; ++k)
{
for (var j:int=1; j<=nrcodes[k]; ++j)
{
HT[std_table[pos_in_table]] = bitString = new BitString();
bitString.val = codevalue;
bitString.len = k;
pos_in_table++;
codevalue++;
}
codevalue<<=1;
}
return HT;
}
private var std_dc_luminance_nrcodes:Vector. = Vector.([0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0]);
private var std_dc_luminance_values:Vector. = Vector.([0,1,2,3,4,5,6,7,8,9,10,11]);
private var std_ac_luminance_nrcodes:Vector. = Vector.([0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d]);
private var std_ac_luminance_values:Vector. = Vector.([0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,
0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,
0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,
0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,
0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,
0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,
0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,
0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,
0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,
0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,
0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,
0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,
0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,
0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,
0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,
0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,
0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,
0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,
0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
0xf9,0xfa]);
private var std_dc_chrominance_nrcodes:Vector. = Vector.([0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0]);
private var std_dc_chrominance_values:Vector. = Vector.([0,1,2,3,4,5,6,7,8,9,10,11]);
private var std_ac_chrominance_nrcodes:Vector. = Vector.([0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77]);
private var std_ac_chrominance_values:Vector. = Vector.([0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,
0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,
0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,
0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,
0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,
0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,
0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,
0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,
0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,
0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,
0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,
0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,
0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,
0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,
0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,
0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,
0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,
0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,
0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
0xf9,0xfa
]);
private function initHuffmanTbl():void
{
YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values);
UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values);
YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values);
UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values);
}
private var bitcode:Vector. = new Vector.(65535, true);
private var category:Vector. = new Vector.(65535, true);
private function initCategoryNumber():void
{
var nrlower:int = 1;
var nrupper:int = 2;
var bitString:BitString;
const I15:int = 15;
var pos:int;
for (var cat:int=1; cat<=I15; ++cat)
{
//Positive numbers
for (var nr:int=nrlower; nr= 0 )
{
if (value & uint(1 << posval) )
bytenew |= uint(1 << bytepos);
posval--;
bytepos--;
if (bytepos < 0)
{
if (bytenew == 0xFF)
{
byteout.writeByte(0xFF);
byteout.writeByte(0);
}
else byteout.writeByte(bytenew);
bytepos=7;
bytenew=0;
}
}
}
// DCT & quantization core
private function fDCTQuant(data:Vector., fdtbl:Vector.):Vector.
{
/* Pass 1: process rows. */
var dataOff:int=0;
var d0:Number, d1:Number, d2:Number, d3:Number, d4:Number, d5:Number, d6:Number, d7:Number;
var i:int;
const I8:int = 8;
const I64:int = 64;
for (i=0; i 0.0) ? int(fDCTQuant + 0.5) : int(fDCTQuant - 0.5);
}
return outputfDCTQuant;
}
// Chunk writing
private function writeAPP0():void
{
byteout.writeShort(0xFFE0); // marker
byteout.writeShort(16); // length
byteout.writeByte(0x4A); // J
byteout.writeByte(0x46); // F
byteout.writeByte(0x49); // I
byteout.writeByte(0x46); // F
byteout.writeByte(0); // = "JFIF",'\0'
byteout.writeByte(1); // versionhi
byteout.writeByte(1); // versionlo
byteout.writeByte(0); // xyunits
byteout.writeShort(1); // xdensity
byteout.writeShort(1); // ydensity
byteout.writeByte(0); // thumbnwidth
byteout.writeByte(0); // thumbnheight
}
private function writeSOF0(width:int, height:int):void
{
byteout.writeShort(0xFFC0); // marker
byteout.writeShort(17); // length, truecolor YUV JPG
byteout.writeByte(8); // precision
byteout.writeShort(height);
byteout.writeShort(width);
byteout.writeByte(3); // nrofcomponents
byteout.writeByte(1); // IdY
byteout.writeByte(0x11); // HVY
byteout.writeByte(0); // QTY
byteout.writeByte(2); // IdU
byteout.writeByte(0x11); // HVU
byteout.writeByte(1); // QTU
byteout.writeByte(3); // IdV
byteout.writeByte(0x11); // HVV
byteout.writeByte(1); // QTV
}
private function writeDQT():void
{
byteout.writeShort(0xFFDB); // marker
byteout.writeShort(132); // length
byteout.writeByte(0);
var i:int;
const I64:int = 64;
for (i=0; i = new Vector.(64, true);
private function processDU(CDU:Vector., fdtbl:Vector., DC:Number, HTDC:Vector., HTAC:Vector.):Number
{
var EOB:BitString = HTAC[0x00];
var M16zeroes:BitString = HTAC[0xF0];
var pos:int;
const I16:int = 16;
const I63:int = 63;
const I64:int = 64;
var DU_DCT:Vector. = fDCTQuant(CDU, fdtbl);
//ZigZag reorder
for (var j:int=0;j0)&&(DU[end0pos]==0); end0pos--) {};
//end0pos = first element in reverse order !=0
if ( end0pos == 0) {
writeBits(EOB);
return DC;
}
var i:int = 1;
var lng:int;
while ( i <= end0pos ) {
var startpos:int = i;
for (; (DU[i]==0) && (i<=end0pos); ++i) {}
var nrzeroes:int = i-startpos;
if ( nrzeroes >= I16 ) {
lng = nrzeroes>>4;
for (var nrmarker:int=1; nrmarker <= lng; ++nrmarker)
writeBits(M16zeroes);
nrzeroes = int(nrzeroes&0xF);
}
pos = int(32767+DU[i]);
writeBits(HTAC[int((nrzeroes<<4)+category[pos])]);
writeBits(bitcode[pos]);
i++;
}
if ( end0pos != I63 ) {
writeBits(EOB);
}
return DC;
}
private var YDU:Vector. = new Vector.(64, true);
private var UDU:Vector. = new Vector.(64, true);
private var VDU:Vector. = new Vector.(64, true);
private function RGB2YUV(img:BitmapData, xpos:int, ypos:int):void
{
var pos:int=0;
const I8:int = 8;
for (var y:int=0; y>16)&0xFF;
var G:int = (P>> 8)&0xFF;
var B:int = (P )&0xFF;
YDU[int(pos)]=((( 0.29900)*R+( 0.58700)*G+( 0.11400)*B))-0x80;
UDU[int(pos)]=(((-0.16874)*R+(-0.33126)*G+( 0.50000)*B));
VDU[int(pos)]=((( 0.50000)*R+(-0.41869)*G+(-0.08131)*B));
++pos;
}
}
}
public function JPEGEncoder(quality:int=50)
{
if (quality <= 0)
quality = 1;
if (quality > 100)
quality = 100;
sf = quality < 50 ? int(5000 / quality) : int(200 - (quality<<1));
init();
}
private function init():void
{
ZigZag.fixed = true;
aasf.fixed = true;
YQT.fixed = true;
UVQT.fixed = true;
std_ac_chrominance_nrcodes.fixed = true;
std_ac_chrominance_values.fixed = true;
std_ac_luminance_nrcodes.fixed = true;
std_ac_luminance_values.fixed = true;
std_dc_chrominance_nrcodes.fixed = true;
std_dc_chrominance_values.fixed = true;
std_dc_luminance_nrcodes.fixed = true;
std_dc_luminance_values.fixed = true;
// Create tables
initHuffmanTbl();
initCategoryNumber();
initQuantTables(sf);
}
public function encode(image:BitmapData):ByteArray
{
// Initialize bit writer
byteout = new ByteArray();
bytenew=0;
bytepos=7;
// Add JPEG headers
byteout.writeShort(0xFFD8); // SOI
writeAPP0();
writeDQT();
writeSOF0(image.width,image.height);
writeDHT();
writeSOS();
// Encode 8x8 macroblocks
var DCY:Number=0;
var DCU:Number=0;
var DCV:Number=0;
bytenew=0;
bytepos=7;
var width:int = image.width;
var height:int = image.height;
for (var ypos:int=0; ypos= 0 )
{
var fillbits:BitString = new BitString();
fillbits.len = bytepos+1;
fillbits.val = (1<<(bytepos+1))-1;
writeBits(fillbits);
}
byteout.writeShort(0xFFD9); //EOI
return byteout;
}
}
}
final class BitString
{
public var len:int = 0;
public var val:int = 0;
}
================================================
FILE: flash/src/com/image/PNG.as
================================================
/**
* Copyright 2011, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
package com.image
{
import com.utils.BinaryReader;
import flash.utils.ByteArray;
public class PNG
{
public static const MIME:String = 'image/png';
protected var _br:BinaryReader;
public function PNG(binData:ByteArray)
{
_br = new BinaryReader;
_br.init(binData);
}
static public function test(binData:ByteArray) : Boolean
{
var sign:Array = [ 137, 80, 78, 71, 13, 10, 26, 10 ];
for (var i:int = sign.length - 1; i >= 0 ; i--) {
if (binData[i] != sign[i]) {
return false;
}
}
return true;
}
public function info() : Object
{
var chunk:Object, idx:uint;
chunk = _getChunkAt(8);
if (chunk.type == 'IHDR') {
idx = chunk.start;
return {
width: _br.LONG(idx),
height: _br.LONG(idx += 4),
type: PNG.MIME
};
}
return null;
}
public function metaInfo() : Object
{
return {};
}
private function _getChunkAt(idx:uint) : Object
{
var length:uint, type:String, start:uint, CRC:uint;
length = _br.LONG(idx);
type = _br.STRING(idx += 4, 4);
start = idx += 4;
CRC = _br.LONG(idx + length);
return {
length: length,
type: type,
start: start,
CRC: CRC
};
}
public function purge() : void
{
_br.clear();
}
}
}
================================================
FILE: flash/src/com/image/ascb/filters/ColorMatrixArrays.as
================================================
package com.image.ascb.filters {
public class ColorMatrixArrays {
public static const DIGITAL_NEGATIVE:Array = [-1, 0, 0, 0, 255, 0, -1, 0, 0, 255, 0, 0, -1, 0, 255, 0, 0, 0, 1, 0];
public static const GRAYSCALE:Array = [0.3086, 0.6094, 0.0820, 0, 0, 0.3086, 0.6094, 0.0820, 0, 0, 0.3086, 0.6094, 0.0820, 0, 0, 0, 0, 0, 1, 0];
public static const SEPIA:Array = [0.3930000066757202, 0.7689999938011169, 0.1889999955892563, 0, 0, 0.3490000069141388, 0.6859999895095825, 0.1679999977350235, 0, 0, 0.2720000147819519, 0.5339999794960022, 0.1309999972581863, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1];
public static function getSaturationArray(nValue:Number):Array {
var nRed:Number = 0.3086,
nGreen:Number = 0.6094,
nBlue:Number = 0.0820,
nA:Number = (1 - nValue) * nRed + nValue,
nB:Number = (1 - nValue) * nGreen,
nC:Number = (1 - nValue) * nBlue,
nD:Number = (1 - nValue) * nRed,
nE:Number = (1 - nValue) * nGreen + nValue,
nF:Number = (1 - nValue) * nBlue,
nG:Number = (1 - nValue) * nRed,
nH:Number = (1 - nValue) * nGreen,
nI:Number = (1 - nValue) * nBlue + nValue;
return [nA, nB, nC, 0, 0, nD, nE, nF, 0, 0, nG, nH, nI, 0, 0, 0, 0, 0, 1, 0];
}
public static function getContrastArray(nValue:Number) : Array
{
var nScale:Number = nValue * 11,
nOffset:Number = 63.6 - (nValue * 698.5);
return [nScale, 0, 0, 0, nOffset, 0, nScale, 0, 0, nOffset, 0, 0, nScale, 0, nOffset, 0, 0, 0, 1, 0];
}
public static function getBrightnessArray(nValue:Number) : Array
{
return [1, 0, 0, 0, nValue, 0, 1, 0, 0, nValue, 0, 0, 1, 0, nValue, 0, 0, 0, 1, 0];
}
}
}
================================================
FILE: flash/src/com/image/ascb/filters/ConvolutionMatrixArrays.as
================================================
package com.image.ascb.filters {
public class ConvolutionMatrixArrays {
public static const EMBOSS:Array = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
public static const EDGE_DETECT:Array = [0, 1, 0, 1, -4, 1, 0, 1, 0];
public static const SHARPEN:Array = [0, -1, 0, -1, 5, -1, 0, -1, 0];
}
}
================================================
FILE: flash/src/com/image/events/ExifParserEvent.as
================================================
/**
* Copyright 2011, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
package com.image.events {
import flash.events.Event;
public class ExifParserEvent extends Event {
public var data:Object;
public static const EXIF_DATA:String = 'exifdata';
public static const GPS_DATA:String = 'gpsdata';
function ExifParserEvent(type:String, data:Object) {
this.data = data;
super(type);
}
override public function clone() : Event
{
return new ExifParserEvent(type, data);
}
}
}
================================================
FILE: flash/src/com/image/formatlos/BitmapDataUnlimited.as
================================================
/*
Copyright (c) 2008 Martin Raedlinger (mr@formatlos.de)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package com.image.formatlos
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.IBitmapDrawable;
import flash.display.Loader;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.geom.ColorTransform;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
import com.image.formatlos.events.BitmapDataUnlimitedEvent;
/**
* Dispatched when the BitmapData is ready
*
* @eventType com.formatlos.events.BitmapDataUnlimitedEvent
*/
[Event(name='COMPLETE', type='com.image.formatlos.events.BitmapDataUnlimitedEvent')]
/**
* Dispatched when the BitmapData can't be created due to memory issues.
* watch your system memory and/or System.totalMemory
*
* @eventType com.formatlos.events.BitmapDataUnlimitedEvent
*/
[Event(name='ERROR', type='com.image.formatlos.events.BitmapDataUnlimitedEvent')]
// ---------------------------------------------------------------------------
/**
* The BitmapDataUnlimited Class creates an empty gif image
*
* @author Martin Raedlinger
*
* @example
* The example shows how to use the BitmapDataUnlimited
*
*
*
* var bdu:BitmapDataUnlimited = new BitmapDataUnlimited();
* bdu.addEventListener(BitmapDataUnlimitedEvent.COMPLETE, onBmpReady);
* bdu.create(5000, 5000, true);
*
* var hugeBitmapData : BitmapData;
*
* function onBmpReady(event : BitmapDataUnlimitedEvent) : void
* {
* hugeBitmapData = bdu.bitmapData;
*
* var rect : Rectangle = new Rectangle(10, 10, 10, 10);
*
* hugeBitmapData.fillRect(rect, 0xffff0000);
* addChild(new Bitmap(hugeBitmapData));
*
* trace("BitmapData: w=" + hugeBitmapData.width + " h=" + hugeBitmapData.height);
* }
*
*
*
*
*/
public class BitmapDataUnlimited extends EventDispatcher
{
// basically this value is 4096, but take 4000 to have some buffer
static private const DRAW_LIMIT : uint = 4000;
private var _loader : Loader;
private var _gif : Gif;
private var _fillColor : uint;
private var _transparent : Boolean;
// created bitmapData
private var _bitmapData : BitmapData;
/**
* Returns the created BitmapData Object
*
* @return Huge BitmapData
*/
public function get bitmapData() : BitmapData
{
return _bitmapData;
}
/**
* Creates a huge BitmapData object.
*
* @param width The width of the huge BitmapData
* @param height The height of the huge BitmapData
* @param transparent transparent BitmapData or not
* @param fillColor Fill the BitmapData with color
*/
public function create(width_ : int, height_ : int, transparent_ : Boolean = true, fillColor_ : uint = 0xFFFFFF) : void
{
try
{
_bitmapData = new BitmapData(width_, height_, transparent_, fillColor_);
dispatchComplete();
}
catch(error : ArgumentError)
{
if(width_ <= 0 || height_ <= 0)
{
throw error;
}
else
{
_transparent = transparent_;
_fillColor = fillColor_;
_gif = new Gif(width_, height_, transparent_, fillColor_);
_loader = new Loader();
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaderComplete);
_loader.loadBytes(_gif.bytes);
}
}
}
/**
* Bypasses the 4096px limit in BitmapData.draw() and draws the source display object onto the bitmap image.
*
* @see http://blog.formatlos.de/2008/12/11/bitmapdatadraw-is-limited-to-4096px/
*
* @param source_ The display object or BitmapData object to draw to the BitmapData object. (The DisplayObject and BitmapData classes implement the IBitmapDrawable interface.)
* @param colorTransform_ A ColorTransform object that you use to adjust the color values of the bitmap. If no object is supplied, the bitmap image's colors are not transformed
* @param blendMode_ A string value, from the flash.display.BlendMode class, specifying the blend mode to be applied to the resulting bitmap.
* @param clipRect_ A Rectangle object that defines the area of the source object to draw. If you do not supply this value, no clipping occurs and the entire source object is drawn.
* @param smoothing_ A Boolean value that determines whether a BitmapData object is smoothed
*/
public function draw(source_ : IBitmapDrawable, matrix_ : Matrix = null, colorTransform_ : ColorTransform = null, blendMode_ : String = null, clipRect_:Rectangle = null, smoothing_ : Boolean = false) : void
{
var srcRect : Rectangle;
if (source_ is BitmapData) srcRect = (source_ as BitmapData).rect.clone();
else if (source_ is DisplayObject) srcRect = (source_ as DisplayObject).getBounds(source_ as DisplayObject);
if(srcRect)
{
var x : int = (clipRect_) ? clipRect_.x : 0;
var y : int = (clipRect_) ? clipRect_.y : 0;
var clipWidth : int = (clipRect_) ? clipRect_.right : _bitmapData.width;
var clipHeight : int = (clipRect_) ? clipRect_.bottom : _bitmapData.height;
var xMax : int = Math.min(srcRect.right, clipWidth);
var yMax : int = Math.min(srcRect.bottom, clipHeight);
var matrix : Matrix;
var chunk : BitmapData;
var clip : Rectangle = new Rectangle();
if(matrix_) {
xMax *= matrix_.a;
yMax *= matrix_.d;
}
while(x < xMax)
{
while(y < yMax)
{
matrix = new Matrix();
if(matrix_) {
matrix.a = matrix_.a;
matrix.d = matrix_.d;
}
matrix.translate(-x, -y);
clip.width = (xMax - x >= DRAW_LIMIT) ? DRAW_LIMIT : xMax - x;
clip.height = (yMax - y >= DRAW_LIMIT) ? DRAW_LIMIT : yMax - y ;
// use source
if(x == 0 && y == 0)
{
_bitmapData.draw(source_, matrix, colorTransform_, blendMode_, clip, smoothing_);
}
// copy to chunk first
else
{
if(!chunk) chunk = _bitmapData.clone();
chunk.fillRect(chunk.rect, (!_transparent) ? _fillColor : 0x00000000 );
chunk.draw(source_, matrix, colorTransform_, blendMode_, clip, smoothing_);
_bitmapData.copyPixels(chunk, chunk.rect, new Point(x, y), null, null, true);
}
y += DRAW_LIMIT;
}
x += DRAW_LIMIT;
y = 0;
}
if(chunk)
{
chunk.dispose();
chunk = null;
}
}
}
private function onLoaderComplete(event : Event) : void
{
var ok:Boolean = true;
try
{
_bitmapData = Bitmap(_loader.content).bitmapData.clone();
if(!_transparent) _bitmapData.fillRect(_bitmapData.rect, _fillColor);
}
catch(error : ArgumentError)
{
ok = false;
dispatchEvent(new BitmapDataUnlimitedEvent(BitmapDataUnlimitedEvent.ERROR));
}
_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoaderComplete);
_loader = null;
if(ok) dispatchComplete();
}
private function dispatchComplete() : void
{
dispatchEvent(new BitmapDataUnlimitedEvent(BitmapDataUnlimitedEvent.COMPLETE));
}
}
}
================================================
FILE: flash/src/com/image/formatlos/Gif.as
================================================
/*
Copyright (c) 2008 Martin Raedlinger (mr@formatlos.de)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package com.image.formatlos
{
import flash.utils.ByteArray;
/**
* The Gif Class creates an empty gif image
*
* @author Martin Raedlinger
*/
public class Gif
{
private var _width : int;
private var _height : int;
private var _colorTable : ByteArray;
private var _colorTableSize : int = 7;
private var _transparent : Boolean;
private var _transparentIndex : int = 0;
private var _fillColor : uint;
// binary gif data
private var _binaryGif : ByteArray;
/**
* Returns the created binary gif data
*
* @return binary gif data
*/
public function get bytes() : ByteArray
{
return _binaryGif;
}
public function Gif(width_ : int, height_ : int, transparent_ : Boolean = false, fillColor_ : uint = 4.294967295E9)
{
_width = width_;
_height = height_;
_transparent = transparent_;
_fillColor = fillColor_;
initialize();
}
private function initialize() : void
{
_binaryGif = new ByteArray();
writeHeader();
writeLogicalScreenDescriptor();
writeColorTable();
writeGraphicControlExtensionBlock();
writeImageBlock();
writeTrailer();
}
private function writeHeader() : void
{
_binaryGif.writeUTFBytes("GIF89a");
}
private function writeLogicalScreenDescriptor() : void
{
// size
writeShort(_width);
writeShort(_height);
// Packed Fields
// bit 0: Global Color Table Flag (GCTF)
// bit 1..3: Color Resolution
// bit 4: Sort Flag to Global Color Table
// bit 5..7: Size of Global Color Table: 2^(1+n)
_binaryGif.writeByte((0x80 | 0x70 | 0x00 | _colorTableSize));
// Background Color Index
_binaryGif.writeByte(0);
// Pixel Aspect Ratio
_binaryGif.writeByte(0); //
}
private function writeColorTable() : void
{
_colorTable = new ByteArray();
//_colorTable[0] = 0xFF0000 >> 16;
//_colorTable[1] = 0x00FF00 >> 8;
//_colorTable[2] = 0x0000FF;
_colorTable[0] = _fillColor >> 16 & 0xFF;
_colorTable[1] = _fillColor >> 8 & 0xFF;
_colorTable[2] = _fillColor & 0xFF;
_binaryGif.writeBytes(_colorTable, 0, _colorTable.length);
var i : int = 0;
var n : int = (3 * 256) - _colorTable.length;
while(i < n)
{
_binaryGif.writeByte(0);
++i;
}
}
private function writeGraphicControlExtensionBlock() : void
{
// Extension Introducer
_binaryGif.writeByte(0x21);
// Graphic Control Label
_binaryGif.writeByte(0xf9);
// Block Size
_binaryGif.writeByte(4);
var transparent : int;
var dispose : int;
if (_transparent)
{
transparent = 1;
dispose = 2;
}
else
{
transparent = 0;
dispose = 0;
}
dispose <<= 2;
// Packed Fields
// bit 0..2: Reserved
// bit 3..5: Disposal Method
// bit 6: User Input Flag
// bit 7: Transparent Color Flag
_binaryGif.writeByte(0 | dispose | 0 | transparent);
// Delay Time
writeShort(0);
// Transparent Color Index
_binaryGif.writeByte(_transparentIndex);
// Block Terminator
_binaryGif.writeByte(0);
}
private function writeImageBlock() : void
{
//Image Separator
_binaryGif.writeByte(0x2c);
// Image Left Position
writeShort(0);
// image position x,y = 0,0
// Image Top Position
writeShort(0);
// Image Width
writeShort(_width);
// Image Height
writeShort(_height);
// Packed Fields
_binaryGif.writeByte(0);
}
private function writeTrailer() : void
{
_binaryGif.writeByte(0x3b);
}
private function writeShort(pValue : int) : void
{
_binaryGif.writeByte(pValue & 0xFF);
_binaryGif.writeByte((pValue >> 8) & 0xFF);
}
}
}
================================================
FILE: flash/src/com/image/formatlos/events/BitmapDataUnlimitedEvent.as
================================================
/*
Copyright (c) 2008 Martin Raedlinger (mr@formatlos.de)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package com.image.formatlos.events
{
import flash.events.Event;
/**
* @author Martin Raedlinger
*/
public class BitmapDataUnlimitedEvent extends Event
{
public static const COMPLETE : String = "bitmapDataComplete";
public static const ERROR : String = "bitmapDataError";
public function BitmapDataUnlimitedEvent(type : String, bubbles : Boolean = false, cancelable : Boolean = false)
{
super(type, bubbles, cancelable);
}
override public function clone() : Event
{
return new BitmapDataUnlimitedEvent(type, bubbles, cancelable);
}
}
}
================================================
FILE: flash/src/com/utils/BMPDecoder.as
================================================
package com.utils {
import flash.display.BitmapData;
import flash.errors.IOError;
import flash.utils.ByteArray;
import flash.utils.Endian;
public class BMPDecoder {
//___________________________________________________________ const
private const BITMAP_HEADER_TYPE:String = "BM";
private const BITMAP_FILE_HEADER_SIZE:int = 14;
private const BITMAP_CORE_HEADER_SIZE:int = 12;
private const BITMAP_INFO_HEADER_SIZE:int = 40;
private const COMP_RGB :int = 0;
private const COMP_RLE8 :int = 1;
private const COMP_RLE4 :int = 2;
private const COMP_BITFIELDS:int = 3;
private const BIT1 :int = 1;
private const BIT4 :int = 4;
private const BIT8 :int = 8;
private const BIT16:int = 16;
private const BIT24:int = 24;
private const BIT32:int = 32;
//___________________________________________________________ vars
private var bytes:ByteArray;
private var palette:Array;
private var bd:BitmapData;
private var nFileSize:uint;
private var nReserved1:uint;
private var nReserved2:uint;
private var nOffbits:uint;
private var nInfoSize:uint;
private var nWidth:int;
private var nHeight:int;
private var nPlains:uint;
private var nBitsPerPixel:uint;
private var nCompression:uint;
private var nSizeImage:uint;
private var nXPixPerMeter:int;
private var nYPixPerMeter:int;
private var nColorUsed:uint;
private var nColorImportant:uint;
private var nRMask:uint;
private var nGMask:uint;
private var nBMask:uint;
private var nRPos:uint;
private var nGPos:uint;
private var nBPos:uint;
private var nRMax:uint;
private var nGMax:uint;
private var nBMax:uint;
/**
* コンストラクタ
*/
public function BMPDecoder() {
nRPos = 0;
nGPos = 0;
nBPos = 0;
}
/**
* デコード
*
* @param デコードしたいBMPファイルのバイナリデータ
*/
public function decode( data:ByteArray ):BitmapData {
bytes = data;
bytes.endian = Endian.LITTLE_ENDIAN;
bytes.position = 0;
readFileHeader();
nInfoSize = bytes.readUnsignedInt();
switch ( nInfoSize ) {
case BITMAP_CORE_HEADER_SIZE:
readCoreHeader();
break;
case BITMAP_INFO_HEADER_SIZE:
readInfoHeader();
break;
default:
readExtendedInfoHeader();
break;
}
bd = new BitmapData( nWidth, nHeight );
switch ( nBitsPerPixel ){
case BIT1:
readColorPalette();
decode1BitBMP();
break;
case BIT4:
readColorPalette();
if ( nCompression == COMP_RLE4 ){
decode4bitRLE();
} else {
decode4BitBMP();
}
break;
case BIT8:
readColorPalette();
if ( nCompression == COMP_RLE8 ){
decode8BitRLE();
} else {
decode8BitBMP();
}
break;
case BIT16:
readBitFields();
checkColorMask();
decode16BitBMP();
break;
case BIT24:
decode24BitBMP();
break;
case BIT32:
readBitFields();
checkColorMask();
decode32BitBMP();
break;
default:
throw new VerifyError("invalid bits per pixel : " + nBitsPerPixel );
}
return bd;
}
/**
* BITMAP FILE HEADER 読み込み
*/
private function readFileHeader():void {
var fileHeader:ByteArray = new ByteArray();
fileHeader.endian = Endian.LITTLE_ENDIAN;
try {
bytes.readBytes( fileHeader, 0, BITMAP_FILE_HEADER_SIZE );
if ( fileHeader.readUTFBytes( 2 ) != BITMAP_HEADER_TYPE ){
throw new VerifyError("invalid bitmap header type");
}
nFileSize = fileHeader.readUnsignedInt();
nReserved1 = fileHeader.readUnsignedShort();
nReserved2 = fileHeader.readUnsignedShort();
nOffbits = fileHeader.readUnsignedInt();
} catch ( e:IOError ) {
throw new VerifyError("invalid file header");
}
}
/**
* BITMAP CORE HEADER 読み込み
*/
private function readCoreHeader():void {
var coreHeader:ByteArray = new ByteArray();
coreHeader.endian = Endian.LITTLE_ENDIAN;
try {
bytes.readBytes( coreHeader, 0, BITMAP_CORE_HEADER_SIZE - 4 );
nWidth = coreHeader.readShort();
nHeight = coreHeader.readShort();
nPlains = coreHeader.readUnsignedShort();
nBitsPerPixel = coreHeader.readUnsignedShort();
} catch ( e:IOError ) {
throw new VerifyError("invalid core header");
}
}
/**
* BITMAP INFO HEADER 読み込み
*/
private function readInfoHeader():void {
var infoHeader:ByteArray = new ByteArray();
infoHeader.endian = Endian.LITTLE_ENDIAN;
try {
bytes.readBytes( infoHeader, 0, BITMAP_INFO_HEADER_SIZE - 4 );
nWidth = infoHeader.readInt();
nHeight = infoHeader.readInt();
nPlains = infoHeader.readUnsignedShort();
nBitsPerPixel = infoHeader.readUnsignedShort();
nCompression = infoHeader.readUnsignedInt();
nSizeImage = infoHeader.readUnsignedInt();
nXPixPerMeter = infoHeader.readInt();
nYPixPerMeter = infoHeader.readInt();
nColorUsed = infoHeader.readUnsignedInt();
nColorImportant = infoHeader.readUnsignedInt();
} catch ( e:IOError ) {
throw new VerifyError("invalid info header");
}
}
/**
* 拡張 BITMAP INFO HEADER 読み込み
*/
private function readExtendedInfoHeader():void {
var infoHeader:ByteArray = new ByteArray();
infoHeader.endian = Endian.LITTLE_ENDIAN;
try {
bytes.readBytes( infoHeader, 0, nInfoSize - 4 );
nWidth = infoHeader.readInt();
nHeight = infoHeader.readInt();
nPlains = infoHeader.readUnsignedShort();
nBitsPerPixel = infoHeader.readUnsignedShort();
nCompression = infoHeader.readUnsignedInt();
nSizeImage = infoHeader.readUnsignedInt();
nXPixPerMeter = infoHeader.readInt();
nYPixPerMeter = infoHeader.readInt();
nColorUsed = infoHeader.readUnsignedInt();
nColorImportant = infoHeader.readUnsignedInt();
if ( infoHeader.bytesAvailable >= 4 ) nRMask = infoHeader.readUnsignedInt();
if ( infoHeader.bytesAvailable >= 4 ) nGMask = infoHeader.readUnsignedInt();
if ( infoHeader.bytesAvailable >= 4 ) nBMask = infoHeader.readUnsignedInt();
} catch ( e:IOError ) {
throw new VerifyError("invalid info header");
}
}
/**
* ビットフィールド読み込み
*/
private function readBitFields():void {
if ( nCompression == COMP_RGB ){
if ( nBitsPerPixel == BIT16 ){
// RGB555
nRMask = 0x00007c00;
nGMask = 0x000003e0;
nBMask = 0x0000001f;
} else {
//RGB888;
nRMask = 0x00ff0000;
nGMask = 0x0000ff00;
nBMask = 0x000000ff;
}
} else if ( ( nCompression == COMP_BITFIELDS ) && ( nInfoSize < 52 ) ){
try {
nRMask = bytes.readUnsignedInt();
nGMask = bytes.readUnsignedInt();
nBMask = bytes.readUnsignedInt();
} catch ( e:IOError ) {
throw new VerifyError("invalid bit fields");
}
}
}
/**
* カラーパレット読み込み
*/
private function readColorPalette():void {
var i:int;
var len:int = ( nColorUsed > 0 ) ? nColorUsed : Math.pow( 2, nBitsPerPixel );
palette = new Array( len );
for ( i = 0; i < len; ++i ){
palette[ i ] = bytes.readUnsignedInt();
}
}
/**
* 1bitのBMPデコード
*/
private function decode1BitBMP():void {
var x:int;
var y:int;
var i:int;
var col:int;
var buf:ByteArray = new ByteArray();
var line:int = nWidth / 8;
if ( line % 4 > 0 ){
line = ( ( line / 4 | 0 ) + 1 ) * 4;
}
try {
for ( y = nHeight - 1; y >= 0; --y ){
buf.length = 0;
bytes.readBytes( buf, 0, line );
for ( x = 0; x < nWidth; x += 8 ){
col = buf.readUnsignedByte();
for ( i = 0; i < 8; ++i ){
bd.setPixel( x + i, y, palette[ col >> ( 7 - i ) & 0x01 ] );
}
}
}
} catch ( e:IOError ) {
throw new VerifyError("invalid image data");
}
}
/**
* 4bitのRLE圧縮BMPデコード
*/
private function decode4bitRLE():void {
var x:int;
var y:int;
var i:int;
var n:int;
var col:int;
var data:uint;
var buf:ByteArray = new ByteArray();
try {
for ( y = nHeight - 1; y >= 0; --y ){
buf.length = 0;
while ( bytes.bytesAvailable > 0 ){
n = bytes.readUnsignedByte();
if ( n > 0 ){
// エンコードデータ
data = bytes.readUnsignedByte();
for ( i = 0; i < n/2; ++i ){
buf.writeByte( data );
}
} else {
n = bytes.readUnsignedByte();
if ( n > 0 ){
// 絶対モードデータ
bytes.readBytes( buf, buf.length, n/2 );
buf.position += n/2;
if ( n/2 + 1 >> 1 << 1 != n/2 ){
bytes.readUnsignedByte();
}
} else {
// EOL
break;
}
}
}
buf.position = 0;
for ( x = 0; x < nWidth; x += 2 ){
col = buf.readUnsignedByte();
bd.setPixel( x, y, palette[ col >> 4 ] );
bd.setPixel( x + 1, y, palette[ col & 0x0f ] );
}
}
} catch ( e:IOError ) {
throw new VerifyError("invalid image data");
}
}
/**
* 4bitの非圧縮BMPデコード
*/
private function decode4BitBMP():void {
var x:int;
var y:int;
var i:int;
var col:int;
var buf:ByteArray = new ByteArray();
var line:int = nWidth / 2;
if ( line % 4 > 0 ){
line = ( ( line / 4 | 0 ) + 1 ) * 4;
}
try {
for ( y = nHeight - 1; y >= 0; --y ){
buf.length = 0;
bytes.readBytes( buf, 0, line );
for ( x = 0; x < nWidth; x += 2 ){
col = buf.readUnsignedByte();
bd.setPixel( x, y, palette[ col >> 4 ] );
bd.setPixel( x + 1, y, palette[ col & 0x0f ] );
}
}
} catch ( e:IOError ) {
throw new VerifyError("invalid image data");
}
}
/**
* 8bitのRLE圧縮BMPデコード
*/
private function decode8BitRLE():void {
var x:int;
var y:int;
var i:int;
var n:int;
var col:int;
var data:uint;
var buf:ByteArray = new ByteArray();
try {
for ( y = nHeight - 1; y >= 0; --y ){
buf.length = 0;
while ( bytes.bytesAvailable > 0 ){
n = bytes.readUnsignedByte();
if ( n > 0 ){
// エンコードデータ
data = bytes.readUnsignedByte();
for ( i = 0; i < n; ++i ){
buf.writeByte( data );
}
} else {
n = bytes.readUnsignedByte();
if ( n > 0 ){
// 絶対モードデータ
bytes.readBytes( buf, buf.length, n );
buf.position += n;
if ( n + 1 >> 1 << 1 != n ){
bytes.readUnsignedByte();
}
} else {
// EOL
break;
}
}
}
buf.position = 0;
for ( x = 0; x < nWidth; ++x ){
bd.setPixel( x, y, palette[ buf.readUnsignedByte() ] );
}
}
} catch ( e:IOError ) {
throw new VerifyError("invalid image data");
}
}
/**
* 8bitの非圧縮BMPデコード
*/
private function decode8BitBMP():void {
var x:int;
var y:int;
var i:int;
var col:int;
var buf:ByteArray = new ByteArray();
var line:int = nWidth;
if ( line % 4 > 0 ){
line = ( ( line / 4 | 0 ) + 1 ) * 4;
}
try {
for ( y = nHeight - 1; y >= 0; --y ){
buf.length = 0;
bytes.readBytes( buf, 0, line );
for ( x = 0; x < nWidth; ++x ){
bd.setPixel( x, y, palette[ buf.readUnsignedByte() ] );
}
}
} catch ( e:IOError ) {
throw new VerifyError("invalid image data");
}
}
/**
* 16bitのBMPデコード
*/
private function decode16BitBMP():void {
var x:int;
var y:int;
var col:int;
try {
for ( y = nHeight - 1; y >= 0; --y ){
for ( x = 0; x < nWidth; ++x ){
col = bytes.readUnsignedShort();
bd.setPixel( x, y, ( ( ( col & nRMask ) >> nRPos )*0xff/nRMax << 16 ) + ( ( ( col & nGMask ) >> nGPos )*0xff/nGMax << 8 ) + ( ( ( col & nBMask ) >> nBPos )*0xff/nBMax << 0 ) );
}
}
} catch ( e:IOError ) {
throw new VerifyError("invalid image data");
}
}
/**
* 24bitのBMPデコード
*/
private function decode24BitBMP():void {
var x:int;
var y:int;
var col:int;
var buf:ByteArray = new ByteArray();
var line:int = nWidth * 3;
if ( line % 4 > 0 ){
line = ( ( line / 4 | 0 ) + 1 ) * 4;
}
try {
for ( y = nHeight - 1; y >= 0; --y ){
buf.length = 0;
bytes.readBytes( buf, 0, line );
for ( x = 0; x < nWidth; ++x ){
bd.setPixel( x, y, buf.readUnsignedByte() + ( buf.readUnsignedByte() << 8 ) + ( buf.readUnsignedByte() << 16 ) );
}
}
} catch ( e:IOError ) {
throw new VerifyError("invalid image data");
}
}
/**
* 32bitのBMPデコード
*/
private function decode32BitBMP():void {
var x:int;
var y:int;
var col:int;
try {
for ( y = nHeight - 1; y >= 0; --y ){
for ( x = 0; x < nWidth; ++x ){
col = bytes.readUnsignedInt();
bd.setPixel( x, y, ( ( ( col & nRMask ) >> nRPos )*0xff/nRMax << 16 ) + ( ( ( col & nGMask ) >> nGPos )*0xff/nGMax << 8 ) + ( ( ( col & nBMask ) >> nBPos )*0xff/nBMax << 0 ) );
}
}
} catch ( e:IOError ) {
throw new VerifyError("invalid image data");
}
}
/**
* カラーマスクチェック
*/
private function checkColorMask():void {
if ( ( nRMask & nGMask ) | ( nGMask & nBMask ) | ( nBMask & nRMask ) ){
throw new VerifyError("invalid bit fields");
}
while ( ( ( nRMask >> nRPos ) & 0x00000001 ) == 0 ){
nRPos++;
}
while ( ( ( nGMask >> nGPos ) & 0x00000001 ) == 0 ){
nGPos++;
}
while ( ( ( nBMask >> nBPos ) & 0x00000001 ) == 0 ){
nBPos++;
}
nRMax = nRMask >> nRPos;
nGMax = nGMask >> nGPos;
nBMax = nBMask >> nBPos;
}
/**
* 情報出力
*/
public function traceInfo():void {
trace("---- FILE HEADER ----");
trace("nFileSize: " + nFileSize );
trace("nReserved1: " + nReserved1 );
trace("nReserved2: " + nReserved2 );
trace("nOffbits: " + nOffbits );
trace("---- INFO HEADER ----");
trace("nWidth: " + nWidth );
trace("nHeight: " + nHeight );
trace("nPlains: " + nPlains );
trace("nBitsPerPixel: " + nBitsPerPixel );
if ( nInfoSize >= 40 ){
trace("nCompression: " + nCompression );
trace("nSizeImage: " + nSizeImage );
trace("nXPixPerMeter: " + nXPixPerMeter );
trace("nYPixPerMeter: " + nYPixPerMeter );
trace("nColorUsed: " + nColorUsed );
trace("nColorUsed: " + nColorImportant );
}
if ( nInfoSize >= 52 ){
trace("nRMask: " + nRMask.toString( 2 ) );
trace("nGMask: " + nGMask.toString( 2 ) );
trace("nBMask: " + nBMask.toString( 2 ) );
}
}
}
}
================================================
FILE: flash/src/com/utils/Base64.as
================================================
/*
* Copyright (C) 2012 Jean-Philippe Auclair
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
* Base64 library for ActionScript 3.0.
* By: Jean-Philippe Auclair : http://jpauclair.net
* Based on article: http://jpauclair.net/2010/01/09/base64-optimized-as3-lib/
* Benchmark:
* This version: encode: 260ms decode: 255ms
* Blog version: encode: 322ms decode: 694ms
* as3Crypto encode: 6728ms decode: 4098ms
*
* Encode: com.sociodox.utils.Base64 is 25.8x faster than as3Crypto Base64
* Decode: com.sociodox.utils.Base64 is 16x faster than as3Crypto Base64
*
* Optimize & Profile any Flash content with TheMiner ( http://www.sociodox.com/theminer )
*/
package com.utils
{
import flash.utils.ByteArray;
public class Base64
{
private static const _encodeChars:Vector. = InitEncoreChar();
private static const _decodeChars:Vector. = InitDecodeChar();
public static function encode(data:ByteArray):String
{
var out:ByteArray = new ByteArray();
//Presetting the length keep the memory smaller and optimize speed since there is no "grow" needed
out.length = (2 + data.length - ((data.length + 2) % 3)) * 4 / 3; //Preset length //1.6 to 1.5 ms
var i:int = 0;
var r:int = data.length % 3;
var len:int = data.length - r;
var c:uint; //read (3) character AND write (4) characters
var outPos:int = 0;
while (i < len)
{
//Read 3 Characters (8bit * 3 = 24 bits)
c = data[int(i++)] << 16 | data[int(i++)] << 8 | data[int(i++)];
out[int(outPos++)] = _encodeChars[int(c >>> 18)];
out[int(outPos++)] = _encodeChars[int(c >>> 12 & 0x3f)];
out[int(outPos++)] = _encodeChars[int(c >>> 6 & 0x3f)];
out[int(outPos++)] = _encodeChars[int(c & 0x3f)];
}
if (r == 1) //Need two "=" padding
{
//Read one char, write two chars, write padding
c = data[int(i)];
out[int(outPos++)] = _encodeChars[int(c >>> 2)];
out[int(outPos++)] = _encodeChars[int((c & 0x03) << 4)];
out[int(outPos++)] = 61;
out[int(outPos++)] = 61;
}
else if (r == 2) //Need one "=" padding
{
c = data[int(i++)] << 8 | data[int(i)];
out[int(outPos++)] = _encodeChars[int(c >>> 10)];
out[int(outPos++)] = _encodeChars[int(c >>> 4 & 0x3f)];
out[int(outPos++)] = _encodeChars[int((c & 0x0f) << 2)];
out[int(outPos++)] = 61;
}
return out.readUTFBytes(out.length);
}
public static function decode(str:String):ByteArray
{
var c1:int;
var c2:int;
var c3:int;
var c4:int;
var i:int = 0;
var len:int = str.length;
var byteString:ByteArray = new ByteArray();
byteString.writeUTFBytes(str);
var outPos:int = 0;
while (i < len)
{
//c1
c1 = _decodeChars[int(byteString[i++])];
if (c1 == -1)
break;
//c2
c2 = _decodeChars[int(byteString[i++])];
if (c2 == -1)
break;
byteString[int(outPos++)] = (c1 << 2) | ((c2 & 0x30) >> 4);
//c3
c3 = byteString[int(i++)];
if (c3 == 61)
{
byteString.length = outPos
return byteString;
}
c3 = _decodeChars[int(c3)];
if (c3 == -1)
break;
byteString[int(outPos++)] = ((c2 & 0x0f) << 4) | ((c3 & 0x3c) >> 2);
//c4
c4 = byteString[int(i++)];
if (c4 == 61)
{
byteString.length = outPos
return byteString;
}
c4 = _decodeChars[int(c4)];
if (c4 == -1)
break;
byteString[int(outPos++)] = ((c3 & 0x03) << 6) | c4;
}
byteString.length = outPos
return byteString;
}
public static function InitEncoreChar():Vector.
{
var encodeChars:Vector. = new Vector.(64, true);
// We could push the number directly
// but I think it's nice to see the characters (with no overhead on encode/decode)
var chars:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
for (var i:int = 0; i < 64; i++)
{
encodeChars[i] = chars.charCodeAt(i);
}
return encodeChars;
}
public static function InitDecodeChar():Vector.
{
var decodeChars:Vector. = new [
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1];
return decodeChars;
}
}
}
================================================
FILE: flash/src/com/utils/BinaryReader.as
================================================
/**
*
* Copyright 2011, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
package com.utils {
import flash.utils.ByteArray;
import flash.utils.Endian;
public class BinaryReader extends ByteArray {
public function init(binData:ByteArray):void {
clear();
endian = Endian.BIG_ENDIAN;
writeBytes(binData);
}
public function II(... args):* {
if (!args.length)
return endian == Endian.LITTLE_ENDIAN ? true : false;
else
endian = args[0] == true ? Endian.LITTLE_ENDIAN : Endian.BIG_ENDIAN;
}
public function SEGMENT(... args):ByteArray {
var seg:ByteArray = new ByteArray();
switch (args.length) {
case 1:
position = args[0];
readBytes(seg, 0);
break;
case 2:
position = args[0];
readBytes(seg, 0, args[1]);
break;
case 3:
seg.writeBytes(this, 0, args[0]);
if (args[2] is ByteArray) {
seg.writeBytes(args[2]);
}
seg.writeBytes(this, args[0] + args[1]);
clear();
writeBytes(seg);
seg.clear();
return null;
default:
seg.writeBytes(this);
}
return seg;
}
public function BYTE(idx:int):uint {
position = idx;
return readUnsignedByte();
}
public function SHORT(idx:int):uint {
position = idx;
return readUnsignedShort();
}
public function LONG(idx:int, ... args):* {
position = idx;
if (!args.length)
return readUnsignedInt();
else
writeUnsignedInt(args[0]);
}
public function SLONG(idx:uint):int {
position = idx;
return readInt();
}
public function STRING(idx:uint, size:uint):String {
position = idx;
return readUTFBytes(size);
}
}
}
================================================
FILE: flash/src/com/utils/Buffer.as
================================================
package com.utils
{
import flash.net.FileReference;
import flash.utils.ByteArray;
public class Buffer
{
private var _data:ByteArray;
public function get data() : ByteArray {
if (_fileRef && _fileRef.data) {
_data = _fileRef.data
}
return _data;
}
private var _fileRef:FileReference;
public function get fileRef() : FileReference {
return _fileRef;
}
public function get size() : uint {
if (_fileRef) {
return _fileRef.size;
} else if (_data) {
return _data.length;
}
return 0;
}
public var refs:uint = 1; // counting references to this object
public function Buffer(source:*)
{
if (source is FileReference) {
_fileRef = source;
} else if (source is ByteArray) {
_data = source;
} else {
// throw wrong type exception
}
}
public function isEmpty() : Boolean
{
return !_data || !_data.length;
}
public function purge() : void {
if (_fileRef && _fileRef.data.length) {
_fileRef.data.clear();
}
}
public function destroy() : void {
if (_data && _data.length) {
_data.clear();
}
purge();
}
}
}
================================================
FILE: flash/src/com/utils/OEventDispatcher.as
================================================
package com.utils
{
import flash.events.EventDispatcher;
public class OEventDispatcher extends EventDispatcher
{
private var _events:Object = [];
public override function addEventListener(type:String, callback:Function, useCapture:Boolean = false, priority:int = 0, useWeak:Boolean = false) : void
{
if (hasListener(type, callback, useCapture)) {
return;
}
_events.push({
type: type,
callback: callback,
useCapture: useCapture
});
super.addEventListener(type, callback, useCapture, priority, useWeak);
}
public override function removeEventListener(type:String, callback:Function, useCapture:Boolean=false):void
{
var index:uint, e:Object;
index = hasListener(type, callback, useCapture);
if (index === false) {
return;
}
e = _events.splice(index, 1);
super.removeEventListener(e.type, e.callback, e.useCapture);
}
public function hasListener(type:String, callback:Function = null, useCapture:Boolean = false): *
{
for (var i:uint = 0, length:uint = _events.length; i < length; i++) {
if (type == _events[i].type && callback == _events[i].callback && _events[i].useCapture == useCapture) {
return i;
}
}
return false;
}
/* anyone any idea why Flash doesn't have a call like this?.. */
public function removeAllEventsListeners() : void
{
for (var i:uint = 0, length:uint = _events.length; i < length; i++) {
super.removeEventListener(_events[i].type, _events[i].callback, _events[i].useCapture); // call super method directly
}
_events = [];
}
}
}
================================================
FILE: flash/src/com/utils/URLStreamProgress.as
================================================
package com.utils
{
import com.events.URLStreamProgressEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.events.TimerEvent;
import flash.external.ExternalInterface;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLRequestMethod;
import flash.net.URLStream;
import flash.utils.ByteArray;
import flash.utils.Timer;
public class URLStreamProgress extends OEventDispatcher
{
private var _options:Object = {};
public static var speed:uint = 512000; // number of bytes per 500ms
public static var rate:uint = 50;
private var _progressTimer:Timer;
private var _bytesLoaded:uint = 0;
private var _bytesTotal:uint = 0;
public function URLStreamProgress(options:Object = null)
{
_options = Utils.extend({
url: 'webuploader' + new Date().getTime(),
size: 307200
}, options);
}
public static function calculateSpeed(size:uint, time:uint) : void
{
URLStreamProgress.speed = Math.ceil(size * URLStreamProgress.rate / Math.max(time - 30, 3));
}
public function start(bytesTotal:uint) : void
{
var onProgress:Function;
if (!URLStreamProgress.speed) {
addEventListener(URLStreamProgressEvent.PROBE_COMPLETE, function() : void {
start(bytesTotal);
}, false, 0, true);
probe();
return;
}
dispatchEvent(new Event(Event.OPEN));
_bytesTotal = bytesTotal;
onProgress = function() : void {
_bytesLoaded += URLStreamProgress.speed;
if (_bytesLoaded < _bytesTotal) {
dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS, false, false, _bytesLoaded, _bytesTotal));
} else {
dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS, false, false, _bytesTotal, _bytesTotal));
stop();
dispatchEvent(new Event(Event.COMPLETE));
}
};
_progressTimer = new Timer(URLStreamProgress.rate);
_progressTimer.addEventListener(TimerEvent.TIMER, onProgress, false, 0, true);
_progressTimer.start();
}
public function stop() : void
{
if (_progressTimer) {
_progressTimer.stop();
_bytesLoaded = _bytesTotal = 0;
}
}
public function probe() : void
{
var stream:URLStream, request:URLRequest,
onComplete:Function,
start:Date, end:Date;
request = new URLRequest(_options.url);
request.method = URLRequestMethod.POST;
request.data = _generateByteArray(_options.size);
start = new Date;
onComplete = function(e:* = null) : void {
end = new Date;
URLStreamProgress.calculateSpeed(_options.size, end.time - start.time);
dispatchEvent(new URLStreamProgressEvent(URLStreamProgressEvent.PROBE_COMPLETE));
};
stream = new URLStream;
stream.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
stream.addEventListener(IOErrorEvent.IO_ERROR, onComplete, false, 0, true);
stream.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onComplete, false, 0, true);
stream.load(request);
}
private function _generateByteArray(size:uint = 307200) : ByteArray
{
var ba:ByteArray, replicator:ByteArray;
ba = new ByteArray;
replicator = new ByteArray;
replicator.writeByte(0xE0);
replicator.writeByte(0xA5);
replicator.writeByte(0x90);
size = Math.ceil(size / replicator.length);
for (var i:uint = 0; i < size; i++) {
ba.writeBytes(replicator);
}
return ba;
}
}
}
================================================
FILE: flash/src/com/utils/Utils.as
================================================
package com.utils
{
public class Utils
{
static public function trim(str:String) : String
{
if (!str) return '';
return str.replace(/^\s+/, '').replace(/\s+$/, '');
}
static public function sanitize(str:String) : String
{
// allow only [a-zA-Z0-9_]
return str.replace(/[^\w]/g, '');
}
static private var _guidCounter:uint = 0;
static public function guid(prefix:String = '') : String
{
var guid:String = new Date().getTime().toString(32), i:int;
for (i = 0; i < 5; i++) {
guid += Math.floor(Math.random() * 65535).toString(32);
}
return (prefix || 'o_') + guid + (_guidCounter++).toString(32);
}
static public function extend(obj1:*, obj2:*, strict:Boolean = false, propsOnly:Boolean = true) : *
{
if (!obj1)
obj1 = {};
for (var key:String in obj2) {
if (propsOnly && obj2[key] is Function)
continue;
if (strict) {
if (obj1.hasOwnProperty(key))
obj1[key] = obj2[key];
} else {
obj1[key] = obj2[key];
}
}
return obj1;
}
static public function isTrue(value:String) : Boolean
{
if (!value) return false;
return ['1', 'true'].indexOf(value.toLowerCase()) !== -1 ? true : false;
}
static public function isFalse(value:String) : Boolean
{
return !Utils.isTrue(value);
}
static public function toHHIISS(seconds:Number) : String
{
var h:Number, i:Number, s:Number,
HHIISS:String,
padZero:Function = function(number:uint) : String {
return number > 9 ? number.toString() : '0' + number.toString();
};
s = seconds % 60;
i = Math.floor((seconds % 3600) / 60);
h = Math.floor(seconds / (3600));
HHIISS = padZero(s);
HHIISS = (i > 0 ? padZero(i) : '00') + ':' + HHIISS;
if (h > 0)
HHIISS = padZero(h) + ':' + HHIISS;
return HHIISS;
}
static public function isEmptyObj(o:Object) : Boolean {
var prop:*;
if (!o) {
return true;
}
for (prop in o) {
return false;
}
return true;
}
}
}
================================================
FILE: flash/src/com/utils/Zhenpin.as
================================================
package com.utils
{
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
public class Zhenpin
{
private static var sound:Sound;
private static var st:SoundChannel;
public static var hasStart:Boolean = false;
public function Zhenpin()
{
}
public static function start():void{
sound = new BlankSound();
sound.addEventListener(IOErrorEvent.IO_ERROR, onError);
st = sound.play();
st.addEventListener(Event.SOUND_COMPLETE, onComp);
hasStart = true;
}
private static function onComp(e:Event):void{
st.removeEventListener(Event.SOUND_COMPLETE, onComp);
st = sound.play();
st.addEventListener(Event.SOUND_COMPLETE, onComp);
}
private static function onError(e:Object):void{
}
}
}
================================================
FILE: jekyll/_config.yml
================================================
name: Web Uploader
markdown: redcarpet
redcarpet:
extensions:
- with_toc_data
- html_toc
highlighter: true
baseurl: /webuploader
exclude:
- node_modules
- README.md
================================================
FILE: jekyll/_includes/comments.html
================================================
{% if page.commentIssueId %}
{% endif %}
================================================
FILE: jekyll/_includes/footer.html
================================================
================================================
FILE: jekyll/_includes/header.html
================================================
{% for weight in (1..10) %} {% for post in site.pages %} {% if post.group == 'nav' and post.weight == weight %} {% if page.url == post.url %}{{post.navName}} {% else %}{{ post.navName }} {% endif %}{% endif %}{% endfor %}{% endfor %}
FAQ
================================================
FILE: jekyll/_layouts/default.html
================================================
{% if page.url == '/index.html' %}
{{ page.title }}
{% else %}
{{ page.title }} - {{ site.name }}
{% endif %}
{% for link in page.styles %}
{% endfor %}
{% include header.html %}
{{ content }}
{% include footer.html %}
{% for script in page.scripts %}
{% endfor %}
================================================
FILE: jekyll/_layouts/post.html
================================================
---
layout: default
---
{% if page.bannerTitle %}
{{ page.bannerTitle }}
{% for paragraph in page.bannerContents %}
{{ paragraph }}
{% endfor %}
{% endif %}
{% capture toc %}{{ page.content | fancytoc }}{% endcapture %}
{% if page.noToc == nil and toc != '' %}
{% if page.hideTitle == nil %}
{% endif %}
{{ content }}
{% include comments.html %}
{% else %}
{% if page.hideTitle == nil %}
{% endif %}
{{ content }}
{% include comments.html %}
{% endif %}
================================================
FILE: jekyll/_plugins/fancytoc.rb
================================================
module Jekyll
module FancyToCFilter
def fancytoc(input)
converter = Redcarpet::Markdown.new(Redcarpet::Render::HTML_TOC)
toc = converter.render(input)
toc.gsub(/
评论
如果是讨论技术问题或者报告bug,请最好还是新建一个issue展开讨论,以免你提出的问题石沉大海。
点此进入issues列表页。