SpringBoot文件上传的方法有以下几种:
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
// 处理文件上传逻辑
return "upload success";
}
@PostMapping("/upload")
public String uploadFile(@RequestPart("file") MultipartFile file) {
// 处理文件上传逻辑
return "upload success";
}
@PostMapping("/upload")
public String uploadFile(HttpServletRequest request) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("file");
// 处理文件上传逻辑
return "upload success";
}
无论使用哪种方法,都需要在SpringBoot的配置文件中配置文件上传的相关属性,如最大文件大小、临时文件存储路径等。可以通过在application.properties或application.yml文件中添加以下配置来实现:
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
spring.servlet.multipart.location=/tmp