使用python请求通过POST发送图像

时间:2020-01-27 10:10:17

标签: python post python-requests

我正在尝试使用以下代码发送图像:这只是我的代码的一部分,我没有在此处包括标头,但它们的设置正确,内容类型为content-type: multipart/form-data; boundary=eBayClAsSiFiEdSpOsTiMaGe

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错误incorrect multipart/form-data format

如何正确发送图像?

其他详细信息:

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

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.........&......�..

我切断了文件的formdata部分,因为它太长了。我的标头编写如下(我在这里构成了实际的auth值):

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错误incorrect multipart/form-data format

1 个答案:

答案 0 :(得分: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)