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

如何通过FastAPI与Python requests传递字符串及多文件?

问题解决:FastAPI多文件上传同时传递表单参数

1. 修正FastAPI端点代码

原端点中keywords参数未明确指定来源,当与UploadFile(表单文件)配合使用时,FastAPI要求所有参数都来自表单数据,因此需要给keywords添加Form依赖标注:

from fastapi import FastAPI, File, UploadFile, Form  # 新增导入Form
from typing import List
import uvicorn

app = FastAPI()

@app.post("/multiplefiles")
async def _file_upload(keywords: str = Form(...), files: List[UploadFile] = File(...)):
    return {"keywords": keywords, "file_count": len(files)}

2. 修正requests请求代码

requests的files参数需接收扁平的元组列表,不能嵌套列表。将keywords作为表单字段加入列表即可:

import requests

# 用with语句管理文件,避免资源泄漏
with open('files\\file1.pdf', 'rb') as f1, open('files\\file2.pdf', 'rb') as f2:
    form_data = [
        ("keywords", "key1"),
        ("files", ("file1.pdf", f1, "application/pdf")),
        ("files", ("file2.pdf", f2, "application/pdf"))
    ]
    response = requests.post('http://127.0.0.1:3000/multiplefiles', files=form_data)
    print(response.json())

关键说明:

  • 所有表单字段(普通参数、文件)都要放在同一个列表中,requests会自动编码为multipart/form-data格式,匹配FastAPI的接收要求。
  • 文件字段的元组可采用(字段名, 文件对象)简化格式,或(字段名, (文件名, 文件对象, MIME类型))的规范格式,后者更利于服务端识别文件信息。

内容的提问来源于stack exchange,提问作者ardito.bryan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 15:30:51