1.创建springboot项目,加入spring-web、thymeleaf依赖
2.在类路径下的template目录下新建demo.html,并编写如下代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>修改头像</title>
</head>
<body>
//上传图片
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" accept="image/*">
<br>
<input type="submit" value="上传" accept="image/*">
</form>
<br>
//显示图片
<img th:src="@{${filename}}" style="width: 200px">
</body>
</html>
3.编写controller类接收图片
@Controller
public class ImgesController {
//跳转页面
@RequestMapping("/jump")
public String jumpPage(){
return "demo";
}
//保存图片到本地并回显图片
@PostMapping("/upload")
public String uploadImage(MultipartFile file, Model model) throws IOException {
//获取上传文件的名字
String fileName = file.getOriginalFilename();
//通过上传文件名字截后缀名
String fileext = fileName.substring(fileName.indexOf("."));
//定义新的文件名字
String newFileName = UUID.randomUUID().toString()+fileext;
//获取上传图片路径
String path = ResourceUtils.getURL("classpath:").getPath()+"static/images/";
//拼接路径和文件名
File uploadPath = new File(path+newFileName);
//如果上传目录不存在,创建目录
if(!uploadPath.exists()){
uploadPath.mkdirs();
}
//上传文件
file.transferTo(uploadPath);
//把图片路径存入数据库
System.out.println("用户头像图片存放的路径已存入数据库");
//把图片放入model
model.addAttribute("filename","/images/"+newFileName);
//跳转到demo.html页面
return "demo";
}
}
4.配置properties文件
#单个文件上传的最大值
spring.servlet.multipart.max-file-size=5MB
#上传文件总的最大值
spring.servlet.multipart.max-request-size=10MB
5.测试
浏览器地址栏输入测试url:http://localhost:8080/jump 测试