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

FastAPI中如何处理名称含点的form-data参数?

FastAPI处理带点的form-data参数

当form-data的参数名称包含点(比如anpr.licensePlatePicture)时,直接用带点的字符串作为Python函数参数行不通——因为Python变量名不允许包含点号,FastAPI无法完成字段映射。

有两种常用解决方法:

方法一:使用File的alias参数

给File指定alias参数,对应表单里带点的字段名,函数参数用合法的变量名即可:

from fastapi import FastAPI, File, UploadFile

app = FastAPI()

@app.post('/test')
async def test(
    anpr: UploadFile = File(...), 
    license_plate_picture: UploadFile = File(..., alias="anpr.licensePlatePicture"),
    detection_picture: UploadFile = File(..., alias="anpr.detectionPicture")
):
    # 直接使用变量处理文件
    return {"received_files": ["anpr", "anpr.licensePlatePicture", "anpr.detectionPicture"]}

方法二:通过Request对象直接解析表单

如果需要更灵活的处理,可以直接获取整个表单数据,再提取对应字段:

from fastapi import FastAPI, Request
from fastapi.datastructures import UploadFile

app = FastAPI()

@app.post('/test')
async def test(request: Request):
    form_data = await request.form()
    # 按表单字段名直接获取文件
    anpr_file = form_data.get("anpr")
    license_plate_file = form_data.get("anpr.licensePlatePicture")
    detection_file = form_data.get("anpr.detectionPicture")
    
    # 示例:读取文件内容
    if isinstance(anpr_file, UploadFile):
        content = await anpr_file.read()
    
    return {"message": "所有文件已接收"}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 13:50:45