Spring Boot 实现图片上传并回显功能
作者:Mr_YMX 时间:2021-10-11 17:45:20
一、常规形式
1 项目结构
2 配置文件及环境设置
(1)配置文件
# 应用服务 WEB 访问端口
server.port=8080
# spring 静态资源扫描路径
spring.resources.static-locations=classpath:/static/
# 访问template下的html文件需要配置模板
spring.thymeleaf.prefix.classpath=classpath:/templates/
# 是否启用缓存
spring.thymeleaf.cache=false
# 模板文件后缀
spring.thymeleaf.suffix=.html
# 模板文件编码
spring.thymeleaf.encoding=UTF-8
#上传的绝对路径
file.upload.path=G://images/ #最关键#
#绝对路径下的相对路径
file.upload.path.relative=/images/** #最关键#
#设置文件最大值
spring.servlet.multipart.max-file-size=5MB
在相关路径新建文件夹
3 代码
(1)pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
(2)index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="../upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" accept="image/*">
<br>
<input type="text" value="">
<input type="submit" value="上传" class="btn btn-success">
</form>
[[${filename}]]
<br>
<img th:src="@{${filename}}" alt="图片">
</body>
</html>
(3)TestController.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Controller
public class TestController {
/**
* 上传地址
*/
@Value("${file.upload.path}")
private String filePath;
// 跳转上传页面
@RequestMapping("test")
public String test() {
return "Page";
}
// 执行上传
@RequestMapping("upload")
public String upload(@RequestParam("file") MultipartFile file, Model model) {
// 获取上传文件名
String filename = file.getOriginalFilename();
// 定义上传文件保存路径
String path = filePath + "rotPhoto/";
// 新建文件
File filepath = new File(path, filename);
// 判断路径是否存在,如果不存在就创建一个
if (!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}
try {
// 写入文件
file.transferTo(new File(path + File.separator + filename));
} catch (IOException e) {
e.printStackTrace();
}
// 将src路径发送至html页面
model.addAttribute("filename", "/images/rotPhoto/" + filename);
return "index";
}
}
(4)MyWebAppConfigurer
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 资源映射路径
*/
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
/**
* 上传地址
*/
@Value("${file.upload.path}")
private String filePath;
/**
* 显示相对地址
*/
@Value("${file.upload.path.relative}")
private String fileRelativePath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(fileRelativePath).
addResourceLocations("file:/" + filePath);
}
}
4 测试
二、增加异步操作
1 前端ajax
<div class="modal-body">
<form method="post" enctype="multipart/form-data">
<input type="file" name="file" id="img">
<input type="button" value="上传" class="btn btn-outline-primary" onclick="uploadFile()"
style="width: 30%;">
</form>
</div>
<script>
//上传文件
function uploadFile() {
//formData里面存储的数据形式,一对key/value组成一条数据,key是唯一的,一个key可能对应多个value
var myform = new FormData();
// 此时可以调用append()方法来添加数据
myform.append('file', $("#img")[0].files[0]);
//验证不为空
var file = $("#img")[0].files[0];
if (file == null) {
alert("请选择文件");
return false;
} else {
$.ajax({
url: "/user/upLoad",
type: "POST",
data: myform,
async: false,
contentType: false,
processData: false,
success: function (result) {
console.log(result);
alert("上传成功!");
$("#div_show_img").html("<img id='input_img' src='" + result + "'>");
$("#imgPath").attr("value", result);
$("#div_upload").removeClass("show");
},
error: function (data) {
alert("系统错误");
}
});
}
}
</script>
2 后端Controller
@ResponseBody
@RequestMapping("/upLoad")
public String upLoadImage(@RequestParam("file") MultipartFile file) {
// 获取上传文件名
String filename = file.getOriginalFilename();
String suffixName = filename.substring(filename.lastIndexOf("."));
// 定义上传文件保存路径
String path = filePath + "images/";
//生成新的文件名称
String newImgName = UUID.randomUUID().toString() + suffixName;
// 新建文件
File filepath = new File(path, newImgName);
// 判断路径是否存在,如果不存在就创建一个
if (!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}
try {
// 写入文件
file.transferTo(new File(path + File.separator + newImgName));
} catch (IOException e) {
e.printStackTrace();
}
return "/images/images/" + newImgName;
}
来源:https://blog.csdn.net/Mr_YanMingXin/article/details/118484438
标签:Spring,Boot,上传图片,回显
0
投稿
猜你喜欢
SpringBoot返回Json对象报错(返回对象为空{})
2022-06-30 03:31:19
MyBatis-Plus分页插件不生效的解决方法
2023-03-10 20:24:58
JavaCV实现读取视频信息及自动截取封面图详解
2022-05-20 14:43:05
svn 清理失败 (cleanup 失败) 的快速解决方法
2022-10-25 11:22:40
SpringBoot基于Swagger2构建API文档过程解析
2022-12-06 20:42:58
解决Springboot get请求是参数过长的情况
2023-11-27 16:45:37
基于idea Maven中的redis配置使用详解
2023-11-29 11:57:28
关于Mybatis-Plus Wrapper是否应该出现在Servcie类中
2023-11-28 22:04:56
java实现图片写入高清字体及带边框的方法
2023-11-29 03:43:47
Spring如何利用@Value注解读取yml中的map配置
2023-07-24 21:18:00
Java中的static关键字修饰属性和方法(推荐)
2021-09-29 05:46:20
如何在IDE部署springboot项目(有swagger和无swagger都是一样的)到服务器或者虚拟机上的docker
2023-09-01 00:33:25
c语言switch反汇编的实现
2023-06-29 03:38:17
关于springBoot yml文件的list读取问题总结(亲测)
2023-11-04 12:37:08
java联调生成测试数据工具类方式
2021-10-12 06:42:17
java数字转汉字工具类详解
2023-04-28 02:00:26
深入理解java虚拟机的故障处理工具
2023-11-20 06:41:58
Java的JNI快速入门教程(推荐)
2022-11-22 16:10:48
通过FeignClient调用微服务提供的分页对象IPage报错的解决
2022-01-27 20:19:23
JPA中EntityListeners注解的使用详解
2023-08-04 21:39:18