Spring图片上传报415 Unsupported Media Type错误求助
Hey there, let’s tackle that frustrating 415 error together—file uploads in Spring can be finicky, but we’ll break down the most common fixes step by step.
Common Causes & Fixes
1. Frontend Request Format Mismatch
This is the #1 culprit for 415 errors in file uploads. When uploading a file, the browser needs to send the request with multipart/form-data encoding—without it, Spring can’t parse the file content.
- Check your HTML form: Ensure your
<form>tag includesenctype="multipart/form-data". This is mandatory for file uploads. Here’s a correct example:<form method="POST" action="/upload-image" enctype="multipart/form-data"> <input type="file" name="uploadedImage" accept="image/*"> <button type="submit">Upload Image</button> </form> - If using AJAX/Fetch: Don’t manually set the
Content-Typeheader! Use aFormDataobject, and let the browser handle setting the correctmultipart/form-dataheader with the necessary boundary. Manually setting the header without the boundary will break Spring’s parsing. Example:const fileInput = document.querySelector('input[type="file"]'); const formData = new FormData(); formData.append('uploadedImage', fileInput.files[0]); fetch('/upload-image', { method: 'POST', body: formData // No Content-Type header needed here! });
2. Missing or Misconfigured Multipart Support in Spring
Spring requires a MultipartResolver to handle file uploads. If it’s not set up correctly, the app can’t process multipart requests.
- For Spring Boot: Make sure you have the
spring-boot-starter-webdependency (it includes multipart support by default):
You can tweak upload limits in<!-- pom.xml --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>application.propertiesif needed:spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB - For non-Boot Spring: Explicitly define a
CommonsMultipartResolverbean (you’ll also need thecommons-fileuploaddependency):@Bean public CommonsMultipartResolver multipartResolver() { CommonsMultipartResolver resolver = new CommonsMultipartResolver(); resolver.setMaxUploadSize(10485760); // 10MB return resolver; }
3. Incorrect Controller Method Setup
Your controller needs to accept the file the right way—wrong annotations or parameters will trigger a 415 error.
- Use
@RequestParamfor the file: Don’t use@RequestBodyhere—we’re dealing with multipart form data, not JSON. Correct controller example:@PostMapping("/upload-image") public String handleImageUpload(@RequestParam("uploadedImage") MultipartFile imageFile) throws IOException { // Process the file: convert to bytes, save to DB, etc. byte[] imageBytes = imageFile.getBytes(); // Add your database storage logic here return "upload-success"; } - Avoid conflicting
consumesattributes: If you addedconsumes = MediaType.APPLICATION_JSON_VALUEto your@PostMapping, remove it. Or explicitly set it toMediaType.MULTIPART_FORM_DATA_VALUEif needed.
4. Mismatched Parameter Names
Double-check that the name attribute in your frontend file input matches the value in @RequestParam. For example, if your input is <input name="profilePic">, your controller should use @RequestParam("profilePic") MultipartFile file.
5. Bonus: Database Storage Tips (Post-Fix)
Once you resolve the 415 error, make sure your database column is set to store binary data (like BLOB in MySQL, BYTEA in PostgreSQL). Example entity field:
@Lob @Column(name = "image_data") private byte[] imageData;
If you can share your actual backend controller code and frontend HTML/JS, we can pinpoint the exact issue even faster! But these steps cover 90% of the common 415 cases for Spring image uploads.
内容的提问来源于stack exchange,提问作者dorcsi

