我想显示上载图像时的进度,上载未压缩的图像时工作正常。但是上载压缩后的图像,功能onuploadprogress仅运行一次。代码有什么问题吗?谢谢!
beforeupload:function(file){
var ready=new FileReader();
ready.readAsDataURL(file);
var that=this;
ready.onload=function(){
var img=new Image();
img.src=this.result;
img.onload=function(){
var img1=new Image();
var canvas=document.createElement("canvas");
var ctx=canvas.getContext('2d');
var sourcew=img.width;
var sourceh=img.height;
var scale=sourcew/sourceh;
var desw,desh;
if(sourcew>4000)
{
desw=4000;
desh=desw/scale;
}
else{
desw=sourcew;
desh=sourceh;
}
var w=document.createAttribute("width");
w.nodeValue=desw;
var h=document.createAttribute("height");
h.nodeValue=desh;
canvas.setAttributeNode(w);
canvas.setAttributeNode(h);
ctx.drawImage(this,0,0,desw,desh);
var base64=canvas.toDataURL('image/jpeg',1);
var arr=base64.split(','),mime=arr[0].match(/:(.*?);/)[1],
bstr=window.atob(arr[1]),n=bstr.length,u8arr=new Uint8Array(n);
for(var i=0;i<n;i++)
{
u8arr[i]=bstr.charCodeAt(i);
}
var file1=new File([u8arr],"newfile",{type:"image/jpeg"});
//that.form.append("file1",file,"file.jpg");//it work right;
that.form.append("file1",file1,"file1.jpg");//it work wrong;
var config={
headers:{"Content-type":"multipart/form-data"},
onUploadProgress:function(progress){
var percent=100*(progress.loaded/progress.total);
console.log(percent);
that.uploadpercent=percent;
},
onDownloadProgress:function(progress1){
console.log("downing");
},
};
that.$http.post("/Manager/postitem",that.form,config).then(response=>{alert("success");
that.num=0;that.current=0;that.form=new FormData();that.uploadpercent=0;}).catch(error=>{alert(error);});
}
}
return false;
}
文件未压缩,而file1已压缩。
使用时
that.form.append("file1",file,"file.jpg");
可以正常使用,而chrome日志:
14.657238452273665
30.857344110049823
47.05744976782598
64.0289890283534
80.22909468612954
96.4292003439057
100
使用时
that.form.append("file1",file1,"file1.jpg");
它无法正常工作,并且镀铬日志:
100