Sending file uploads via HTTP requests is a common task in many Python applications. This guide covers how to upload files using the requests library and multipart/form-data.
Overview
The
Here's what we'll cover:
Follow along with the examples below to learn how to integrate file uploading into your Python applications.
Why Multipart/Form-Data for File Uploads
Browser file upload forms use the
The
Uploading a File with Requests
Uploading a file is just a matter of attaching the binary data as well as metadata to identify the file contents.
Here's an example of posting an image to an upload endpoint:
import requests
url = 'https://api.example.com/upload'
files = {'file': open('image.png', 'rb')}
r = requests.post(url, files=files)
Breaking this down:
The server receives the uploaded filename, content type, and binary file data for further processing.
Uploading Multiple Files
Simply add additional key/value pairs to the files dictionary:
files = {
'file1': open('photo.jpg', 'rb'),
'file2': open('document.pdf', 'rb')
}
r = requests.post(url, files=files)
Each file is transferred with a unique form field name for the server to distinguish.
Setting Custom Filenames
By default the filename sent to the server is based on the file object name. Pass a tuple with the desired filename instead:
files = {
'file': ('myphoto.jpg', open('photo.jpg', 'rb'))
}
Now the uploaded filename sent to the server is
Handling the Response
As with all
if r.status_code == requests.codes.ok:
print('Upload successful')
else:
print('Error, got response:', r.status_code)
Check the status code to see if the upload succeeded. Additionally, parse the response body for server-provided metadata.
Exceptions and Troubleshooting
If the upload fails,
try:
r = requests.post(url, files=files, timeout=10)
except requests.exceptions.Timeout:
print('Request timed out')
except requests.exceptions.RequestException as req_err:
print('Error:', req_err)
Catch general
Additionally, enable verbose logging and inspect request parameters to troubleshoot odd server behaviors.
Summary
That covers the main techniques for uploading files via the excellent
With these basics, you can integrate robust file upload capabilities into APIs, web scrapers, and automation scripts built in Python.