对于不同的文件格式,Antd beforeUpload 无法按预期工作

Antd beforeUpload does not work as expected with different file formats

我正在使用简单的 antd Uploader 拖动器组件并在上传之前传递道具,以避免上传我确实想要上传的文件扩展名。代码如下:

const props = {
    name: "file",
    multiple: true,
    action: "/upload",
    beforeUpload: (file) => {
         if (file.name.split(".").reverse()[0] !== ("pdf" || "doc" || "docx")) {
            console.log(`${file.name} is not a correct format file`);
         }
         return file.name.split(".").reverse()[0] === ("pdf" || "doc" || "docx") ? true : Upload.LIST_IGNORE;
              },
     onChange(info) {
        const { status } = info.file;
         console.log(info.files) //All format files are shown in console
      },
      accept: ".pdf,.doc,.docx",
      showUploadList: false,
      fileList: files,
};

这是组件

的return
<Upload.Dragger {...props}>
  <p>Drag and upload your files</p>
</Upload.Dragger>

问题是即使控制台工作并显示特定文件不是正确的格式文件,它仍然被添加到 fileList 数组中,这是不应该的,因为我正在使用它 Upload.LIST_IGNORE .我几个小时以来一直在尝试调试,但没有用,任何人都可以指导我解决这个问题,我将不胜感激。

在您当前的实现中,您只是将上传文件的文件类型与 pdf 类型进行比较,因为您所有的文件格式都在括号中并且您使用的是 || 这将 return 第一个真值,在你的例子中是 pdf

您需要根据您接受的文件格式列表检查上传的文件类型。

beforeUpload: (file) => {
 const acceptedFormats = ['pdf', 'doc', 'docx'];
 return acceptedFormats.includes(file.name.split('.')[1]) ? true : Upload.LIST_IGNORE;
},