requests icon indicating copy to clipboard operation
requests copied to clipboard

Allow multipart uploads when Content-Type has been set on on a Session

Open gvengel opened this issue 2 months ago • 1 comments

It's currently impossible to use multipart file uploads with a Session when the Content-Type header has been set session wide. The problem is that the session header takes precedence over the header returned by _encode_files. See https://github.com/psf/requests/issues/6992.

This change adds support for the Content-Type header being explicitly set to None on a multipart file upload, signaling that the session header should be ignored. Similar to the pattern used by https://github.com/psf/requests/pull/1921.

Usage:

from requests import Session
from io import StringIO

fh = StringIO("Lobster Thermidor")

session = Session()
session.headers["Content-Type"] = "application/json"
session.post(
    "http://localhost:8000/",
    data={"menu": "Egg and bacon. Egg, sausage, and bacon. Egg and Spam"},
    files={"file": ("special.txt", fh, "text/plain")},
    headers={"Content-Type": None},  # unset the session content-type to allow multipart file upload
)

gvengel avatar Nov 11 '25 08:11 gvengel

Note, I think the "correct" fix is actually for multipart file uploads to always force the Content-Type, since the request must contain the disposition generated by _encode_files to remain valid; however, that would cause an implicate change, so I figured this patch requiring an explicit change from the caller might be safer. Let me know if you are open to forcing the header and I'll update the MR.

gvengel avatar Nov 11 '25 08:11 gvengel