这两天在做移动端上传头像功能,想对大于400kb的图片进行压缩再上传,压缩大于400kb的图片一直没成功,也没有报什么错误,后来我重新看了自己的代码,发现是因为当图片大小大于400kb的时候,压缩图片函数传入的base64Img参数我写错了,真的是太粗心,现在将正确的代码附上:uploadImg(){letvm=this;console.log(vm.temp);varimg=document.getElementById("phoneImage"),maxSize=400*1024;//400kbvarimgFile=newFileReader();imgFile.readAsDataURL(img.files[0]);imgFile.onload=function(){vm.temp.base64Img=imgFile.result;if(vm.temp.base64Img.length//图片直接上传 alert("<=100kb;size="+vm.temp.base64Img.length);uploadImage(vm.temp).then(response=>{constdata=response.data;vm.temp=data.data;setTimeout(()=>{vm.$router.push({path:"/setting"});window.location.reload();},5);});}else{//>400kb,压缩再上传vm.compress(vm.temp.base64Img,function(base64Img){uploadImage({base64Img}).then(response=>{constdata=response.data;setTimeout(()=>{vm.$router.push({path:"/setting"});window.location.reload();},5);});});}};},compress(base64Img,callback){varimg=newImage();img.src=base64Img;img.onload=function(){varwidth=img.width;varheight=img.height;varcanvas=document.createElement("canvas");canvas.width=width;canvas.height=height;canvas.getContext("2d").drawImage(img,0,0,width,height);callback(canvas.toDataURL("image/jpeg",0.05));};}
汪汪一只猫
相关分类