SpringBoot 图片上传

SpringBoot 图片上传

SpringBoot 实现图片上传功能

SpringBoot 是为了简化Spring应用的创建、运行、测试、调试、部署等一系列问题而诞生的产物,自动装配的特性让我们可以更好的关注业务本事而不是外部的xml配置,我们只需遵循规范,引入相关的依赖就可以轻易搭建出一个web工程

说明

  • 文件上传控件较多,本文以引用LayUI图片上传控件为例
  • 页面上传插件使用Layui的图片上传控件,点击跳转
  • 文件上传使用JQuery 的Ajax请求对应图片上传API,API返回包含图片路径格式的JSON数据
  • 上传图片路径并非在项目文件夹中,需配置静态资源文件路径

配置文件上传控件

第一步:添加 Layui 的文件上传控件

  1. Layui库添加进项目的静态资源文件夹中,在src/main/resources/satic文件夹下创建layui文件夹存放Layui库等资源文件;

  2. HTML页面引用js及css文件,图片上传控件需要用到的资源有jquery.mini.js/jquery.js、layer.js、layui.js、layui.css。相关资源文件路径需要配置为项目具体引用路径或使用在线配置路径layui,详细内容可到layui官网查看。

  3. 初始化插件及样式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<script type="text/javascript">
layui.use('upload',function() {
var $ = layui.jquery, upload = layui.upload;
//普通图片上传
var uploadInst = upload.render({
url : '../picture/uploadImg'//图片上传action路径配置
,data : {
folder : 'hotel/'
},
before : function(obj) {
//预读本地文件示例,不支持ie8
obj.preview(function(index, file,
result) {
$('#imgSrc').attr('src', result); //图片链接(base64),显示缩略图
});
},
done : function(data) {
if (data.data.message == 'success') {
$('#hotelPicture').val(
data.data.picUrl);//设置图片相对路径,表单提交时提交图片url
return layer.msg('上传成功!')
}
},
error : function() {
//演示失败状态,并实现重传
var demoText = $('#demoText');
demoText
.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
demoText.find('.demo-reload').on(
'click', function() {
uploadInst.upload();
});
}
});
});
</script>
```

## 修改配置文件

> 第二步: 修改配置文件

```properties
# file write static resource path
web.upload-path=F:/temp/springboot/

spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/templates/,classpath:/META-INF/resources/,classpath:/resources/,\
classpath:/static/,classpath:/public/,file:${web.upload-path}

注: web.upload-path 为图片保存路径,若使用linux系统部署需要将绝对路径替换为相对路径。 例如:

API 接口

  • SpringBoot 2.x版本中,页面静态资源配置无法实现。故采用配置文件的方式实现了,可以忽略本文中的页面显示配置或采用其他的方式。

第三步:文件上传API

1
2
3
4
5
6
7
8
9
10
11
# 配置外部文件夹可通过HTTP访问图片,即配置静态资源路径
spring:
mvc:
static-path-pattern: /**
web:
resources:
static-locations: classpath:/static/,file:/temp/fileupload/image
# 上传文件路径配置
web:
upload:
image: /temp/fileupload/image
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
@Value("${web.upload.image}")
private String imageUrl;

/**
* @Title uploading <br>
* @Description 上传背景图片<br>
* @Param
*
* @param file
* @param groupId
* @return java.lang.Object
*/
@PostMapping(value = "uploading")
public Object uploading(MultipartFile file) {

// 图片保存到数据库的相对路径
String filePath = this.saveImages(file);

// 根据实际情况修改返回值
Map<String ,Object> result = new HashMap<>();
s.put("filePath",filePath)
return new ResponseDTO<>(Boolean.TRUE, result);
}

/**
* @Title saveImages <br>
* @Description 保存视频文件 <br>
* @Param
*
* @param image
* @return java.lang.String 例如(image/20210122/20210122130940421.jpg)
*/
private String saveImages(MultipartFile image) {

// 获取原文件名
String name = image.getOriginalFilename();
// 获取文件后缀
String subffix = name.substring(name.lastIndexOf(".") + 1, name.length());

// 日期文件夹
String nowFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());
// 新的文件名以日期命名:
String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + "." + subffix;
// 获取项目路径到webapp
String filepath = imageUrl + "/" + nowFolder;
File file = new File(filepath);

// 文件路径不存在时,创建文件夹(可创建多层文件夹)
if (!file.exists()) {
file.mkdirs();
}
// 实际保存路径
filepath += ("/" + fileName);
// 保存文件
try {
image.transferTo(new File(filepath));
} catch (IOException e) {
e.printStackTrace();
}
// 保存数据库的相对路径
String relativePath = "image/" + nowFolder + "/" + fileName;
return relativePath;
}

页面显示配置

第四步:图片在前端页面显示路径配置,不配置显示不了图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
public class WebAppConfig extends WebMvcConfigurerAdapter {
@Value("${web.upload.image}")
private String imgPath;//application.properties中的文件资源位置

/**
* 图片访问方法
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if(imgPath.equals("") || imgPath.equals("${web.upload.image}")){
String imagesPath = WebAppConfig.class.getClassLoader().getResource("").getPath();
if(imagesPath.indexOf(".jar")>0){
imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));
}else if(imagesPath.indexOf("classes")>0){
imagesPath = "file:"+imagesPath.substring(0, imagesPath.indexOf("classes"));
}
imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/"))+"/images/";
imgPath = imagesPath;
}
LoggerFactory.getLogger(WebAppConfig.class).info("imagesPath="+imgPath);
registry.addResourceHandler("/images/**").addResourceLocations(imgPath);
super.addResourceHandlers(registry);
}
}