Spring Boot 实现图片上传并回显功能
作者:Mr_YMX 发布时间:2021-10-11 17:45:20
标签:Spring,Boot,上传图片,回显
一、常规形式
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
0
投稿
猜你喜欢
- <dependency> <groupId>org.projectlombok</g
- 每当想找哪个运算符优先级高时,很多时候总是想找的就没有,真让人气愤!现在,终于有个我个人觉得非常全的,分享给大家,欢迎拍砖!C语言运算符优先
- Java Set集合的遍历及实现类的比较Java中Set集合是一个不包含重复元素的Collection,首先我们先看看遍历方法package
- 引言float和double类型的主要设计目标是为了科学计算和工程计算。他们执行二进制浮点运算,这是为了在广域数值范围上提供较为精确的快速近
- 开发环境win10Android Studio效果用于多级菜单展示,或选择。如 每个省,市,县;如 树木的病虫害;关键代码 @overrid
- 本文介绍了Spring Boot 开发REST接口最佳实践,分享给大家,具体如下:HTTP动词与SQL命令对应GET从服务器获取资源,可一个
- 前言:什么是多数据源?最常见的单一应用中最多涉及到一个数据库,即是一个数据源(Datasource)。那么顾名思义,多数据源就是在一个单一应
- 利用Java,在控制台操作下,编写的五子棋,作为复习二维数组,面向对象等基础知识。w表示白棋,b表示黑棋import java.util.S
- jar包就指第三方提供的开源的API,这些API不属于JDK的,需要通过导入才能使用。添加和导入的区别注意:本文里的 导入 和 添加 jar
- Comparable 简介Comparable 是排序接口。若一个类实现了Comparable接口,就意味着“该类支持排序”。
- Spring 提供了自动代理机制,可以让容器自动生成代理,从而把开发人员从繁琐的配置中解脱出来 。 具体是使用 BeanPostProces
- javax.persistence中@Column定义字段类型在@Column中有个比较强大的配置 columnDefinition,如果有
- Java 开发语言中实现HTTP请求的方法主要有两种:一种是JAVA的标准类HttpUrlConnection,比较原生的实现方法;另一种是
- 本文实例讲述了Java Swing实现让窗体居中显示的方法。分享给大家供大家参考,具体如下:Swing组件是AWT组建的增强组件,是功能强大
- 本文实例为大家分享了java实现抽奖功能的具体代码,供大家参考,具体内容如下抽一个:输入抽奖人数,生成随机数字进行抽奖。比如:楼主抽幸运儿送
- 本文实例为大家分享了Java 1.8使用数组实现循环队列的具体代码,供大家参考,具体内容如下1、引入使用数组实现循环队列,功能如下:1)is
- 一、基本介绍 1、介绍学习很多算法知识,力争做到最优解的学习过程中,很多时候都会遇到PriorityQueue(优先队列)。一个基
- 本文介绍了JAVA中实现原生的 socket 通信机制原理,分享给大家,具体如下:当前环境jdk == 1.8知识点socket 的连接处理
- 众所周知Web服务器与客户端之间的通信是使用HTTP协议的。HTTP是一个客户端和服务器端请求和应答的标准(TCP)。因为HTTP协议是基于
- 1.SpringCloud是什么以前的服务器就像是一个医院只有一个医生,什么病人都要让这个医生看,如果医生觉得太累,自我暴毙了,那整个医院都