1 line
1.5 KiB
JavaScript
1 line
1.5 KiB
JavaScript
"use strict";define(function(){var e=function(){this.init()};return e.prototype={init:function(){return this.xhr=new XMLHttpRequest,this.form=new FormData,this.field={},this.header={},this},setUrl:function(e){return e&&"string"==typeof e?(this.url=e,this):console.error("url不能为空且必须是字符串")},setField:function(e,r){if("object"==typeof e)for(var t in e)this.field[t]=e[t];else this.field[e]=r;return this},setHeader:function(e,r){if("object"==typeof e)for(var t in e)this.header[t]=e[t];else this.header[e]=r;return this},start:function(){var e=this;if(!this.url)return console.error("请先设置url");this.xhr.open("POST",this.url,!0);for(var r in this.field)this.form.append(r,this.field[r]);var t=Date.now();this.xhr.upload.addEventListener("progress",function(r){if(r.lengthComputable&&e.progress){var s=Date.now(),i=1e3*r.loaded/1024,n={loaded:r.loaded,time:s-t};n.speed=i/n.time,n.speed<10?n.speed=Math.floor(1024*n.speed)+" B/s":n.speed=n.speed.toFixed(2)+" KB/s",n.progress=Math.round(100*r.loaded/r.total),e.progress(n)}},!1),this.xhr.onreadystatechange=function(){if(4===e.xhr.readyState&&200===e.xhr.status&&""!==e.xhr.responseText){var r=e.xhr.responseText;try{r=JSON.parse(r)}catch(e){}e.end&&e.end(r)}else 200!==e.xhr.status&&e.xhr.responseText&&e.error&&e.error(e.xhr.responseText)},this.xhr.send(this.form)},onProgress:function(e){return this.progress=e,this},onEnd:function(e){return this.end=e,this},onError:function(e){return this.error=e,this}},window.Uploader||(window.Uploader=e),e}); |
JavaScript
95.2%
CSS
4.8%