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

Python调用Spring Boot POST REST API上传文件提示无法转换为MultipartFile

错误原因
  • 手动指定了Content-Type: multipart/form-data:使用requests的files参数上传文件时,库会自动生成带边界标识(boundary)的请求头,手动指定会丢失边界信息,导致后端无法正常解析表单字段
  • 把表单参数放在了params中:params参数会把内容拼接为URL查询参数,而Spring Boot的@ModelAttribute默认从请求体的表单字段读取参数,参数位置不匹配
  • 多余的参数配置:payload中重复定义了file字段,且错误把文件对象放入了请求参数中,导致后端接收到的file字段是文件对象的字符串表示,无法转换为MultipartFile类型
修复后的Python代码
import requests

headers = {
    'Accept': 'application/json, text/plain, */*',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US,en;q=0.9',
    'Authorization': 'Bearer XXXX',
    'Connection': 'keep-alive'
    # 移除手动设置的Content-Type,让requests自动生成
}

fp = 'C:/inputs/inputfile.txt'
# 文件只需要在files参数中定义即可
files = {'file': open(fp, 'rb')}

# 普通表单字段放在data参数中,不要加file字段
payload = {
    'integrator': 1,
    'version': 2
}

# 把params改为data,传递普通表单字段
resp = requests.post("http://localhost:8080/api/v1/upload/text", data=payload, headers=headers, files=files)
print(resp.text)
print("status code " + str(resp.status_code))
额外校验点
  • 确认TextUploadModel类的三个字段integrator、version、file的Getter/Setter方法完整,Spring需要通过反射注入字段值
  • 上传的文件不能为空,否则也可能触发类型转换异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 12:00:00