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

如何使用Python requests库发送携带base64编码文件的JSON POST请求

问题原因

  • 你的prescription字典中Body字段的值是bytes类型,Python原生JSON序列化逻辑不支持bytes类型的序列化,因此抛出了类型错误。
  • requests.post(url, prescription)的写法本身不符合发送JSON请求的要求:直接传入字典时,requests默认会将其作为表单数据处理,而非JSON payload。

正确实现方案

该需求完全可以实现,属于API开发中非常常见的base64格式文件上传场景,以下是两种可行写法:

写法1:最简适配方案(你已验证可用)

先将bytes类型的base64内容解码为字符串,再使用requests的json参数发送请求,requests会自动完成JSON序列化、设置正确的请求头:

import requests

prescription = {
    "Name": "file_name", # 字符串类型
    "Body" : xxx.decode("utf-8"), # bytes类型base64转字符串
    "ParentId" : "xxxxxxxxxxxxxxxxxx", # 字符串类型
    "ContentType" : "xxxxx/xxx" # 字符串类型
}
response = requests.post(url, json=prescription)

写法2:手动序列化方案(适配特殊自定义场景)

如果需要自定义序列化规则,也可以手动调用json模块处理:

import requests
import json

prescription = {
    "Name": "file_name",
    "Body" : xxx.decode("utf-8"),
    "ParentId" : "xxxxxxxxxxxxxxxxxx",
    "ContentType" : "xxxxx/xxx"
}
response = requests.post(
    url, 
    data=json.dumps(prescription), 
    headers={"Content-Type": "application/json"}
)

内容的提问来源于stack exchange,提问作者carlos de la morena

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:06:04