Phoenix多部分文件上传返回415 Unsupported Media Type问题排查
First off, let’s clear up the Accept-Encoding question: this is almost never the cause of a 415 error for multipart uploads. Accept-Encoding tells the server what compression formats your client can handle for responses, but a 415 error relates to the request’s media type (the Content-Type header) not being supported by the server. Unless you’ve built custom logic that incorrectly ties Accept-Encoding to request parsing, you can rule this out as the root issue.
Now let’s dive into the actual likely culprits:
Missing or malformed
Content-Typeheader
Even if you’re sending a multipart request, Phoenix requires theContent-Typeheader to explicitly include a boundary value. It should look like this:Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
If you omit the boundary, or the boundary value doesn’t match what’s actually used in the request body to separate parts, Phoenix’s parser won’t recognize the request as valid multipart data and will throw a 415.Incomplete Phoenix parser configuration
You mentioned you’ve configured Phoenix to accept multipart, but double-check these spots:- In your
config/config.exs(or environment-specific config), make sure:multipartis included in the endpoint’s parsers list:config :your_app, YourAppWeb.Endpoint, parsers: [:urlencoded, :multipart, :json], # ... other configs - Verify that the route handling your upload is using a pipeline that includes the parser. If you’ve defined a custom pipeline, ensure it doesn’t exclude the
:multipartparser or override the Content-Type handling.
- In your
Invalid multipart request body structure
Sometimes the issue isn’t the header, but the actual structure of the request body. Common mistakes include:- Boundary strings that don’t match between the header and the body
- Missing closing boundary markers
- Malformed part headers (e.g., invalid
Content-Dispositionfor file fields)
Test with a simple, known-good request to rule this out. For example, use curl to send a test file:
curl -X POST -F "upload=@./test-file.txt" https://your-app.com/upload-endpointIf this works, your original request has a structural issue.
Custom plugs interfering with request parsing
If you have any custom plugs that run before Phoenix’s default parsers, they might be modifying the request headers or body in a way that breaks multipart parsing. Try temporarily disabling custom plugs one by one to see if the error goes away—this can help isolate the problematic code.
Start with checking the Content-Type header and boundary first; that’s the most common fix for this scenario.
内容的提问来源于stack exchange,提问作者nullnullnull

