先简单的写个页面upload.html,用来模拟多文件上传的操作,内容如下:
<!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>
上传的控制器类UploadController信息如下:
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;
}
}
页面访问http://localhost:8080/upload_html,进入上传页面进行操作,如下:
点击上传,在控制器上传方法中打上一个断点,观察参数情况,如下:
可以发现此时后台已经能够接收到多个文件的入参了。接下来根据自己的业务逻辑操作即可。