Springboot 后台接收并存储pdf文件到项目根目录-jar包可运行 windows、linux通用

试了很多网上说的后台保存文件办法,但是打包成jar包后,保存文件就出错,终于自己在综合多个帖子后才有了以下代码


    @RequestMapping(value = "/uploadPDF/{node_key}", method = RequestMethod.POST)
    public ResultJson upload(@RequestParam("file") MultipartFile file, @PathVariable int node_key){
        if (file.isEmpty()) {
            return  ResultJson.fail();
        }
        try {
            File path=new File(ResourceUtils.getURL("classpath:").getPath());
            if(!path.exists()){
                path=new File("");
            }
            File upload = new File(path.getAbsolutePath(),"static/pdf/upload/"+node_key);
//            System.out.println(path.getAbsolutePath());
            if(!upload.exists()){
                upload.mkdirs();
            }
            String filename = file.getOriginalFilename();
            File pdfFile = new File(upload + "/"+ filename);
            file.transferTo(pdfFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return ResultJson.success("添加成功!");
    }

在Jar包同级目录创建文件夹并存储文件,windows/linux通用

File path=new File(ResourceUtils.getURL("classpath:").getPath());
if(!path.exists()){
    path=new File("");
}
File upload = new File(parentFile.getAbsolutePath(),"static/pdf/upload/);
if(!upload.exists()){
    upload.mkdirs();//创建各级目录对象
}
filename.....
//在upload目录创建相应文件对象
File pdfFile = new File(upload + "/"+ filename);

在Jar包上级目录创建文件夹并存储文件,windows/linux通用

File path=new File(ResourceUtils.getURL("classpath:").getPath());
if(!path.exists()){
    path=new File("");
}
//path是一个抽象路径的文件对象,必须获取相应的绝对路径文件对象,才能获取附文件对象
File parentFile = path.getAbsoluteFile().getParentFile();
if(!parentFile.exists()){
   parentFile.mkdir();
}
File upload = new File(parentFile.getAbsolutePath(),"static/pdf/upload/");
if(!upload.exists()){
    upload.mkdirs();
}

贴一下有帮助的帖子:

https://www.cnblogs.com/yangming1996/p/6602086.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值