【代码】上传服务器的图片通过地址栏访问

前言

SpringBoot项目实现文件上传后,通过配置静态资源对外暴露的路径映射,实现通过地址栏访问上传后的图片

配置文件

  • statis/properties/目录下创建image.properties配置文件
1
2
3
4
5
# 上传的文件在服务器中保存的路径
file.accessPath=~/Downloads/images

# 静态资源对外暴露的访问路径
file.staticAccessPath=/images/**

配置类

  • 创建一个配置类,实现WebMvcConfigurer接口,配置映射关系
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Configuration
@PropertySource("classpath:/properties/image.properties")
public class UploadConfig implements WebMvcConfigurer {

@Value("${file.staticAccessPath}")
private String staticAccessPath;
@Value("${file.accessPath}")
private String uploadFolder;

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + uploadFolder);
}

}

完成

  • 此时访问域名+图片存放的根目录名即可实现图片的访问

参考文献

CSDN——@郭小茶