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

使用Python的urllib3上传文件时出现错误求助

urllib3上传文件失败的解决方法

你的问题出在urllib3上传文件的参数格式不对——直接传递文件字节串时,urllib3会把它当成普通表单字段,而非文件上传字段,导致服务器无法解析。

urllib3要求文件字段的值必须是元组格式,包含文件名和文件对象/字节数据(可选加上Content-Type),这样才能正确构造multipart/form-data请求,这和requests的自动处理逻辑不同。

修正后的代码有两种写法:

方式1:直接使用文件对象(推荐,节省内存)

import urllib3

http = urllib3.PoolManager()
url = "https://tmpfiles.org/api/v1/upload"

# 用with语句自动管理文件句柄
with open("image", "rb") as dfile:
    response = http.request(
        "POST",
        url,
        fields={
            "file": ("image", dfile)  # 元组结构:(文件名, 文件对象)
        }
    )

print(response.data)

方式2:使用已读取的文件字节

如果已经提前把文件读入内存,需要把字节数据和文件名一起放进元组:

import urllib3

http = urllib3.PoolManager()
url = "https://tmpfiles.org/api/v1/upload"

with open("image", "rb") as f:
    dfile = f.read()

response = http.request(
    "POST",
    url,
    fields={
        "file": ("image", dfile)  # 元组结构:(文件名, 文件字节)
    }
)

print(response.data)

如果需要指定文件的Content-Type,可以在元组里再加第三个参数,比如上传JPG图片时:

"file": ("image.jpg", dfile, "image/jpeg")

这样修改后,urllib3会按照正确的文件上传格式发送请求,服务器就能正常接收文件了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 09:35:15