Sending multiple files in a single request with the Python requests
library is straightforward. You can achieve this by constructing a multipart/form-data request, which is the type of request that web forms typically use to upload files.
Here's how you can do it:
- Import the
requests
library. - Construct the
files
dictionary, where each key is the name of the form field associated with the file upload. The value will be a tuple consisting of:- The filename (or
None
to use the filename of the file object). - The file object (or file-like object).
- The content type (or
None
to use the default content type).
- The filename (or
- Make a POST request with the
files
parameter.
Below is an example of uploading two files in a single request using requests
:
import requests
# Define the URL to the endpoint where you're sending the files
url = 'http://example.com/upload'
# Open the files in binary mode
with open('file1.txt', 'rb') as file1, open('file2.png', 'rb') as file2:
# Create the files dictionary. The keys are the names of the form fields.
files = {
'text_file': ('custom_filename.txt', file1, 'text/plain'),
'image_file': (file2.name, file2, 'image/png')
}
# Send the POST request with the files
response = requests.post(url, files=files)
# Check if the request was successful and print the response
if response.ok:
print('Upload successful.')
print(response.text)
else:
print('Upload failed.')
In this example, we are uploading a text file and a PNG image. The custom_filename.txt
is the name we want to give to the uploaded file1.txt
. For the image file, we are using the original filename.
Make sure that the keys in the files
dictionary match the names expected by the server-side script or API that is handling the upload. If you're not sure what these should be, you might need to consult the API documentation or the HTML of the form that typically handles the upload.
Remember that when using with
to open the files, they will be automatically closed after the with
block. If you need to handle files manually, don't forget to close them after the request is made to avoid resource leaks.
This is the Python way to do it. If you need to send multiple files in a single request from a client-side JavaScript application, you'll use the FormData
object and the fetch
API or XMLHttpRequest
. Here's an example using fetch
:
// Create a new FormData object
let formData = new FormData();
// Append files to the FormData object
formData.append('text_file', new Blob(['File contents'], { type: 'text/plain' }), 'file1.txt');
formData.append('image_file', fileInputElement.files[0]);
// Define the URL to the endpoint where you're sending the files
const url = 'http://example.com/upload';
// Make the fetch request
fetch(url, {
method: 'POST',
body: formData
})
.then(response => {
if (response.ok) {
return response.text();
} else {
throw new Error('Upload failed.');
}
})
.then(text => console.log('Upload successful:', text))
.catch(error => console.error('Error:', error));
In this JavaScript example, fileInputElement
is a reference to an <input type="file">
HTML element from which you can get the files chosen by the user.
Both the Python and JavaScript examples demonstrate how to send multiple files in a single request to a server. The specific implementation on the server-side to handle these files will depend on the technology and framework you're using.