// 压缩前将file转换成img对象
readImg(file) {
return new Promise((resolve, reject) => {
const img = new Image()
const reader = new FileReader()
reader.onload = function(e) {
img.src = e.target.result
}
reader.onerror = function(e) {
reject(e)
}
reader.readAsDataURL(file)
img.onload = function() {
resolve(img)
}
img.onerror = function(e) {
reject(e)
}
})
},
compressImg(img, type, mx, mh) {
return new Promise((resolve, reject) => {
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
const { width: originWidth, height: originHeight } = img
// 最大尺寸限制
const maxWidth = mx
const maxHeight = mh
// 目标尺寸
let targetWidth = originWidth
let targetHeight = originHeight
if (originWidth > maxWidth || originHeight > maxHeight) {
if (originWidth / originHeight > 1) {
// 宽图片
targetWidth = maxWidth
targetHeight = Math.round(maxWidth * (originHeight / originWidth))
} else {
// 高图片
targetHeight = maxHeight
targetWidth = Math.round(maxHeight * (originWidth / originHeight))
}
}
canvas.width = targetWidth
canvas.height = targetHeight
context.clearRect(0, 0, targetWidth, targetHeight)
// 图片绘制
context.drawImage(img, 0, 0, targetWidth, targetHeight)
canvas.toBlob(function(blob) {
resolve(blob)
console.log('压缩')
}, type || 'image/jpeg') })
},
上传
async afterRead(res){
let _this = this;
let file = res.file;
let params = new FormData();
if(file.size/(1024*1024)>1){ //大于1M的文件压缩
const img = await _this.readImg(file);
const blob = await _this.compressImg(img, file.type, 1200, 1200);
blob.name = file.name;
params.append("file", blob,'file_pic.jpg');
}else {
params.append("file", file);
}
upload(params).then((res)=>{ //上传接口
if(res.code == 0){
//上传成功
}
})
},