Moment For Technology

The Spring Boot implementation file was uploaded

Posted on Dec. 2, 2022, 5:56 p.m. by Lindsey Connolly-Baker
Category: The back-end Tag: Spring Boot

File upload is a common form submission for web pages. Essentially, file upload is a POST request sent by the front end and accepted by the back end. How do you upload files in Spring Boot?

1. Upload a single file

1, the front end

Make a suggestion form with the following code:

form enctype="multipart/form-data" method="POST" action="/upload"
    input type="text" name="imgName" /
    input type="file" name="imgFile" /
    input type="submit" value="upload" /
Copy the code

Note that if you want to upload a file, you must set the form to multipart/form-data format. The encType attribute in the

tag is the one that sets the format of the form data.

specifies that the form entry is a file type.

If you don't want to use the buttons in the form tag, but instead assemble the data yourself, you can write a function like this:

@param {*} file (@param {*} file) */ function upload(@param {*} file) */ file) { let form = new FormData(); // Create a new form object form.append('img', file); Img fetch(requestURL, {method: 'POST', body: form}).then((response) = {return response.json(); // Add a file to the form object named img fetch(requestURL, {method: 'POST', body: form}).then((response) = {return response.json(); }).then((result) = {// console.log(result); })}Copy the code

Get file from input tag:

let input = document.querySelector('input'); Let file = input.files[0]; // The input property files indicates the array of files to select, specifying the index 0 if it is a single fileCopy the code

2, the back end

The default limit is 1MB, so uploading a file larger than that will fail:

# set maximum size of 20 MB spring. The request to the servlet. Multipart. Max - request - size = 20 MB # set maximum size for the 20 MB file upload spring.servlet.multipart.max-file-size=20MBCopy the code

Then write the following method in the Controller class:

@PostMapping("/upload") public String upload(@RequestParam("imgFile") MultipartFile file, @requestparam ("imgName") String name) throws Exception {// Set uploadFile to the project folder. File dir = new File("uploadFile"); if (! dir.exists()) { dir.mkdirs(); } file.transferTo(new File(dir.getAbsolutePath() + File.separator + name + ".png")); Return "Upload complete! Name: "+ name; }Copy the code

Note that the file is of type MultipartFile in Java, and the value in @requestparam is the name of each of our front end forms ( tags), or the name of the FormData object append. It has to be the same for one to one. The action attribute in the front-end form is the address to which the form is submitted, which corresponds to the value in our Controller's @PostMapping.

The MultipartFile instance uses the transferTo method to save the uploaded file to the specified location.


The file is also uploaded to the specified location:

2. Upload multiple files

Uploading multiple files is actually as simple as uploading a single file.

form enctype="multipart/form-data" method="POST" action="/upload"
    input type="text" name="imgColName" /
    input type="file" name="imgFile" multiple /
    input type="submit" value="upload" /
Copy the code

In this case, the back end receives an array of MultipartFile when uploading the file, so change the parameter in the Controller method to type MultipartFile[], and then iterate over it, as shown in the following example:

@PostMapping("/upload") public String upload(@RequestParam("imgFile") MultipartFile[] files, @RequestParam("imgColName") String name) throws Exception { File dir = new File("uploadFile"); if (! dir.exists()) { dir.mkdirs(); } for (MultipartFile file : files) { file.transferTo(new File(dir.getAbsolutePath() + File.separator + file.getOriginalFilename())); } return "Upload complete! "+ name; }Copy the code
About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.