Submitting binary data as a file via post request

Viewed 748

I know how to submit a post request with a file.

files = {'file': open('local.pdf', 'rb')}
r = requests.post(url, files=files)

Since I'm downloading the file from a response, I want to avoid writing the response.contents to my local disk ('local.pdf') before I submit the post request. Can I submit the file as a bytes object?

1 Answers

You can use io.BytesIO to do that.

Here is an example:

rawData = io.BytesIO(b"Some data: \x00\x01") # Change the content
files = {'file': rawData}
r = requests.post(url, files=files)
Related