• SpringBoot+Thymeleaf上传头像并回显【表单提交】


    参考文章:springboot+thymeleaf实现图片上传并回显https://www.wanmait.com/note/shaowei/javaee/b3717a24fde24d3e89c47765a1a63214.html

    一、新建SpringBoot项目

    添加 spring web和 thymeleaf 的依赖

    二、在templates新建页面

    在页面中添加一个表单和一个文件上传控件、一个按钮用于提交表单

    一个img标签用于图片回显

    1. <div class="head">
    2. <div th:if="${#session.getAttribute('loginUser').headerImage==null}">
    3. <span><img th:src="@{/images/header.png}" width="90" height="90"/>span>
    4. div>
    5. <div th:unless="${#session.getAttribute('loginUser').headerImage==null}">
    6. <span><img th:src="@{|/image/${#session.getAttribute('loginUser').headerImage}|}"width="90" height="90"/>span>
    7. div>
    8. <form action="/web/loan/page/uploadHeader" method="post" enctype="multipart/form-data">
    9. <input type="file" value="选择头像" accept="image/*">
    10. <input type="submit" value="上传头像">
    11. form>
    12. div>

    三、新建控制器

    页面提交表单后上传图片并返回到此页面

    1. //获取本地文件 更新头像
    2. @PostMapping("/loan/page/uploadHeader")
    3. public String uploadHeader(MultipartFile file, HttpServletRequest request, Model model) throws IOException {
    4. //1.获取上传文件名字
    5. String fileName = file.getOriginalFilename();
    6. //2.通过上传文件名字截图后缀名
    7. String fileNameLast = fileName.substring(fileName.indexOf("."));
    8. //3.定义新的文件名字
    9. String newFileName = UUID.randomUUID().toString() + fileNameLast;
    10. //4.获取上传图片路径
    11. String path = ResourceUtils.getURL("classpath:").getPath() + "static/image/";
    12. File uploadPath = new File(path + newFileName);
    13. //5.如果上传目录不存在,创建目录
    14. if (!uploadPath.exists()) {
    15. uploadPath.mkdirs();
    16. }
    17. //6.上传文件
    18. file.transferTo(uploadPath);
    19. //7.更新 用户头像
    20. User user = (User) request.getSession().getAttribute(Constants.LOGIN_USER);
    21. user.setHeaderImage(newFileName);
    22. userService.insertHeaderImage(user);
    23. return "myCenter";
    24. }
    1. //更新 用户头像
    2. @Override
    3. public void insertHeaderImage(User user) {
    4. userMapper.updateByPrimaryKeySelective(user);
    5. }

     

    四、在application.properties配置文件

    添加上传文件大小的控制

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

    五、运行项目

  • 相关阅读:
    SpringBoot自动装配原理
    Promise从入门到精通 (第二章 Promise的理解和使用)
    misc类设备与蜂鸣器驱动==Linux驱动开发6
    JS构造函数和原型
    跟着cherno手搓游戏引擎【27】升级2DRenderer(添加旋转)
    Tomcat颁布自定义SSL(Https)证书
    HTTP 响应头Cache-Control
    纵横职场的8招秘诀,高手都这么干
    如何在 Vue 中使用 防抖 和 节流
    求解八皇后问题
  • 原文地址:https://blog.csdn.net/qq_45037155/article/details/128175702