How to Handle File Upload in Spring Boot: Simple Guide
@PostMapping that accepts a MultipartFile parameter. Ensure your application has spring-boot-starter-web dependency and that multipart support is enabled in application.properties.Why This Happens
When file upload handling is not set up correctly, Spring Boot may fail to bind the uploaded file to the controller parameter, causing errors like Required request part 'file' is not present or MultipartException. This usually happens if the controller method does not accept MultipartFile or multipart support is not enabled.
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class FileUploadController { @PostMapping("/upload") public String uploadFile(String file) { return "File uploaded: " + file; } }
The Fix
Change the controller method to accept a MultipartFile parameter annotated with @RequestParam. Also, ensure multipart support is enabled in application.properties by setting spring.servlet.multipart.enabled=true (enabled by default). This allows Spring Boot to handle the file upload correctly.
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; @RestController public class FileUploadController { @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return "No file selected to upload."; } return "File uploaded: " + file.getOriginalFilename(); } }
Prevention
Always use MultipartFile for file parameters in controller methods. Confirm multipart support is enabled in your Spring Boot app. Validate file presence and size before processing. Use @RequestParam with the exact form field name. Test uploads with tools like Postman or curl to ensure correct multipart requests.
Related Errors
Common related errors include:
- MaxUploadSizeExceededException: File size exceeds configured max size. Fix by setting
spring.servlet.multipart.max-file-sizeandspring.servlet.multipart.max-request-size. - Required request part 'file' is not present: Happens if form field name mismatches or multipart request is missing.
- MultipartException: Usually caused by missing multipart resolver or incorrect request type.