springboot实现头像图片上传显示功能

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   测试

  • 1
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值