这两天在做移动端上传头像功能,想对大于400kb的图片进行压缩再上传,压缩大于400kb的图片一直没成功,也没有报什么错误,后来我重新看了自己的代码,发现是因为当图片大小大于400kb的时候,压缩图片函数传入的base64Img参数我写错了,真的是太粗心,现在将正确的代码附上:
uploadImg() {
let vm = this;
console.log(vm.temp);
var img = document.getElementById("phoneImage"),
maxSize = 400 * 1024; //400kb
var imgFile = new FileReader();
imgFile.readAsDataURL(img.files[0]);
imgFile.onload = function() {
vm.temp.base64Img = imgFile.result;
if (vm.temp.base64Img.length < maxSize) {
//图片直接上传
alert("<=100kb;size=" + vm.temp.base64Img.length);
uploadImage(vm.temp).then(response => {
const data = 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 => {
const data = response.data;
setTimeout(() => {
vm.$router.push({
path: "/setting"
});
window.location.reload();
}, 5);
});
});
}
};
},
compress(base64Img, callback) {
var img = new Image();
img.src = base64Img;
img.onload = function() {
var width = img.width;
var height = img.height;
var canvas = 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));
};
}
弑天下
慕侠2389804
相关分类