You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ant Design Upload组件多格式上传仅识别docx文件问题

Antd Upload组件文件格式校验异常修复

问题描述

项目接入Antd Upload组件实现文件上传能力,预期支持.doc、.docx、.pdf三类格式文件上传,实际运行时只要选择的文件不是.docx格式就会触发报错,原实现代码如下:

import React from "react";
import "antd/dist/antd.css";
import { Upload, message, Button } from "antd";

const props = {
  headers: {
    authorization: "authorization-text",
  },
  action: "",
  name: "file",
  multiple: true,
  accept: ".pdf,.doc,.docx",
  beforeUpload: (file) => {
    const acceptedFormats = ["pdf", "doc", "docx"];
    return acceptedFormats.includes(file.name.split(".")[1])
      ? true
      : Upload.LIST_IGNORE;
  },
};

export default function App() {
  return (
    <div
      style={{
        display: "block",
        width: 700,
        padding: 30,
      }}
    >
      <h4>Upload Documents</h4>
      <>
        <Upload
          {...props}
          onChange={(response) => {
            if (response.file.status !== "uploading") {
              console.log(response.file, response.fileList);
            }
            if (response.file.status === "done") {
              message.success(`${response.file.name} 
                               file uploaded successfully`);
            } else if (response.file.status === "error") {
              message.error(`${response.file.name} 
                             file upload failed.`);
            }
          }}
        >
          <Button>Upload File</Button>
        </Upload>
      </>
    </div>
  );
}

问题根因

格式校验逻辑存在两处缺陷:

  • 文件后缀提取逻辑错误:file.name.split(".")[1] 只会取文件名按第一个.分割后的第二段内容,只要文件名包含多个.(例如项目方案.v2.doc、入职证明.2024.pdf),取到的内容就不是真实文件后缀,无法命中允许格式列表
  • 未兼容后缀大小写场景:如果文件后缀为大写格式(例如.PDF、.DOC),直接字符串匹配会判定为不合法

修复方案

调整后缀提取逻辑,取文件名最后一个.后的内容作为真实后缀,同时统一转小写兼容大小写差异,修改后的beforeUpload逻辑如下:

beforeUpload: (file) => {
  const acceptedFormats = ["pdf", "doc", "docx"];
  // 取最后一个点后的内容作为文件后缀,统一转小写规避大小写问题
  const fileSuffix = file.name.split(".").pop().toLowerCase();
  const isAllowed = acceptedFormats.includes(fileSuffix);
  if (!isAllowed) {
    message.error("仅支持上传.doc、.docx、.pdf格式的文件");
  }
  return isAllowed || Upload.LIST_IGNORE;
},

注意:组件的accept属性仅能控制系统文件选择弹窗的默认过滤规则,无法阻止用户手动切换选择范围选中非允许格式文件,不能替代beforeUpload中的手动校验逻辑。


内容的提问来源于stack exchange,提问作者Nedim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 11:30:47