python requests upload file multipart/form-data

Python Requests Upload File Multipart/Form-Data

If you need to upload a file using Python, you can use the requests module. With requests, uploading a file is a simple process. Requests support multipart/form-data encoding which enables users to send both text and files as a single HTTP request.

Uploading Single File

If you want to upload a single file, you can use the open() method from the built-in Python os module to open the file, then use the requests.post() method to upload the file.


import requests
import os

url = 'https://example.com/upload'
file = {'file': open('example.txt', 'rb')}

response = requests.post(url, files=file)

In this example, we are uploading a file called example.txt and sending it to the URL https://example.com/upload using the HTTP POST method. The file is opened in binary mode using 'rb' so that it can be read and uploaded in its binary format. The file is then passed to the requests.post() method using the files parameter.

Uploading Multiple Files

If you want to upload multiple files, you can use a list of tuples for the files parameter.


import requests
import os

url = 'https://example.com/upload'
files = [('file1', open('example1.txt', 'rb')), ('file2', open('example2.txt', 'rb'))]

response = requests.post(url, files=files)

In this example, we are uploading two files called example1.txt and example2.txt and sending them to the URL https://example.com/upload using the HTTP POST method. The files are opened in binary mode using 'rb' so that they can be read and uploaded in their binary format. The files are then passed as a list of tuples to the requests.post() method using the files parameter.

Uploading Files with Additional Fields

If you want to upload a file along with additional fields, you can pass them as a dictionary to the data parameter.


import requests
import os

url = 'https://example.com/upload'
file = {'file': open('example.txt', 'rb')}
data = {'name': 'John Doe', 'email': '[email protected]'}

response = requests.post(url, files=file, data=data)

In this example, we are uploading a file called example.txt and sending it along with additional fields 'name' and 'email' to the URL https://example.com/upload using the HTTP POST method. The file is opened in binary mode using 'rb' so that it can be read and uploaded in its binary format. The file and additional fields are then passed to the requests.post() method using the files and data parameters respectively.

Conclusion

Python Requests makes it easy to upload files to a server. The multipart/form-data encoding allows you to send both text and files as a single HTTP request. You can also upload multiple files and include additional fields with your request.