Resultful接口实现后端文件下载

简介:springboot前后端分离项目,要实现文件下载功能。如果文件较大时采用后端直接下载,将文件采用zip压缩后以流的方式写入响应中,返回给浏览器,浏览器解析完成下载。

一:获取下载请求,调用实现,返回响应。

   @ApiOperation(value = "", notes = "")
    //@UserLoginToken
    @GetMapping(value = "/downTaskResult")
    @ResponseBody
    public RestfulResult downLoadTaskRes(@RequestParam Long id, @RequestParam(required = false) String token,HttpServletResponse response){
        RestfulResult restfulResult = new RestfulResult();
        try {
            Boolean flag=batchTaskService.downLoadTaskRes(id,response);
            if (flag){
                return null;
            }
        }catch (Exception e){
            logger.error("批量任务结果下载!",e);
            restfulResult = new RestfulResult(ResCode.ERROR.getCode(),ResCode.ERROR.getMessage());
        }

        return restfulResult;
    }

二:具体service实现

 @Override
    public Boolean downLoadTaskRes(Long id, HttpServletResponse response) throws RequestException {
       
       string result="";//具体路径,demo暂时写null
        //判断文件是否存在
        URL pathUrl=null;
        Path path=null;
        try {
             pathUrl=new URL(result);
             path=Paths.get(pathUrl.toURI());
        }catch (Exception e){
            throw  new RequestException(ResCode.TASK_FILE_ERROR.getCode(),
                    ResCode.TASK_FILE_ERROR.getMessage());
        }

        if (!Files.exists(path)){
            throw  new RequestException(ResCode.TASK_FILE_ERROR.getCode(),
                    ResCode.TASK_FILE_ERROR.getMessage());
        }
        String filePath=path.toString();
        //String filePath="/Users/jiaokc/Desktop/list_diff_data.json";
        String fileRealName=filePath.substring(filePath.lastIndexOf("/")+1);
        String fileName=fileRealName.substring(0,fileRealName.lastIndexOf("."));
        //下载文件压缩返回。
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" +fileName+".zip");
        response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
        response.setHeader("Access-Control-Allow-Origin","*");
        zipUtil(response,filePath,fileRealName);

        return  true;


    }

三:文件边压缩边下载

/**
     * 压缩文件边压缩边下载
     * @param response
     * @param filePath
     * @param fileName
     */
    private  void zipUtil(HttpServletResponse response,String filePath,String fileName) {
        //设置压缩流:直接写入response,实现边压缩边下载
        ZipOutputStream zipos = null;
        try {
            zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
            zipos.setMethod(ZipOutputStream.DEFLATED); //设置压缩存储方法
            zipos.setLevel(9);//设置压缩率9
        } catch (Exception e) {
            e.printStackTrace();
        }

        //将文件写入压缩流
        DataOutputStream os = null;

        File file = new File(filePath);
        try {
            //添加ZipEntry,并ZipEntry中写入文件流
            zipos.putNextEntry(new ZipEntry(fileName));
            os = new DataOutputStream(zipos);
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer= new byte[1024];
            int length = 0;
            while((length = bis.read(buffer))!= -1){
                os.write(buffer, 0, length);
            }
            bis.close();
            zipos.closeEntry();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //关闭流
        try {
            os.flush();
            os.close();
            zipos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值