python requests post file multipart/form-data

Python Requests Post File Multipart/Form-Data

If you are working with Python and want to upload a file, the requests module can be used to do so. The requests.post method can be used to send a POST request to a server. In order to upload a file, you need to set the Content-Type header to multipart/form-data.

Example Code:


import requests

url = 'http://example.com/upload'
files = {'file': open('/path/to/file.txt', 'rb')}
headers = {'Content-Type': 'multipart/form-data'}

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

print(response.text)

In this code, we are uploading a file named file.txt using the requests.post method. We first define the URL where we want to upload the file. We then open the file in binary mode and pass it to the files parameter of the requests.post method. We also set the Content-Type header to multipart/form-data.

The server should respond with a message indicating whether the upload was successful or not. You can print the response text using the response.text attribute.

If you have multiple files to upload, you can pass them as a list of tuples to the files parameter:


import requests

url = 'http://example.com/upload'
files = [('file1', open('/path/to/file1.txt', 'rb')),
         ('file2', open('/path/to/file2.txt', 'rb'))]
headers = {'Content-Type': 'multipart/form-data'}

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

print(response.text)

In this code, we are uploading two files named file1.txt and file2.txt.

Another way to upload files using requests is to use the data parameter instead of the files parameter. In this case, you need to encode the file content as base64 and pass it as a string:


import requests
import base64

url = 'http://example.com/upload'
with open('/path/to/file.txt', 'rb') as f:
    encoded_file = base64.b64encode(f.read()).decode('utf-8')
data = {'file': encoded_file}
headers = {'Content-Type': 'application/json'}

response = requests.post(url, json=data, headers=headers)

print(response.text)

In this code, we are encoding the contents of the file as base64 and passing it as a string in a JSON object using the json parameter. We set the Content-Type header to application/json.

These are some ways to upload files using the requests module in Python. Choose the method that best suits your needs.