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

使用Axios向FastAPI上传文件时遭遇422 (Unprocessable Entity)错误求助

解决Axios上传文件到FastAPI出现422错误的问题

问题排查与修复点:

  1. 变量引用错误:React提交函数的参数是acceptedFiles,但代码里用了未定义的file变量,需从acceptedFiles中获取实际文件。
  2. 错误的Accept请求头:设置的Accept: "application/solidarity"不符合FastAPI默认的响应格式,应改为application/json或直接移除该头。
  3. 手动设置Content-Type导致解析失败:上传FormData时,Axios会自动生成包含正确boundary的Content-Type头,手动设置"multipart/form-data"会丢失boundary,导致FastAPI无法解析表单数据,需移除该手动设置。

修改后的React提交函数:

const handleSubmit = async (acceptedFiles) => {
    // 单文件上传时取第一个文件,多文件需循环处理
    const file = acceptedFiles[0];
    if (!file) return;

    const formData = new FormData();
    formData.append("file", file);

    try {
      const response = await axios.post(
        "http://127.0.0.1:8000/upload",
        formData,
        {
          headers: {
            Accept: "application/json",
            // 移除手动设置的Content-Type,交由Axios自动处理
          },
        }
      );
      if (response.status >= 200 && response.status < 300) {
        console.log(response.data);
        // 处理审计结果逻辑
      } else {
        throw new Error("Server responded with a non-2xx status code");
      }
    } catch (error) {
      console.error(
        "Error uploading file:",
        error.response?.data || error.message
      );
    }
};

额外检查项:

  • 确认FastAPI中的UPLOAD_DIR已创建,且服务进程对该目录有写入权限。
  • 若需支持多文件上传,需修改FastAPI接口为async def upload_file(files: List[UploadFile]),同时React侧循环将文件添加到FormData中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:47:56