Springboot 上传图片到项目路径下不能访问,需要重启

Springboot 上传图片到项目路径下不能访问,需要重启

1.bug场景

做图片上传 功能是,发现图片上传至项目下后无法通过ip:port/路径访问,重启项目是就可以正常访问。

2.bug原因

这是因为对服务器的保护措施导致的,服务器不能对外部暴露真实的资源路径,需要配置虚拟路径映射访问。

3.bug解决

新建配置类UploadConfig.java

@Configuration
/*springbooot 2.0 使用*/
public class UploadConfig implements WebMvcConfigurer{
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //映射图片保存地址
        //file: 项目路径/src/main/resources/static/upload/imgs/
        String filePath = UploadUtil.getJarRootPath() + "/src/main/resources/static/upload/imgs/";
        System.out.println(filePath);
        registry.addResourceHandler("/upload/imgs/**").addResourceLocations("file:"+ filePath);
    }
}

或Springboot 1.5

/*  spring boot 1.5*/
public class UploadConfig extends WebMvcConfigurerAdapter  {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //映射图片保存地址
        //file: 项目路径\\src\\main\\resources\\static\\upload\\
        String filePath = UploadUtil.getJarRootPath() + "/src/main/resources/static/upload/imgs/";
        System.out.println(filePath);
        registry.addResourceHandler("/upload/imgs/**").addResourceLocations("file:"+ filePath);

    }
}

 

获取项目绝对路径:

    /*
    * 获取项目绝对路径
    * */
    public static String getJarRootPath() {
        //获取项目所在的绝对路径,
        String path = System.getProperty("user.dir") ;

        //File directory = new File("");
        //path = directory.getAbsolutePath();
        //System.out.println(path);
        return path;
    }

Tip: addResourceHandler指向映射路径,addResourceLocations指向资源文件路径;资源文件路径地址必须以/结尾。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值