JAVA通过流下载文件

首先是JAVA后台代码,资源请求都用GET比较好,但是要注意前端传路径回来的长度是否超过GET请求限制长度 

    /**
     * 
     * @param response
     * @param pathUrl
     */
    @GetMapping(value = "/common/download/resourceStream")
    public void  resourceStreamDownload(HttpServletResponse response,
                                        @RequestParam(value = "pathUrl",required = false) String pathUrl){
        //这三行代码是我去其他地方获得的流文件
        Response pathUrlResponse = dfsFeignClient.downloadFileByPath(pathUrl);
        Response.Body body = pathUrlResponse.body();
        InputStream inputStream = null;
try {
            //File file = new File("d:/20190906163248.png");
            // 以流的形式下载文件。
            //InputStream inputStream = new BufferedInputStream(new FileInputStream("d:/20190906163248.png"));
            inputStream = body.asInputStream();//文件流
            BufferedInputStream bins = new BufferedInputStream(inputStream);//放到缓冲流里面
            byte[] buffer = new byte[inputStream.available()];
            // 清空response
            response.reset();
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename="+pathUrl.substring(pathUrl.lastIndexOf("/")+1,
                    pathUrl.length()));
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            // 采用多次read的方式,这种toClient.write(buffer);方式会导致图片不完整
            int length = -1;
            while((length = bins.read(buffer)) != -1) {
                toClient.write(buffer, 0, length);
            }
            bins.close();
            toClient.flush();
            toClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 接下来是前端代码,最好都使用a标签链接后台请求下载,用ajax的话会出现乱码问题暂时还没找到解决方案。

                    {
                        field : 'reserve',
                        title : '点击下载注册证书',
                        formatter:function(value){
                            return "<a href=/common/download/resourceStream?pathUrl="+value+">点击下载证书</a>";
                        }
                    },

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值