原因:springboot访问映射配置问题导致。
原来的映射配置:
@Configuration
public class AppConfig implements WebMvcConfigurer {
@Value("${upload.resource.innerfilepath}")
private String uploadResourceInnerpath;
@Value("${upload.resource.innerfilepath.webrelativepath}")
private String uploadResourceInnerpathRelative;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//增加视图注册,将配置的指定文件路径,映射到外部网络访问
String innerPath = "";
//获取运行jar包所在目录
ApplicationHome ah = new ApplicationHome(getClass());
if(null != ah ){
File jarF = ah.getSource();
if(null != jarF){
innerPath = jarF.getParentFile().toString();
innerPath = FileUtil.windowsPathTransform(innerPath);
}
}
innerPath = innerPath + uploadResourceInnerpath;
registry.addResourceHandler(uploadResourceInnerpathRelative +"/**").addResourceLocations("file:/"+innerPath);
}
}
正确的映射配置:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//增加视图注册,将配置的指定文件路径,映射到外部网络访问
String innerPath = "";
//获取运行jar包所在目录
ApplicationHome ah = new ApplicationHome(getClass());
if(null != ah ){
File jarF = ah.getSource();
if(null != jarF){
innerPath = jarF.getParentFile().toString();
innerPath = FileUtil.windowsPathTransform(innerPath);
}
}
innerPath = innerPath + uploadResourceInnerpath;
//访问url中uploadResourceInnerpathRelative会映射到innerPath
//若映射本地文件,则必须是file:/// 为前缀,否则会报错:java.net.UnknownHostException: home
//或报错:java.net.ConnectException: 拒绝连接 (Connection refused)
registry.addResourceHandler(uploadResourceInnerpathRelative + "/**").addResourceLocations("file:///"+innerPath);
}
application.properties
# 本服务内部文件存储路径(与运行的jar包同级目录下upload目录)注意,一定要/结尾
upload.resource.innerfilepath=/uploadResource/
# 相对路径是用于映射网络访问 upload.resource.innerfilepath 目录资源
upload.resource.innerfilepath.webrelativepath=/uploadResource
访问方式:
<img src="/uploadResource/test.png" id="imgUrl" alt="">
1 业务背景
使用springboot搭建的管理平台,在上传文件后需直接网络读取上传的文件(图片)。
使外部网络访问链接读取当前jar所运行的目录同级的目录下资源.