您好,以下是一个基于 Vue3 和 el-upload 的文件类型判断示例:

<template>
  <el-upload
    class="upload-demo"
    :action="url"
    :on-change="handleChange"
    :before-upload="beforeUpload">
    <el-button size="small" type="primary">上传文件</el-button>
  </el-upload>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const url = 'https://www.mocky.io/v2/5cc8019d300000980a055e76';

    // 允许上传的文件类型
    const allowTypes = ['image/jpeg', 'image/png', 'application/pdf'];

    // 存储上传的文件类型
    const fileTypes = ref([]);

    const handleChange = (file, fileList) => {
      console.log(file, fileList);
    };

    const beforeUpload = (file) => {
      const isAllowType = allowTypes.includes(file.type);
      if (!isAllowType) {
        this.$message.error(`只允许上传 ${allowTypes.join(', ')} 类型的文件`);
      } else {
        fileTypes.value.push(file.type);
      }
      return isAllowType;
    };

    return {
      url,
      allowTypes,
      fileTypes,
      handleChange,
      beforeUpload,
    };
  },
};
</script>

在上面的代码中,我们定义了一个 allowTypes 数组,用于存储允许上传的文件类型,然后在 beforeUpload 方法中判断上传的文件类型是否在 allowTypes 数组中,如果不在就提示用户只允许上传指定的文件类型,否则将文件类型存储到 fileTypes 数组中。在 handleChange 方法中,我们可以通过 file.type 获取到上传文件的类型。

帮我写一个基于vue3 el-upload 判断文件类型

原文地址: https://www.cveoy.top/t/topic/bJlf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录