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

如何用aiohttp发送包含数据与文件的multipart/form-data请求?

使用aiohttp发送multipart/form-data请求返回422错误(原requests请求正常)

我之前用requests发送multipart/form-data请求完全正常,但换成aiohttp后,请求一直返回422错误(API提示数据格式不正确)。我的类中,self.files是io.BytesIO对象,self.data是字符串类型的字典。

现有aiohttp相关代码

params = {
    "url": self.url,
    "headers": self.headers,
    "timeout": self.timeout,
    "proxy": self.proxy
}
# GET请求不允许body带数据
if self.method != "get":
    if self.header_content_type == "multipart/form-data":
        with aiohttp.MultipartWriter("form-data") as mp:
            if self.data:
                for key, value in self.data.items():
                    part = mp.append(value, {'content-type': 'form-data'})
                    part.set_content_disposition('form-data', name=key)
            if self.files:
                for key, value in self.files.items():
                    part = mp.append(value.read(), {'content-type': 'form-data'})
                    part.set_content_disposition('form-data', name=key)

            params["data"] = mp

            async with aiohttp.ClientSession(trust_env=False) as session:
                async with session.post(**params) as response:
                    print(params)
                    return response

错误现象

请求失败后返回422状态码,打印的params内容如下:

{'url': 'http://localhost:9999/v2/toing', 'headers': {'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkY200Y2hlZSIsImV4cCI6MTcxODI4MzAyMX0.6d5XcxucVLvml4O0Z-JBfOvrJLtz254371aQ0XKiCuI'}, 'timeout': 500, 'proxy': None, 'data': <aiohttp.multipart.MultipartWriter object at 0x1149aff40>}

看起来data部分格式不正确,且files属性没有正确传递。

可行的requests请求参数

之前用requests.post可以正常请求的参数如下:

('http://localhost:9999/v2/toing', {'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkY200Y2hlZSIsImV4cCI6MTcxODMwMjQyMH0.lpAfQKISeIhUIcSf1OdM9ZN3eOUB0YHwcfVshY7y0VQ'}) {'data': {'request_data': '{"kk_shape": [2595, 2826], "algorithm_type": "trauma", "age": "33", "center": "toing", "is_spx": false, "detected_xx": "yyy", "kk": "hand"}'}, 'files': {'image_arr': <_io.BytesIO object at 0x116faed90>}, 'header_content_type': 'multipart/form-data'}

疑问

aiohttp.ClientSession.post似乎没有像requests.post那样的files参数,能不能分开发送files和data?我的代码哪里出错了?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 14:20:03