Categories
Python Answers

How to upload file with Python requests?

Spread the love

Sometimes, we want to upload file with Python requests.

In this article, we’ll look at how to upload file with Python requests.

How to upload file with Python requests?

To upload file with Python requests, we call requests.post with the files argument.

For instance, we write

files = {"upload_file": open("file.txt", "rb")}
values = {"DB": "photcat", "OUT": "csv", "SHORT": "short"}

r = requests.post(url, files=files, data=values)

to call requests.posts to make a POST request to the url.

We set the files argument to the files dict that has a file as a value in the entry to upload that file as form data.

And we set data to values to add those key-value pairs as form data.

Conclusion

To upload file with Python requests, we call requests.post with the files argument.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *