Master Spring Boot 3 File Upload: 5 Practical Techniques & Code Samples
This article demonstrates multiple ways to handle file uploads in Spring Boot 3, covering basic @RequestParam usage, Map and object binding, jakarta.servlet.http.Part, and @RequestPart for combined JSON and file data, complete with code snippets and practical examples.
1. Introduction
Spring Boot makes file upload simple and efficient. By using Spring MVC's MultipartFile together with the @RequestParam annotation, developers can receive uploaded files with just a few lines of code.
2. Practical Cases
2.1 Basic Application
<code>@PostMapping("/form")
public String handleFormUpload(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file) throws Exception {
if (!file.isEmpty()) {
file.transferTo(new File("d:\\upload\\" + file.getOriginalFilename()));
return "success";
}
return "failure";
}</code>When the parameter type is MultipartFile , the @RequestParam("file") name must match the form field name.
You can also declare List<MultipartFile> to handle multiple files with the same field name.
2.2 Receiving Files with a Map
<code>@PostMapping("/map")
public String handleMapUpload(@RequestParam("name") String name,
@RequestParam Map<String, MultipartFile> files) throws Exception {
files.forEach((key, file) -> {
System.out.println("name = " + key);
try {
file.transferTo(new File("d:\\upload\\" + file.getOriginalFilename()));
} catch (Exception e) { /* handle */ }
});
return "success";
}</code>If @RequestParam is used without specifying a name and the parameter type is Map<String, MultipartFile> or MultiValueMap<String, MultipartFile> , Spring automatically binds all uploaded parts, using the form field name as the key.
2.3 Encapsulating into an Object
You can bind multipart data to a command object.
<code>@PostMapping("/dataform")
public String handleDataFormUpload(DataForm form) throws Exception {
System.err.println("name = " + form.getName());
MultipartFile file = form.getFile();
file.transferTo(new File("d:\\upload\\" + file.getOriginalFilename()));
return "success";
}
// DataForm definition
public class DataForm {
private String name;
private MultipartFile file;
// getters and setters
}</code>2.4 Using jakarta.servlet.http.Part
<code>@PostMapping("/part")
public String handlePartUpload(@RequestParam("name") Part name,
@RequestParam Part file) throws Exception {
String value = StreamUtils.copyToString(name.getInputStream(), StandardCharsets.UTF_8);
System.err.println("name = " + value);
FileOutputStream out = new FileOutputStream(new File("d:\\upload\\" + file.getSubmittedFileName()));
StreamUtils.copy(file.getInputStream(), out);
out.close();
return "success";
}</code>Both regular fields and files can be received via Part . The console output shows the field names and headers.
2.5 Using @RequestPart for JSON + File
<code>@PostMapping("/requestpart")
public Object requestPart(@RequestPart("user") User user,
@RequestPart("file") MultipartFile file) throws Exception {
file.transferTo(new File("d:\\upload\\" + file.getOriginalFilename()));
return user;
}</code>Front‑end example:
<code>let form = new FormData();
form.append('file', document.querySelector('#file').files[0]);
let data = {age: 5000, name: '中国🇨🇳'};
let user = new Blob([JSON.stringify(data)], {type: 'application/json'});
form.append('user', user);
axios({
method: 'post',
url: 'http://localhost:8080/api/request/requestpart',
headers: {'Content-Type': 'multipart/form-data'},
data: form
});
</code>Parameters can be validated with @Valid on the User object.
<code>public Object requestPart(@Valid @RequestPart("user") User user,
@RequestPart("file") MultipartFile file) { }
</code>Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.