Spring Boot multiple file upload

First, simply write a page upload.html to simulate the operation of multi-file upload. The content is as follows:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>多文件上传</title>
</head>
<body>
<form th:action="@{/upload}" method="post" enctype="multipart/form-data">
    照片1:<input type="file" name="photo"/><br/>
    照片2:<input type="file" name="photo"/><br/>
    照片3:<input type="file" name="photo"/><br/>
    <input type="submit" value="上传">
</form>
</body>
</html>

The uploaded controller class UploadController information is as follows:

package com.springboot.advance.controller;

import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class UploadController {
    
    

    @GetMapping("/upload_html")
    public String uploadHtml() {
    
    
        return "upload";
    }

    @PostMapping("/upload")
    @ResponseBody
    public String upload(HttpServletRequest httpRequest) {
    
    
        if (httpRequest instanceof MultipartHttpServletRequest) {
    
    
            MultipartHttpServletRequest request = (MultipartHttpServletRequest) httpRequest;
            List<MultipartFile> photos = request.getFiles("photo");
        }
        return null;
    }
}

Visit http://localhost:8080/upload_html on the page and enter the upload page to operate, as follows:
Insert picture description here

Click Upload, put a breakpoint in the controller upload method, and observe the parameters as follows:
Insert picture description here

It can be found that the background has been able to receive the input parameters of multiple files. Then operate according to your own business logic.

Guess you like

Origin blog.csdn.net/weixin_38106322/article/details/110525828