栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

  @RequestMapping(value = "/download", method = RequestMethod.GET)
    public ResponseEntity 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 fail(String msg){
        String errorMsg = "";
        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是给下载后的文件给一个名字、

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/737062.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号