Python: how to upload files with the requests module

Python: how to upload files with the requests module

In this article we will see how to upload a file in Python with the requests module.

In this article we will see how to upload a file in Python with the requests module.

The solution is as follows:


import os
import requests

def upload_file(url, file_path):
    if not os.path.exists(file_path):
        return False
    with open(file_path, 'rb') as f:
        files = {'file': f}
        try:
            r = requests.post(url, files=files)
        except requests.exceptions.RequestException:
            return False
    return True                

The function will return a boolean value. In case of non-existent or inaccessible file and HTTP request error, False will be returned. The file is read in binary mode and inserted as a value into the dictionary files which will be used in the POST request to the specified URL. The dictionary key in the example corresponds to the file name that the web server expects to finalize the upload. In fact in this case we are simulating the submission of an HTML form, so the key file corresponds to the value of the name attribute of an HTML input field of type file.