Skip to main content

Uploading Files

In this tutorial, we will explore how to upload files using Python's requests module. This is a core feature that is used in various scenarios, such as uploading images to a server or sending data files for processing.

Introduction to File Uploads with Requests

Python's requests module provides a built-in method, requests.post(), for sending HTTP POST requests. This method can be used to upload files by sending multipart/form-data requests, which is a common way to transmit data in HTTP.

Before getting started, ensure you have the requests module installed. If not, you can install it using pip:

pip install requests

Uploading Single File

Let's start by uploading a single file. Here's a basic example:

import requests

file_dict = {'file': open('example.txt', 'rb')}

response = requests.post('http://httpbin.org/post', files=file_dict)

print(response.text)

In this example, we open the file example.txt in binary mode. Then, we pass a dictionary to the files parameter of the requests.post() method. The dictionary key is 'file', which becomes the name of the file on the server. The dictionary value is the file object.

The file content is sent as binary data in the body of the POST request. The server's response is printed out.

Uploading Multiple Files

To upload multiple files, we can pass a dictionary with multiple key-value pairs:

import requests

multiple_files = [
('images', ('cat.jpg', open('cat.jpg', 'rb'))),
('images', ('dog.jpg', open('dog.jpg', 'rb')))
]

response = requests.post('http://httpbin.org/post', files=multiple_files)

print(response.text)

Each tuple contains the form field name and a tuple of filename and file object.

Specifying Content-Type

In some cases, you may want to specify the MIME type of the uploaded file. You can do this by including the content type in the tuple:

import requests

file_dict = {'file': ('report.csv', open('report.csv', 'rb'), 'text/csv')}

response = requests.post('http://httpbin.org/post', files=file_dict)

print(response.text)

Here, 'text/csv' is the MIME type for CSV files.

Error Handling

Remember to handle potential errors when uploading files. For instance, you should handle exceptions that might occur when opening the file:

import requests

try:
file_dict = {'file': open('non_existent.txt', 'rb')}
except IOError:
print("File not accessible")
else:
response = requests.post('http://httpbin.org/post', files=file_dict)
print(response.text)

Also, check the status code of the HTTP response to ensure the request was successful:

import requests

file_dict = {'file': open('example.txt', 'rb')}

response = requests.post('http://httpbin.org/post', files=file_dict)

if response.status_code == 200:
print("File uploaded successfully")
else:
print("Failed to upload file")

That concludes this tutorial on file uploads with Python's requests module. Always remember to close any files you open, and handle any potential errors in your code. Happy coding!