File uploads generally use a request body in multipart/form-data format. The code to handle uploading files in Spring Boot is as follows:

1
2
3
4
5
@PostMapping(path = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public void upload(@RequestParam("file1") MultipartFile file1,
        @RequestParam("file2") MultipartFile file2) throws IOException, ServletException {
    // Processing of uploaded files...
}

The code above the upload method declares 2 parameters (including the form name of the file), representing 2 files. If we don’t know how many files are uploaded and the name of the file form. Then how to get all the uploaded files?

Servlet 3.0 provides a new Part interface which describes each uploaded file in the multipart/form-data request.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
@PostMapping(path = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public void upload(HttpServletRequest request) throws IOException, ServletException {

    // Each file in a Multipart request
    Collection<Part> parts = request.getParts();

    for (Part part : parts) {
        
        // Type of file
        String contentType = part.getContentType();
        // Form Name
        String name = part.getName();
        // Original file name
        String fileName = part.getSubmittedFileName();
        // File Size
        long size = part.getSize();

        log.info("contentType={}, name={}, fileName={}, size={}", contentType, name, fileName, size);
        
        
        // Read file contents
        try(InputStream inputStream = part.getInputStream()){
            
        }
        
        // It is also possible to write directly to the specified file.
        // part.write(String fileName);
        
        // Some other methods about header.
        
        // part.getHeader(String name);
        // part.getHeaderNames();
        // part.getHeaders(String name);
        
    }
}

Note that the contents of a file can only be read once. part.getInputStream() and part.write(String fileName) can only execute one of these methods.

Reference https://springboot.io/t/topic/4853