SpringBoot file upload sample code and process analysis

illustrate

File upload, everyone should have noticed in PostMan or ApiPost and other common tools, when the body is from-data (form submission), we can choose the file to upload, as shown below:

 This article mainly introduces the use of SpringBoot backend to receive this file.

the code

The code is very simple, and the SpringBoot project can be used directly by copying it

If you need to download the source code, click here update_demo.zip - Lanzuoyun

@Slf4j
@RestController
@RequestMapping("/")
public class DemoController {

    @PostMapping(value = "/demo")
    public String uploading(@RequestParam("file") MultipartFile file) {
        String filePath = System.getProperty("java.io.tmpdir") + file.getOriginalFilename();
        log.info("文件上传到了:{}", filePath);
        try (FileOutputStream out = new FileOutputStream(filePath)){
            out.write(file.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
            return "uploading failure";
        }
        log.info("文件上传成功!");
        return "uploading success";
    }

}

test

Use the request sending tool to send a request for testing, where the file parameter selects a random file for testing:

 The log successfully outputs the file upload location:

 View the contents of the files in the corresponding directory:

 After testing the function is normal, let's look at the principle now.

analyze

DispatcherServlet

First we open org.springframework.web.servlet.DispatcherServlet#initStrategies

The first one (the red box in the figure) is the method we are looking for:

You can see that this object is initialized.

judgement

After initializing the object is not enough, it is necessary to determine whether a request is a file upload request or this class:

 into this method:

Enter this method, enter: org.springframework.web.multipart.commons.CommonsMultipartResolver#isMultipart

You can see this method: org.apache.commons.fileupload.servlet.ServletFileUpload#isMultipartContent

Just two checks: detecting the POST method and judging that the ContentType is multipart;

Return to the check logic just now: 

 This method is normally called, the location is: org.springframework.web.multipart.MultipartResolver#resolveMultipart 

It is determined whether it is lazy loading or not. In fact, it is a combination of various required parameters:

The official explanation is: parse the given HTTP request into multipart files and parameters, and wrap the request in a MultipartHttpServletRequest object, which provides access to the file descriptor and makes the contained parameters available through the standard ServletRequest method to access.

Click to see a bunch of things that basically get the file information and decode it. 

The above is the process of file upload

Guess you like

Origin blog.csdn.net/qq_20051535/article/details/123971892
Recommended