Skip to content
Advertisement

Upload Image using POST form data in Python-requests

I’m working with wechat APIs … here I’ve to upload an image to wechat’s server using this API http://admin.wechat.com/wiki/index.php?title=Transferring_Multimedia_Files

url = 'http://file.api.wechat.com/cgi-bin/media/upload?access_token=%s&type=image'%access_token
files = {
    'file': (filename, open(filepath, 'rb')),
    'Content-Type': 'image/jpeg',
    'Content-Length': l
}
r = requests.post(url, files=files)

I’m not able to post data

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement