Python Requests Post Base64
If you want to send a file or image in your HTTP request body, you can encode it in Base64 format and send it as a string. Python Requests is a popular library to work with HTTP requests and responses. Here's how you can send a Base64-encoded file or image using the Requests library:
import requests
import base64
with open("example.png", "rb") as f:
data = f.read()
encoded = base64.b64encode(data)
response = requests.post("https://example.com/upload", data=encoded)
Let's break down the code:
import requests
: Import the Requests libraryimport base64
: Import the Base64 librarywith open("example.png", "rb") as f:
: Open the file in binary modedata = f.read()
: Read the contents of the file into a variableencoded = base64.b64encode(data)
: Encode the contents of the file in Base64 formatresponse = requests.post("https://example.com/upload", data=encoded)
: Send a POST request with the encoded data in the request body
If you have a file that is already a Base64 string, you can directly send it in the request body without encoding it again. Here's an example:
import requests
with open("example.txt", "r") as f:
data = f.read()
response = requests.post("https://example.com/upload", data=data)
Let's break down the code:
import requests
: Import the Requests librarywith open("example.txt", "r") as f:
: Open the file in text modedata = f.read()
: Read the contents of the file into a variableresponse = requests.post("https://example.com/upload", data=data)
: Send a POST request with the data in the request body
Conclusion
Python Requests library makes it easy to work with HTTP requests and responses. You can send Base64-encoded files or images in the request body using the library. If you have a file that is already a Base64 string, you can directly send it in the request body without encoding it again.