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


猜你喜欢
- 目录事件最基本的用法理解路由事件WPF中使用路由事件升级了传统应用开发中的事件,在WPF中使用路由事件能更好的处理事件相关的逻辑,我们从这篇
- 本文实例为大家分享了OpenCV+Qt实现图像处理操作的具体代码,供大家参考,具体内容如下一、目标Qt界面实现 雪花屏 高斯模糊 中值滤波
- 前言大家在学习Java的过程中,或者工作中,始终都绕不开集合。在单线程环境下,ArrayList就可以满足要求。多线程时,我们可以使用Cop
- Gateway什么是Gateway  由于Netflix的zuul发生问题,spring公司自己研发了一
- 废话不多说,直接上代码package com.ietree.basicskill.socket.basic.nio;import java.
- 本文实例为大家分享了java实现微信红包的具体代码,供大家参考,具体内容如下要求基于BigDecimal类实现微信红包算法的功能,比如设置红
- 一、什么是ASMASM是一个java字节码操纵框架,它能被用来动态生成类或者增强既有类的功能。ASM 可以直接产生二进制 class 文件,
- 写在前面注:本文章使用的 SpringBoot 版本为 2.2.4.RELEASE,其 Spring 版本为 5.2.3.RELEASE前言
- TCP与UDP都属于TCP/IP协议TCP(Transmission Control Protocol,传输控制协议)是面向连接的协议,也就
- 本文实例为大家分享了Unity实现10天签到系统的具体代码,供大家参考,具体内容如下实现功能:正常在游戏中签到,并把剩下的倒计时给显示出来。
- /*冒泡排序:双层循环1.外层循环:控制排序轮数,排序数组长度减1(最后一次循环只剩下一个元素,不需要比较,同时数组已完成排序。2.内层循环
- 前言短信信息的发送目前已经是项目中必不可少的部分,我们怎么通过web页面来实现把信息推送到别人手机上呢?简单点,编码的方式简单点!看完本篇文
- 本文实例讲述了Java实现插入排序的方法。分享给大家供大家参考。具体实现方法如下:import java.util.Arrays; /**
- 本文实例讲述了Android编程实现定时发短信功能。分享给大家供大家参考,具体如下:第一,要实现发短信的功能,必须要用到android系统中
- 本文实例讲述了Android获取SD卡及手机ROM容量的方法。分享给大家供大家参考,具体如下:这里通过一个简单的小例子,来获取SD卡的容量和
- 最近有一个实现一个带有圆角的ImageView的需求,在网上找了找三方,虽然Demo都是正确的,但是移植过来就不可以了,因为请求链接的时候用
- 摘要分析验证码素材图片混淆原理,并采用selenium模拟人拖动滑块过程,进而破解验证码。人工验证的过程1、打开威锋网注册页面2、移动鼠标至
- 最近,阿里开源的nacos比较火,可以和springcloud和dubbo共用,对dubbo升级到springcloud非常的方便。这里学习
- ArratList 类:存放同一数据类型容器(只能为引用数据类型,因实际其内部存放的是地址)1.导入其所在包import java.util
- 效果展示单选版可看上篇博文 用flutter封装一个点击菜单工具栏组件本文是CHeckbox多选版效果如图所示,点击选项回调选中的