el-upload 压缩图片

911 阅读1分钟

安装image-conversion

npm i -S image-conversion

import * as imageConversion from 'image-conversion'

Vue.prototype.beforeUpload_compress = function (file) {
   return new Promise((resolve, reject) => {
      console.log('压缩前', file) // 压缩到200KB,大于200KB的图片都会进行压缩,小于则不会
      imageConversion.compressAccurately(file, 200).then(res => { // console.log(res)
         res = new File([res], file.name, { type: res.type, lastModified: Date.now() })
         console.log('压缩后', res);
         resolve(res)
      })
   })
}
<el-upload
    :action="VUE_APP_BASE_API + '/crm/attachment/uploadPic'"
    :accept="'image/*'"
    :limit="1"
    ref="upload_logo"
    :show-file-list="false"
    :headers="header_token"
    :before-upload="beforeUpload_compress"
    :on-success="(res)=>{$refs.upload_logo.clearFiles();req.logoUrl = res.attachmentName}">
    <el-button size="small" type="primary">上传</el-button>
</el-upload>

限制附件大小

:beforeUpload="beforeAvatarUpload"
beforeAvatarUpload(file) {
    const isLt2M = file.size / 1024 / 1024 < 2
    if(!isLt2M) {
        this.$message({
            message: '上传文件大小不能超过 2MB!',
            type: 'warning'
        });
    }
    return isLt2M
},