我对Python还是比较陌生的,也是我第一次使用aiohttp,所以我希望有人能帮我找出问题所在。
我的职能如下:
从JSON有效负载检索两个base64Back
base64Front和base64字符串,保存到“图像”文件夹
Front.jpg和Back.jpg发送到外部API
multipart/form-dataimgDataF = base64.b64decode(base64FrontStr)
frontFilename = 'images/Front.jpg'
with open(frontFilename, 'wb') as frontImgFile:
frontImgFile.write(imgDataF)
imgDataB = base64.b64decode(base64BackStr)
backFilename = 'images/Back.jpg'
with open(backFilename, 'wb') as backImgFile:
backImgFile.write(imgDataB)
headers = {
'Content-Type': 'multipart/form-data',
'AccountAccessKey': 'some-access-key',
'SecretToken': 'some-secret-token'
}
url = 'https://external-api/2.0/AuthenticateDoc'
files = [('file', open('./images/Front.jpg', 'rb')),
('file', open('./images/Back.jpg', 'rb'))]
async with aiohttp.ClientSession() as session:
async with session.post(url, data=files, headers=headers) as resp:
print(resp.status)
print(await resp .json())我得到的响应是状态代码400,下面是:
{'ErrorCode': 1040, 'ErrorMessage': 'Malformed/Invalid Request detected'}如果我通过邮递员调用url并发送两个jpg文件,我将得到状态代码200。希望有人能帮上忙。提前谢谢。
发布于 2021-01-20 05:47:55
尝试使用FormData构造您的请求。从标头中删除内容类型,并在FormData字段中使用它,如下所示:
data = FormData()
data.add_field('file',
open('Front.jpg', 'rb'),
filename='Front.jpg',
content_type='multipart/form-data')
await session.post(url, data=data)参考资料:https://docs.aiohttp.org/en/stable/client_quickstart.html#post-a-multipart-encoded-file
https://stackoverflow.com/questions/62926052
复制相似问题