java.net.UnknownHostException: home

原因: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所运行的目录同级的目录下资源.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值