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:

The easiest way to do Web Scraping

Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


Try ProxiesAPI for free

curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

<!doctype html>
<html>
<head>
    <title>Example Domain</title>
    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
...

X

Don't leave just yet!

Enter your email below to claim your free API key: