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

Python Requests如何为FastAPI多文件上传接口构造列表格式上传请求

前置依赖确认

先确保你已经安装了multipart相关依赖:

pip install python-multipart

错误原因&修复方案

你碰到的报错由几个核心问题导致:

  1. requests多文件传参格式错误:requests的files参数不支持直接把文件元组列表作为字典单个键的值,会触发类型解析错误
  2. 参数名&请求路径不匹配:FastAPI接口定义的接收字段是files、路由是带尾部斜杠的/uploadfiles/,你的测试代码里字段用了uploads、请求路径少了尾部斜杠
  3. 同一文件句柄重复使用:单个打开的文件句柄读取一次后指针会落在文件末尾,第二次读取会返回空内容

修复后的测试代码

import requests

testapi = '' # 替换为你的接口地址,比如http://127.0.0.1:8000

# 分别打开两个文件,不要复用同一个文件句柄
with open("profile.jpeg", "rb") as f1, open("profile2.jpeg", "rb") as f2:
    response = requests.post(
        # 路径补全尾部斜杠,和接口定义一致
        f"{testapi}/uploadfiles/",
        # files参数直接传列表,每个元素第一个值为接口接收的字段名files
        files=[
            ("files", ("profile.jpeg", f1, "image/jpeg")),
            ("files", ("profile2.jpeg", f2, "image/jpeg")),
        ]
    )
    print(response.json())
    assert response.status_code == 200

如果你只有一个测试文件要模拟两次上传,可以在第一次读取后把文件指针重置到开头:

import requests

testapi = ''

with open("profile.jpeg", "rb") as image_file:
    response = requests.post(
        f"{testapi}/uploadfiles/",
        files=[
            ("files", ("profile.jpeg", image_file, "image/jpeg")),
        ]
    )
    # 重置文件指针到开头
    image_file.seek(0)
    response2 = requests.post(
        f"{testapi}/uploadfiles/",
        files=[
            ("files", ("profile2.jpeg", image_file, "image/jpeg")),
        ]
    )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:54:02