Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Upload Files with Python Requests Using Multipart Form Data

Learn how to upload files with Python requests using multipart/form-data: single and multiple files, extra form fields, custom filenames, and common pitfalls.

~3 min readPython
#requests#file upload#multipart form data#HTTP client
Python requests library uploading a file as multipart form data, shown as a document moving into an HTTP request envelope

Python's requests library makes multipart file uploads straightforward. This guide covers how to send one or more files as multipart/form-data, include extra form fields, control the filename sent to the server, and avoid common mistakes.

How the files Parameter Works

When you pass a dictionary to the files parameter, requests encodes the request body as multipart/form-data. Each key in the dictionary becomes a form field name, and each value can be a file-like object, a tuple that supplies a filename and file data, or raw bytes or string content. The library generates the multipart boundary and sets the Content-Type header for you.

A single-file upload looks like this:

python
import requests url = 'https://api.example.com/upload' with open('report.pdf', 'rb') as f: response = requests.post(url, files={'file': f}) print(response.status_code)

The with statement keeps the file open while requests builds and sends the request, and closes it afterward even if an exception occurs.

Sending Multiple Files in One Request

The files dictionary can hold multiple entries, each representing a separate file field. The server receives each file under its corresponding field name.

python
import requests url = 'https://api.example.com/upload' with open('report.pdf', 'rb') as document, open('photo.jpg', 'rb') as image: files = { 'document': document, 'image': image, } response = requests.post(url, files=files)

If the API expects multiple files under the same field name, use a list of tuples instead of a dictionary:

python
import requests url = 'https://api.example.com/upload' with open('a.pdf', 'rb') as a, open('b.pdf', 'rb') as b: files = [ ('files', a), ('files', b), ] response = requests.post(url, files=files)

This sends multiple parts named files.

Including Additional Form Fields

Multipart uploads often include non-file fields. Pass them in the data parameter; requests includes them as normal form fields in the same multipart body.

python
import requests url = 'https://api.example.com/upload' with open('report.pdf', 'rb') as f: files = {'file': f} data = {'description': 'Q3 report', 'author': 'Alice'} response = requests.post(url, files=files, data=data)

Custom Filenames and File-Like Objects

When you pass a bare file-like object, requests uses the field name as the filename. To control the filename and content type, use a tuple:

python
from io import BytesIO import requests url = 'https://api.example.com/upload' file_data = BytesIO(b'some binary content') files = {'file': ('custom_name.bin', file_data, 'application/octet-stream')} response = requests.post(url, files=files)

The tuple is (filename, file_handle, content_type). You can add a fourth element with extra headers for that part. The same pattern works with a real file object when the server should see a different filename than the local one.

Large Files and Memory Use

Be careful with large uploads. When you provide a file-like object, requests reads the data while it constructs the multipart body, so a large file can use a significant amount of memory. Passing a generator object as a file value is not a streaming solution: requests does not consume a general generator as chunked file data.

For genuinely large files, use a client or library designed for streaming multipart uploads, such as requests-toolbelt's MultipartEncoder, or upload directly to an object-storage service that handles multipart uploads natively. For ordinary files, the built-in files behavior is simple and sufficient.

Common Pitfalls and Error Handling

Forgetting to Close Files

If you open a file with open() and do not close it, the file descriptor leaks. Use a context manager or close the file explicitly after the request.

Incorrect File Mode

Use binary mode (rb) for uploads. Opening the file in text mode (r) can cause encoding errors, especially for non-text files.

Overriding the Content-Type Header

When you pass files, requests sets the Content-Type header to multipart/form-data with a boundary. If you set that header yourself, you can override the boundary and break the request. Let requests manage the header.

Handling HTTP Errors

A non-2xx status code does not raise an exception by default. Check response.status_code or call response.raise_for_status(). If the upload fails, the server may include error details in response.text.

python
import requests url = 'https://api.example.com/upload' with open('report.pdf', 'rb') as f: files = {'file': f} try: response = requests.post(url, files=files) response.raise_for_status() except requests.exceptions.RequestException as exc: print(f'Upload failed: {exc}')

Security Considerations

When your application accepts file uploads, validate file types, size limits, and content before processing; requests sends whatever you provide. On the server, enforce those limits and sanitize filenames. On the client, avoid blindly uploading files from untrusted sources.

Reusing Sessions and Setting Timeouts

If you upload many files to the same host, reuse a requests.Session to take advantage of connection pooling. Pass timeout to the request call to prevent a hung request. In requests, timeout is not read from a session attribute, so set it on each request.

python
import requests session = requests.Session() url = 'https://api.example.com/upload' with open('report.pdf', 'rb') as f: response = session.post(url, files={'file': f}, timeout=30) response.raise_for_status()

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.