保存到本地文件夹
<form role="form" th:action="@{/upload}" method="post" enctype="multipart/form-data">
<!-- 单个文件上传 -->
<input type="file" name="headerImg">
<!-- 多文件上传 -->
<input type="file" name="photos" multiple>
<button type="submit">提交</button>
</form>
@PostMapping("/upload")
public String upload(@RequestPart("headerImg") MultipartFile headerImg,
@RequestPart("photos") MultipartFile[] photos) throws IOException {
if(!headerImg.isEmpty()){ // 判断是否为空
// 保存到本地文件夹
String originalFilename = headerImg.getOriginalFilename();
headerImg.transferTo(new File("H:\\cache\\"+originalFilename));
}
if(photos.length > 0){
for (MultipartFile photo : photos) { // 遍历单个文件
if(!photo.isEmpty()){
String originalFilename = photo.getOriginalFilename();
photo.transferTo(new File("H:\\cache\\"+originalFilename));
}
}
}
return null;
}
spring.servlet.multipart.max-file-size=10MB # 上传单个文件大小
spring.servlet.multipart.max-request-size=100MB # 上传多个文件的总大小
上传到服务器
- 业务逻辑:将文件上传到tomcat服务器,返回给前端一个路径;之后将这个路径存入数据库
@RestController
@CrossOrigin
public class FileUpload {
@RequestMapping("/upload")
public RespResult fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest req) {
try {
System.out.println("name+"+ file.getOriginalFilename());
String[] split = file.getOriginalFilename().split("[.]");
String hz = split[split.length -1]; // 获取文件后缀
String replace = UUID.randomUUID().toString().replace("-", "");
String url = getClass().getResource("/").getPath(); // 获取classes的路径
System.out.println("url:" + url);
String path = replace + "." + hz;
String realPath = req.getServletContext().getRealPath("/"); // 获取tomcat路径
System.out.println(realPath);
// 将文件写入tomcat,File.separator确保在任何系统中路径不会出错
file.transferTo(new File(realPath + File.separator + path));
return RespResult.success(path);
} catch (IOException e) {
e.printStackTrace();
return RespResult.error("文件上传异常");
}
}
}