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.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Master Spring Boot 3 File Upload: 5 Practical Techniques & Code Samples

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

@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";
}

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

@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";
}

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.

@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
}

2.4 Using jakarta.servlet.http.Part

@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";
}

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

@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;
}

Front‑end example:

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
});

Parameters can be validated with @Valid on the User object.

public Object requestPart(@Valid @RequestPart("user") User user,
                           @RequestPart("file") MultipartFile file) { }
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Java backendspring-boot@RequestPartMultipartFilefile-uploadspring-mvccode-samples
Spring Full-Stack Practical Cases
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.