前端压缩图片总的来说还是转base64 然后等比例放小宽和高 这个是上次压缩图片的一个扩展
压缩完之后 再将base64 转成blob再转成文件然后再上传 一生要强的前端崽子(后端不支持base64上传) 自己改吧改吧
javascript
// 图片上传
async changePic(e) {
this.isshangchuantupian=true
this.$message.warning('图片资源正在压缩...')
// 获取图片数据
var file = e.target.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
let ctempfile
let _that = this
reader.onload = await function (event) {
// 压缩图片
var img = new Image();
img.src = event.target.result;
img.onload = function () {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var width = img.width
var height = img.height
if (Math.max(width, height) > _that.maximg) {
if (width > height) {
canvas.width = _that.maximg;
canvas.height = _that.maximg * height / width
} else {
canvas.height = _that.maximg
canvas.width = _that.maximg * width / height
}
} else {
canvas.width = width;
canvas.height = height;
}
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
var dataUrl = canvas.toDataURL('image/jpeg', 0.8); // 压缩后的图片数据
var blob = dataURLToBlob(dataUrl); // 将压缩后的图片数据转换为Blob对象
ctempfile = new File([blob], file.name, { type: 'image/jpeg' }); // 将Blob对象封装为File对象
//console.log(ctempfile)
let formData = new FormData()
// for (let i = 0; i < fileList.length; i++) {
//formData.append('xxxx', fileList[i])
//}
formData.append('update_image', ctempfile)
http
.post('服务器地址', formData)
.then(res => {
//console.log(res.data.update_image)
if (res.data.xxxx) {
_that.isshangchuantupian=false
} else {
_that.$message({
message: '图片上传失败:',
type: 'error'
})
}
})
.catch(err => {
console.log(err)
})
};
};
// 将Base64编码的图片数据转换为Blob对象
function dataURLToBlob(dataUrl) {
var arr = dataUrl.split(','), mime = arr[0].match(/:(.*?);/)[1];
var bstr = atob(arr[1]);
var n = bstr.length;
var u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
//let fileList = e.target.files
},