简体   繁体   中英

Sending images by POST using python requests

I am trying to send through an image using the following code: This is just a part of my code, I didn't include the headers here but they are set up correctly, with content-type as content-type: multipart/form-data; boundary=eBayClAsSiFiEdSpOsTiMaGe 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()

I get a 400 error incorrect multipart/form-data format

How do I send the image properly?

Extra Details:

Network analysis shows the following request been sent:

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

I cut off the the formdata part for file as its too long. My headers are written as follows (I have made up the actual auth values here):

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"
}

Maybe its the way I have written the headers? I suspect its the way I have written the x-ecg-authorization-user part in headers? Because I realise even putting random values for the token or id gives me the same 400 error incorrect multipart/form-data format

You can try the following code. Don't set content-type in the headers.Let Pyrequests do that for you

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM