Python

Multipart File Upload

admin by @admin ADMIN
Jun 15, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
POST a file (or several) as multipart/form-data using requests, with optional extra form fields. Lets you upload to /avatar-style endpoints without manual boundary construction.
Python
Raw
import mimetypes
import requests
from pathlib import Path

def upload_file(
    url: str,
    file_path: str | Path,
    *,
    field: str = "file",
    extra: dict[str, str] | None = None,
    headers: dict[str, str] | None = None,
) -> requests.Response:
    file_path = Path(file_path)
    mime = mimetypes.guess_type(file_path.name)[0] or "application/octet-stream"
    with file_path.open("rb") as f:
        files = {field: (file_path.name, f, mime)}
        return requests.post(url, files=files, data=extra or {}, headers=headers or {}, timeout=60)

resp = upload_file(
    "https://api.example.com/avatar",
    "/tmp/avatar.png",
    extra={"user_id": "42"},
    headers={"Authorization": "Bearer XYZ"},
)
resp.raise_for_status()
print(resp.json())
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.