安装image-conversion包 https://github.com/WangYuLue/image-conversion
<el-upload
class="upload-demo"
action="uploadPath"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-upload="beforeUpload"
list-type="picture">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
import * as imageConversion from 'image-conversion'
methods: {
// 不考虑图片长宽,只考虑图片大小的情况,图片超过4M就压缩
beforeUpload (file) {
return new Promise((resolve, reject) => {
let isLt2M = file.size / 1024 / 1024 < 4 // 判定图片大小是否小于4MB
if (isLt2M) {
resolve(file)
}
console.log('file size:', file) // 压缩到400KB,这里的400就是要压缩的大小,可自定义
imageConversion.compressAccurately(file, 400).then(res => { //
console.log(res)
resolve(res)
})
})
},
}