springboot项目根据id下载下载相对应的文件

 需求:根据前端传递的id查询数据库中相对于的文件路径,根据相对应路径将文件下载下来

:下列代码中的注1、注2、注3、注4、注5代表需要更换的内容后可直接使用

  @RequestMapping(value = "/download", method = RequestMethod.GET)
    public ResponseEntity<InputStreamResource> downloadFile(@RequestParam(value="id") Long id)
            throws Exception {
        PlywoodInfo f = service.download(id);         //注1  
        if(f==null){                          
            return fail("文件不存在!");
        }else{  //f.getPlywoodPath()为数据库中查到的文件路径  eg:D:/test
            File _file = new File(f.getPlywoodPath());          
            if(!_file.exists()){
                return fail("文件不存在!");
            }
            String startPath = f.getStartPath();        //注2 
            File startPathFile = new File(startPath);   //注3 
            String finalFileName = URLEncoder.encode( startPathFile.getName() + ".xml","UTF-8");  //注4 
            FileSystemResource file = new FileSystemResource(f.getPlywoodPath());//注5
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", finalFileName));
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            return ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentLength(file.contentLength())
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new InputStreamResource(file.getInputStream()));
        }
    }

    private ResponseEntity<InputStreamResource> fail(String msg){
        String errorMsg = "<script language=\"javascript\">alert('"+msg+"');</script>";
        InputStream inputStream = null;
        try {
            inputStream = new ByteArrayInputStream(errorMsg.getBytes("GBK"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE,"text/html;charset=UTF-8");
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentType(MediaType.TEXT_HTML)
                .body(inputStreamResource);
    }

 注1:PlywoodInfo f = service.download(id);   //这行代表表示根据id查询数据库中的内容

注2,注3和注4是给下载后的文件给一个名字、

如果有疑问可以私密,有不足地方可以说出来,谢谢!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值