java web监控文件下载进度1e

  

      /**
     * 
     * @downloadFile(下载app文件,监控是否下载完成)1
     * @作者:dww
     * @创建时间:2018年1月30日 下午1:56:35
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/downloadFile")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        InputStream ins = null;
        BufferedInputStream bins = null;
        OutputStream outs = null;
        BufferedOutputStream bouts = null;
        String fileName = "10008328_com.tencent.tmgp.xymobile_h100_1.0.30.1.apk";
        String path = PropertiesUtils.getConfigProperty("appFileSavePath") + "/" + fileName;
        File file = new File(path);
        if (!file.exists()) {
            logger.info("文件不存在");
            return;
        }
        long currentLen = 0;// 已读取文件大小
        long totleLen = file.length();// 总文件大小
        double percent=0.0; //下载进度
        try {
            ins = new FileInputStream(path);
            bins = new BufferedInputStream(ins);// 放到缓冲流里面
            outs = response.getOutputStream();// 获取文件输出IO流
            bouts = new BufferedOutputStream(outs);
            response.setContentType("application/x-download");// 设置response内容的类型
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));// 设置头部信息
            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            // 开始向网络传输文件流
            while ((bytesRead = bins.read(buffer)) != -1) {
                currentLen += bytesRead;
                bouts.write(buffer, 0, bytesRead);
            }
            bouts.flush();// 这里一定要调用flush()方法
            // 获取下载进度
            percent = Math.ceil(currentLen * 1.0 / totleLen * 10000);
            logger.info("下载 进度:",percent/100.0+"%");
            if(percent == 10000) { 
                logger.info("下载完成了");
            }
        } catch (IOException e) {
            percent = Math.ceil(currentLen * 1.0 / totleLen * 10000);
            logger.error("下载中断或者网络异常表示没下载完,当前下载进度:{};{}",percent/100.0 +"%",e.getMessage(),e);
        } finally {
            if (ins != null) {
                ins.close();
            }
            if (bins != null) {
                bins.close();
            }
            if (outs != null) {
                outs.close();
            }
            if (bouts != null) {
                bouts.close();
            }
        }
    }

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值