Python Requests Post Multipart/Form-Data
If you want to send a HTTP POST request with multipart/form-data for uploading files, you can use Python requests library. In this HTTP POST request, data is sent as a series of key-value pairs, with each pair having the key as the 'name' of the form element and the value as the 'value' of the form element.
The requests.post() method can be used to send the POST request. The data parameter of this method is a dictionary containing the form values. The files parameter is a dictionary containing file names and file objects.
Example:
import requests
url = 'http://example.com/upload'
files = {'file': open('file.txt', 'rb')}
data = {'name': 'Raju', 'email': '[email protected]'}
response = requests.post(url, files=files, data=data)
print(response.status_code)
In this example, we are sending a HTTP POST request to the URL 'http://example.com/upload'. We are sending two form values - 'name' and 'email'. We are also uploading a file named 'file.txt'.
The open() function is used to open the file in binary mode. The 'rb' mode is used to read the file in binary mode.
Alternative:
An alternative way to post multipart/form-data is to use the 'requests_toolbelt' library. This library provides a MultipartEncoder class which can be used to upload files with multipart/form-data.
from requests_toolbelt import MultipartEncoder
import requests
url = 'http://example.com/upload'
file = {'file': ('file.txt', open('file.txt', 'rb'), 'text/plain')}
data = {'name': 'Raju', 'email': '[email protected]'}
multipart_data = MultipartEncoder(fields={'field0': 'value',
'field1': 'value',
'field2': ('filename', open('file.docx', 'rb'), 'application/vnd.ms-word'),
'field3': ('filename', open('file.png', 'rb'), 'image/png')})
response = requests.post(url, data=multipart_data, headers={'Content-Type': multipart_data.content_type})
print(response.status_code)
In this example, we are using the MultipartEncoder class to upload files with multipart/form-data. The fields parameter of this class is a dictionary containing form values.
The values in the dictionary can be strings, files (tuples containing file names and file objects), or lists of files. The content_type parameter of the request header is set to the content type of the multipart data.