springboot jar 上传文件到服务器找不到路径问题

springboot  本地上传一直没有问题,但是部署上服务器就总是报找不到路径问题 , 特此记录,以备后用。 

首先 由于springboot 本地找到是本目录,到到服务器上由于没有权限在jar里写文件 只能在jar同级目录写文件

@Configuration
public class WebApiConfigurer implements WebMvcConfigurer {
 
   
    //静态资源配置
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)  {
        registry.addResourceHandler("/view/**").addResourceLocations("file:"+System.getProperty("user.dir")+"/view/");

    }
}

 

注 : 

System.getProperty("user.dir") 不管是window 还是linux 都能获取相同的路径 解决了环境不同的问题 ;

@RequestMapping("/upload")
    public void upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {

		throw new Exception();
        }
        String filePath = System.getProperty("user.dir");


        File upload = new File(filePath + File.separator + "view" + File.separator);
        if (!upload.exists()) {
            upload.mkdirs();
        }
        File dest = new File(filePath + File.separator +  "view" +  File.separator + "index.html");
        try {
            file.transferTo(dest);

         } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
 
    }

这样就可以了 

这样就可以在服务器jar 同级目录view 下找到index文件

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值