ElementPlus文件上传 ,在上传前钩子中判断文件是否为图片

在ElementPlus中,可以使用beforeUpload属性来指定上传文件之前的钩子函数,在该函数中可以对文件进行判断并进行相关操作。

首先,在data中定义一个isImage变量来记录文件是否为图片,初始值为false。然后,在钩子函数中判断文件的类型是否为图片类型。

<template>
  <el-upload
    class="upload-demo"
    action="/your-upload-api"
    :before-upload="handleBeforeUpload"
  >
    <el-button size="small" type="primary">Click to Upload</el-button>
  </el-upload>
</template>

<script>
export default {
  data() {
    return {
      isImage: false
    }
  },
  methods: {
    handleBeforeUpload(file) {
      const fileType = file.type
      if (fileType.startsWith('image/')) {
        this.isImage = true
      } else {
        this.isImage = false
        this.$message.error('Please upload images only.')
        return false  // 阻止文件上传
      }
    }
  }
}
</script>

handleBeforeUpload函数中,首先获取文件的类型,然后使用startsWith方法判断是否以image/开头,如果是,则将isImage设置为true,否则将其设置为false,并且返回false来阻止文件上传。同时,可以根据情况给出相应的错误提示。

猜你喜欢

转载自blog.csdn.net/qq_44848480/article/details/132148170