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

FastAPI文件上传接口Swagger正常但Requests请求返回400解析错误

错误原因

你在query.py中手动指定了Content-Type: multipart/form-data请求头,multipart/form-data格式要求请求头必须携带随机生成的边界(boundary)参数用于分隔请求体中的多个字段,这个参数是requests库传入files参数时自动生成填充的。手动指定请求头会覆盖自动生成的带边界参数的正确请求头,导致FastAPI无法识别请求体的分隔规则,解析失败返回400。

解决方法

直接删除query.py中手动设置的headers参数即可,requests会自动处理文件上传所需的请求头配置。

修正后的query.py代码如下:

import requests

url = 'http://localhost:8000/upload'
files = [
("file", ("file1.txt", open("F://test.txt", "rb"), "text/txt"))
]
response = requests.post(url, files=files)    
print(response.status_code, response.text)

补充优化建议

原代码中直接使用open()打开文件没有主动关闭,存在资源泄漏风险,建议改用上下文管理器写法:

import requests

url = 'http://localhost:8000/upload'
with open("F://test.txt", "rb") as f:
    files = [("file", ("file1.txt", f, "text/txt"))]
    response = requests.post(url, files=files)    
print(response.status_code, response.text)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 07:09:03