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

Flask上传API调用失败:求带PDF与表单数据的正确请求方式

正确的API调用写法

问题根源

  1. 不要手动设置Content-Type: multipart/form-data:当使用requests的files参数上传文件时,库会自动生成包含正确边界符的Content-Type头,手动设置会覆盖这个自动生成的内容,导致后端无法正确解析表单数据。
  2. 普通表单字段需与文件分开传递:AA_num、BB_num这类普通键值对要放在data参数中,而非files参数里——files仅用于文件上传,普通字段通过data传递后,后端才能通过request.form正常获取。

修正后的请求代码

import requests

api_url = 'http://127.0.0.1:5000/upload'  
pdf_path = 'my_CV.pdf'

# 普通表单字段放入data字典
data = {
    'AA_num': "34",
    'BB_num': "55"
}

# 文件放入files字典
files = {
    'file': open(pdf_path, 'rb')
}

# 无需手动设置Content-Type头
response = requests.post(api_url, data=data, files=files)

print(response.json())

更安全的写法(自动关闭文件)

如果担心文件句柄未及时关闭,可使用with语句:

import requests

api_url = 'http://127.0.0.1:5000/upload'  
pdf_path = 'my_CV.pdf'

data = {
    'AA_num': "34",
    'BB_num': "55"
}

with open(pdf_path, 'rb') as f:
    files = {'file': f}
    response = requests.post(api_url, data=data, files=files)

print(response.json())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 10:22:43