Sending zip files over HTTP can be useful for submitting archives of code, data, or other content to a web application. Python's Requests library makes this easy with multipart form data.
Why Use Multipart Form Data?
Multipart form data encodes file contents and metadata together into the body of a POST request. This allows sending files through standard HTTP, without having to write them to disk on the server or use custom protocols.
The main alternatives like encoding the zip file contents directly into the body or base64 encoding it make the requests less efficient and harder to handle on the server. Multipart encoding is optimized for sending files.
Posting a Zip File with Requests
First we need to import Requests and create the zip file data to send:
import requests
import io
import zipfile
# Create in-memory zip file
data = io.BytesIO()
with zipfile.ZipFile(data, mode="w") as z:
z.write("file1.txt")
z.write("folder/file2.txt")
data.seek(0)
We wrap the zip file in an
Next we post it as multipart form data. The files parameter lets us send binary file streams:
r = requests.post("https://example.com/upload",
files={"zip_file": ("archive.zip", data)})
We include the desired file name that will be saved on the server along with the file data.
Handling the Response
The server should return a 2XX status code on success. We can load the text body to check for errors:
print(r.text)
And that's it! The server now has the zip file extracted and available however it needs to process it.