这里基本和SpringBoot2上传单个文件的方式相同,只不过文件变成了多个
@RestController
public class FileUploadController2 {
private DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("/yyyy/MM/dd/", Locale.CHINA);
@PostMapping("/upload")
public List<String> upload(MultipartFile[] multipartFiles, HttpServletRequest request) {
var files = new ArrayList<String>(multipartFiles.length);
var realPath = request.getServletContext().getRealPath("/");
var format = dateFormat.format(LocalDate.now());
var path = realPath + format;
System.out.println(path);
var file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
try {
for (MultipartFile multipartFile : multipartFiles) {
var originalFilename = multipartFile.getOriginalFilename();
var newName =
UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
multipartFile.transferTo(new File(file, newName));
var s =
request.getScheme()
+ "://"
+ request.getServerName()
+ ":"
+ request.getServerPort()
+ format
+ newName;
files.add(s);
}
} catch (IOException e) {
e.printStackTrace();
}
return files;
}
}
Q.E.D.