文件上传springboot
前端
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form th:action="@{/test1}" method="post" enctype="multipart/form-data">
<input type="text" name="name">
<input type="text" name="username">
<input type="file" name="file">
<input type="submit">
</form>
</body>
</html>
后端
@RequestMapping("/test1")
public String test1(User user, @RequestParam("file") MultipartFile pic) {
System.out.println("接收到的" + user);
System.out.println("进入了test方法");
// ResourceUtils.getURL("classpath:") 是获取当前文件的resources路径
try {
// 获取文件的原始名称
String oldFileName = pic.getOriginalFilename();
String realPath = ResourceUtils.getURL("classpath:").getPath() + "static/files";
// 处理文件上传
realPath=realPath.substring(1);
File file = new File(realPath);
System.out.println(file.exists());
if(!file.exists())
file.mkdir();
System.out.println(realPath);
pic.transferTo(new File(realPath,oldFileName));
System.out.println("/files/"+oldFileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/test";
}