当前位置:   article > 正文

springboot实现头像图片上传显示功能_java头像设置spring boot

java头像设置spring boot

1.创建springboot项目,加入spring-web、thymeleaf依赖

2.在类路径下的template目录下新建demo.html,并编写如下代码:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>修改头像</title>
  6. </head>
  7. <body>
  8. //上传图片
  9. <form action="/upload" method="post" enctype="multipart/form-data">
  10. <input type="file" name="file" accept="image/*">
  11. <br>
  12. <input type="submit" value="上传" accept="image/*">
  13. </form>
  14. <br>
  15. //显示图片
  16. <img th:src="@{${filename}}" style="width: 200px">
  17. </body>
  18. </html>

3.编写controller类接收图片

  1. @Controller
  2. public class ImgesController {
  3. //跳转页面
  4. @RequestMapping("/jump")
  5. public String jumpPage(){
  6. return "demo";
  7. }
  8. //保存图片到本地并回显图片
  9. @PostMapping("/upload")
  10. public String uploadImage(MultipartFile file, Model model) throws IOException {
  11. //获取上传文件的名字
  12. String fileName = file.getOriginalFilename();
  13. //通过上传文件名字截后缀名
  14. String fileext = fileName.substring(fileName.indexOf("."));
  15. //定义新的文件名字
  16. String newFileName = UUID.randomUUID().toString()+fileext;
  17. //获取上传图片路径
  18. String path = ResourceUtils.getURL("classpath:").getPath()+"static/images/";
  19. //拼接路径和文件名
  20. File uploadPath = new File(path+newFileName);
  21. //如果上传目录不存在,创建目录
  22. if(!uploadPath.exists()){
  23. uploadPath.mkdirs();
  24. }
  25. //上传文件
  26. file.transferTo(uploadPath);
  27. //把图片路径存入数据库
  28. System.out.println("用户头像图片存放的路径已存入数据库");
  29. //把图片放入model
  30. model.addAttribute("filename","/images/"+newFileName);
  31. //跳转到demo.html页面
  32. return "demo";
  33. }
  34. }

4.配置properties文件

  1. #单个文件上传的最大值
  2. spring.servlet.multipart.max-file-size=5MB
  3. #上传文件总的最大值
  4. spring.servlet.multipart.max-request-size=10MB

5.测试

浏览器地址栏输入测试url:http://localhost:8080/jump   测试

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/393397
推荐阅读
相关标签
  

闽ICP备14008679号