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

FastAPI同时接收文件和结构化数据返回422错误如何解决

FastAPI 同时传输文件与结构化数据报错422解决方案

错误根因

  • FastAPI 中 multipart/form-data 类型的请求(含文件上传的请求默认是该类型),无法直接用 Pydantic 模型解析参数,Pydantic 模型默认适配的是 application/json 格式的请求体,二者格式不兼容导致422参数校验失败。
  • 原服务端代码返回值中调用了data.camera,但自定义的Data模型中没有定义camera字段,即便参数校验通过也会触发属性不存在的报错。

修复代码

服务端修改

将结构化参数改为用Form接收即可,无需额外调整客户端逻辑:

import uvicorn
from fastapi import FastAPI, File, Form

app = FastAPI()

@app.post("/uploadfile/")
async def create_file(
    test1: str = Form(None),
    test2: str = Form(None),
    test3: str = Form(None),
    image: bytes = File(...),
):
    return {
        "postdata": len(image),
        "data": {"test1": test1, "test2": test2, "test3": test3}
    }

if __name__ == "__main__":
    uvicorn.run(app)

如果要保留Pydantic模型的结构,也可以将结构化数据序列化为JSON字符串作为单个Form字段传递,服务端接收后手动解析为模型实例即可。

客户端代码(无需改动,原逻辑可正常运行)

import requests
import cv2
image = cv2.imread('/marti.jpg')
data2 = cv2.imencode(".jpg", image)[1]

payload = {"test1": "value_1", "test2": "value_2", "test3": "value_3"}
files = {
    'image': ('a.jpg', data2.tobytes(), 'image/jpeg', {'Expires': '0'})
}

res = requests.post("http://localhost:8000/uploadfile/",
                    files=files, data=payload)
print(res.content)
print(res.status_code, res.json())

内容的提问来源于stack exchange,提问作者Ali Gökaya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:39:03