Upload Image Using Post Form Data in Python-Requests

Upload Image using POST form data in Python-requests

From wechat api doc:

curl -F media=@test.jpg "http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"

Translate the command above to python:

import requests
url = 'http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE'
files = {'media': open('test.jpg', 'rb')}
requests.post(url, files=files)

Doc: https://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file

Sending images by POST using python requests

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)

How to send an image together with form data using python requests?

You don't need to add it in python-requests.This is not the request header of it.
form-data represents the enctype way.Except form-data, there also have form-urlencoded, text/plain(less common).Get more information on wiki.

Content-Disposition : Because you used files=file. it would send by form-data normally.

name="image" : The name in the form.(In your circumstance, they are image).

name="submit" : This usually means the submit button of the form.When you click the button on the page,it would take this.(Mostly you don't need to add it).

If you really like to post it on the first way:

files = {
'image': (payload_img, open(payload_img, 'rb'), "image/png"),
}
data = {
"submit": "Upload Image".
}

requests.post(url, files=files, data=data, headers=headers .... )
...

Cannot upload images using Python requests

import requests

files = {'Files[]': ("1.png", open(r"your/image/path", 'rb'), "image/png", {})}

data = {
'Func': "UploadPhotos",
"SiteID": "1",
"UserID": "xx", # your user ID here
"IP": "xx", # your IP here
"UploadedFiles": 0
}

response = requests.post('https://static.my.ge/', files=files, data=data)

print(response.json())

And the result:

{'StatusID': 0, 'StatusCode': 1, 'Message': 'Error occurred during the operation', 'Data': {'FilesList': ['xxxx.jpg'], 'imgKey': ['xxxx']}}


Related Topics



Leave a reply



Submit