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

编程入门 行业动态 更新时间:2024-10-25 00:27:35

springboot实现头像<a href=https://www.elefans.com/category/jswz/34/1760202.html style=图片上传显示功能"/>

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("用户头像图片存放的路径已存入数据库");//把图片放入modelmodel.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   测试

更多推荐

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

本文发布于:2024-02-17 14:52:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1694422.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图片上传   头像   功能   springboot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!