ElementUI——el-upload上传前校验图片宽高

发布时间 2023-10-20 10:48:04作者: 。思索

前言

总要写点东西吧,最近忙于项目,github上的问题也没处理,博客也没咋写,自媒体上的东西也没咋发,随手记录一下当前项目改造时候遇到的问题吧;

内容

before-upload

借助于:before-upload来进行校验,使用FileReaderImage来获取宽高

 const reader = new FileReader()
 reader.onload = e => {
  const base64 = e.target.result
  const image = new Image()
  image.src = base64
  image.onload = _ => {
    const width = image.width
    const height = image.height
    console.log(width, height)
  }
}
reader.readAsDataURL(file)

Demo

<el-upload
  action="https://jsonplaceholder.typicode.com/posts/"
  list-type="picture-card"
  :on-preview="handlePictureCardPreview"
  :before-upload="beforeProductImageUpload"
  :on-remove="handleRemove">
  <i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
  <img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
<script>
  export default {
    data() {
      return {
        dialogImageUrl: '',
        dialogVisible: false
      };
    },
    methods: {
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      beforeProductImageUpload(file) {
      console.log('file ===> beforeProductImageUpload ===>', file)
      const imageType = !['image/png', 'image/jpeg', 'image/jpg'].includes(file.type)
      if (imageType) {
        this.$message.warning('产品主图只允许JPG/PNG/JPEG格式')
      }

      const reader = new FileReader()
      reader.onload = e => {
        const base64 = e.target.result
        // 处理base64
        console.log(base64)
        const image = new Image()
        image.src = base64

        image.onload = _ => {
          const width = image.width
          const height = image.height
          console.log(width, height)
        }
      }
      reader.readAsDataURL(file)

      return imageType
    },
    }
  }
</script>