Keywords: Spring Boot | Multipart File Upload | 415 Error | @RequestParam | Configuration
Abstract: This article delves into the 415 Unsupported Media Type error encountered during multipart file upload in Spring Boot. By analyzing user-provided Q&A data, it first explains the root cause: the controller method incorrectly uses @RequestBody to handle MultipartFile arrays, as Spring MVC lacks a built-in HttpMessageConverter for this conversion. The core solution is to replace @RequestBody with @RequestParam for proper form field mapping. The article further compares different configuration methods, including using MultipartConfigElement and application.properties for file size limits, and provides complete code examples and best practices. Additionally, it discusses considerations for sending multipart requests with RestTemplate and handling multiple file uploads. Through step-by-step analysis of the problem and multiple implementation approaches, this article offers comprehensive and practical guidance for developers to efficiently implement file upload functionality in Spring Boot applications.
Problem Background and Error Analysis
When implementing file upload functionality in Spring Boot applications, developers often encounter the 415 Unsupported Media Type error. This error typically manifests as: Content type 'multipart/form-data;boundary=XXXXX not supported. Based on the user-provided Q&A data, the root cause lies in improper parameter binding in the controller method. The user initially used @RequestBody MultipartFile[] submissions to receive files, but the Spring MVC framework does not have a built-in HttpMessageConverter that can directly convert a multipart request body into a MultipartFile array. This is because each part of a multipart request (e.g., a file field) is treated as a request parameter rather than the entire request body.
Core Solution: Correct Usage of @RequestParam
According to the best answer (Answer 1, score 10.0), @RequestBody should be replaced with @RequestParam to correctly map the file field from the form. For example, if the HTML form has a file input field with the name attribute "file", the controller method should be modified as:
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
// File processing logic
return new ResponseEntity<>("Upload successful", HttpStatus.OK);
}
For multiple file uploads, a MultipartFile[] array can be used, ensuring all file input fields share the same name attribute (e.g., name="files"):
@RequestMapping(value = "/uploadMultiple", method = RequestMethod.POST)
public ResponseEntity<String> handleMultipleFiles(@RequestParam("files") MultipartFile[] files) {
for (MultipartFile file : files) {
// Process each file
}
return new ResponseEntity<>("All files uploaded", HttpStatus.OK);
}
This approach leverages Spring MVC's multipart parsing mechanism directly, eliminating the need for additional HttpMessageConverter configuration. Additionally, @RequestParam allows specifying attributes like required and defaultValue, offering more flexible parameter handling.
Configuring Multipart Support
Spring Boot supports multipart file upload by default, but developers may need custom configurations. The user Q&A mentions two configuration methods:
- Using Java Configuration: Set file size limits and other parameters via
MultipartConfigElementandCommonsMultipartResolver(orStandardServletMultipartResolver). For example:
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setMaxFileSize("10MB");
factory.setMaxRequestSize("50MB");
return factory.createMultipartConfig();
}
<ol start="2">
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=50MB
For Spring Boot 2.x and above, StandardServletMultipartResolver is recommended, as it relies on Servlet 3.0 multipart support and requires no extra dependencies. If using CommonsMultipartResolver, add the commons-fileupload dependency.
Client-Side Implementation Examples
The user attempted various client-side sending methods, including HTML forms and RestTemplate. Below are correct implementation examples:
- HTML Form: Ensure
enctype="multipart/form-data"and the correct action URL. For example:
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
- Sending Multipart Requests with RestTemplate: Requires proper configuration of
MultiValueMapandHttpHeaders. The code in user attempt 3 is close to correct but should ensure usingMultipartBodyBuilderor similar tools to build the request body. Spring 5 offers a more concise way:
RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", new FileSystemResource("path/to/file"));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
Note: RestTemplate does not support multipart requests by default; add FormHttpMessageConverter or use MultipartBodyBuilder (Spring 5+).
Advanced Topics and Best Practices
Beyond basic configuration, developers should consider the following aspects:
- Error Handling: Add exception handling in controller methods, such as catching
IOExceptionor file size limit exceptions, and return appropriate HTTP status codes (e.g., 400 Bad Request). - File Validation: Check file type, size, and content to prevent malicious uploads. Use methods like
getContentType()andgetSize()fromMultipartFile. - Using MultipartHttpServletRequest: If access to multipart request details (e.g., part headers) is needed, change the parameter type to
MultipartHttpServletRequestand retrieve files viagetFileMap(). - Asynchronous Processing: For large file uploads, consider asynchronous processing to avoid blocking request threads. Spring MVC supports
@Asyncannotation orDeferredResult.
In summary, resolving the 415 error in Spring Boot multipart file upload hinges on correctly using @RequestParam to bind file parameters and properly configuring multipart support. Through this article's step-by-step analysis and code examples, developers can quickly implement stable and efficient file upload functionality.