使用 Python requests 发送图片的 POST 请求

4
我正在尝试使用以下代码发送图像:这只是我的代码的一部分,我没有在此处包含标头,但它们已经正确设置,其中content-type为Content-Type:multipart/form-data; boundary=eBay Classifieds Post Image
img = "piano.jpg"
f = open(img,'rb')
out = f.read()
files = {'file':out}

p = requests.post("https://ecg-api.gumtree.com.au/api/pictures",headers=headers, data=files)
f.close()

我遇到了一个400错误:multipart/form-data格式不正确

我该如何正确发送图片?

额外细节:

网络分析显示已发送以下请求:

POST https://ecg-api.gumtree.com.au/api/pictures HTTP/1.1
host:   ecg-api.gumtree.com.au
content-type:   multipart/form-data; boundary=eBayClAsSiFiEdSpOsTiMaGe
authorization:  Basic YXV5grehg534
accept: */*
x-ecg-ver:  1.49
x-ecg-ab-test-group:    gblios_9069_b;gblios-8982-b
accept-encoding:    gzip
x-ecg-udid: 73453-7578p-8657
x-ecg-authorization-user:   id="1635662", token="ee56hgjfjdghgjhfj"
accept-language:    en-AU
content-length: 219517
user-agent: Gumtree 12.6.0 (iPhone; iOS 13.3; en_AU)
x-ecg-original-machineid:   Gk435454-hhttehr

Form data:
file: ����..JFIF.....H.H..��.LExif..MM.*..................�i.........&......�..

由于文件的表单数据过长,我切掉了它。我的头部信息如下(这里的实际身份验证值是虚构的):

idd = "1635662"
token = "ee56hgjfjdghgjhfj"

headers = {
"authority":"ecg-api.gumtree.com.au",
"content-type":"multipart/form-data; boundary=eBayClAsSiFiEdSpOsTiMaGe",
"authorization":"Basic YXV5grehg534",
"accept":"*/*",
"x-ecg-ver":"1.49",
"x-ecg-ab-test-group":"gblios_9069_b;gblios-8982-b",
"accept-encoding":"gzip",
"x-ecg-udid":"73453-7578p-8657",
"x-ecg-authorization-user":f"id={idd}, token={token}",
"accept-language":"en-AU",
"content-length":"219517",
"user-agent":"Gumtree 12.6.0 (iPhone; iOS 13.3; en_AU)",
"x-ecg-original-machineid":"Gk435454-hhttehr"
}

也许是我编写的标题的方式有问题?我怀疑是我在标题中编写x-ecg-authorization-user部分的方式有问题?因为我发现即使为令牌或ID提供随机值,也会出现相同的400错误multipart/form-data格式不正确

1
这回答您的问题吗?stackoverflow - Ahmet
@Ahmet 我怀疑是我在头部中写x-ecg-authorization-user的方式有问题?因为我意识到即使为令牌或ID放入随机值也会给我相同的400错误不正确的multipart/form-data格式 - West
这个错误提示显示了“401:未经授权”,而不是“400”。 - Ahmet
@Ahmet 请记住,我发布的授权值并不是实际的值。 - West
正如@Brian建议的那样,请尝试删除“content-type”头并使用相同的代码。可能您设置的边界是不正确的。这个方法可行吗? - Ahmet
显示剩余2条评论
1个回答

2
你可以尝试以下代码。不要在头部设置内容类型,让Pyrequests为你做这件事。
files = {'file': (os.path.basename(filename), open(filename, 'rb'), 'application/octet-stream')}
upload_files_url = "url"
headers = {'Authorization': access_token, 'JWTAUTH': jwt}
r2 = requests.post(parcels_files_url, files=files, headers=headers)

谢谢!删除内容类型起作用了,同时在POST中使用files=files而不是data=files也起作用。 - West

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接