Spring图片上传和回显

0. 概述

​ 本节主要实现功能,在网页中上传的图片存放到项目的resource/static/img下,同时图片传递回页面显示。

1. 环境依赖

1
2
3
4
5
6
7
8
<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>

thymeleaf 是jsp中常用的一个东西,用来返回url地址,传递参数,还有一个web依赖

2. 静态资源处理

这里配置当需要返回图片等等静态资源的返回路径

ImgConfig

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
package com.kd13.uplodeimg.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
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 ImgConfig implements WebMvcConfigurer {
private String filePath;

public ImgConfig() {
ApplicationHome applicationHome = new ApplicationHome(this.getClass());
this.filePath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() +
"\\src\\main\\resources\\static\\img\\";
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 使用 filePath 作为资源位置
registry.addResourceHandler("/img/**")
.addResourceLocations("file:" + filePath);
}
}

其中的:

1
applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath()

是用来寻找到当前目录存放的位置。

3. 图片上传

ImgController

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
package com.kd13.uplodeimg.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Controller;
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;
import java.util.UUID;

@Controller
public class ImgController {

@RequestMapping("test")
public String test() {
return "img";
}

@ResponseBody
@RequestMapping("/upLoad")
public String upLoadImage(@RequestParam("file") MultipartFile file) {
ApplicationHome applicationHome = new ApplicationHome(this.getClass());
String filename = file.getOriginalFilename();
String suffixName = filename.substring(filename.lastIndexOf("."));
String path = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() +
"\\src\\main\\resources\\static\\img\\"; // 使用配置的路径,并确保路径正确
String newImgName = UUID.randomUUID().toString() + suffixName;
File filepath = new File(path, newImgName);

// 确保目录存在
if (!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}

try {
file.transferTo(filepath);
System.out.println("File saved to: " + filepath.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
return "上传失败"; // 处理异常情况
}

// 修改回显路径
return "img/" + newImgName; // 确保返回的路径正确
}
}

4. Thymeleaf设置

上述用到了thymeleaf的依赖,并且有静态html的资源配置,要想使用到控制器中配置的test访问到img.html页面就需要配置好这里的页面模板设置

application.properties

1
2
3
4
5
6
7
8
9
10
11
12
13
# Web 相关配置
server.port=8080

# Spring 静态资源的路径
spring.web.resources.static-locations=classpath:/static/

# Thymeleaf 模板配置
spring.thymeleaf.prefix=classpath:/static/
spring.thymeleaf.cache=false
spring.thymeleaf.suffix=.html

# 上传文件的最大大小
spring.servlet.multipart.max-file-size=5MB

5. 静态测试网页

img.html

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
<div class="modal-body">
<form id="uploadForm" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="img" style="display: none;" accept="image/*">
<label for="img" style="cursor: pointer;">
<img id="input_img" src="img/upimg.png" alt="点击上传"
style="width: 300px; height: 300px; border: 1px solid #ccc; object-fit: cover;">
</label>
</form>
</div>

<script src="jquery.min.js"></script>
<script>
$(document).ready(function () {
// 绑定文件输入框的变化事件
$("#img").change(uploadFile);
});

function uploadFile() {
var myform = new FormData(document.getElementById("uploadForm"));
var file = $("#img")[0].files[0];

if (!file) {
alert("请选择文件");
return;
}

$.ajax({
url: "/upLoad",
type: "POST",
data: myform,
contentType: false,
processData: false,
success: function (result) {
console.log(result);
alert("上传成功!");
// 更新显示的图片
$("#input_img").attr("src", result); // 更新显示的图片路径
},
error: function () {
alert("系统错误");
}
});
}
</script>

6. 项目测试

启动spring项目,访问:

1
http://localhost:8080/test

image-20241123214524826

点击图片进行上传选择一张图片提交:

image-20241123214535477

image-20241123214543919

图片正常回显并且控制台输出储存路径。

end

项目结构:
image-20241123214501271