Uploading Zip Files via HTTP POST with Python Requests

Feb 3, 2024 ยท 2 min read

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 io.BytesIO stream so Requests can read it but we don't have to save it locally.

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.

Browse by tags:

Browse by language:

Tired of getting blocked while scraping the web?

ProxiesAPI handles headless browsers and rotates proxies for you.
Get access to 1,000 free API credits, no credit card required!