Skip to content

Conversation

@gvengel
Copy link

@gvengel gvengel commented Nov 11, 2025

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 #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 #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
)

This allows for properly setting the multipart boundary even if the Content-Type has been set on a Session.
@gvengel
Copy link
Author

gvengel commented Nov 11, 2025

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant