Java 断点续传下载文件

Posted by 浮生 on 03-05,2020

来自网上。

        String filePath = downLoadFile + pathSeparator + fileName;
        InputStream inputStream = null;
        OutputStream out = null;
        try {
            File file = new File(filePath);
            Long fSize = Long.parseLong(String.valueOf(file.length()));
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/x-download");
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("Content-Length", String.valueOf(fSize));
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            inputStream = new FileInputStream(filePath);
            Long pos = 0L;
            if (null != request.getHeader("Range")) {
                // 断点续传
                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                try {
                    pos = Long.valueOf(request.getHeader("Range").replaceAll("bytes=", "").replaceAll("-", ""));
                } catch (NumberFormatException e) {
                    pos = 0L;
                }
            }
            out = response.getOutputStream();
            String contentRange = "bytes " + pos + "" + "-" + (fSize - 1) + "" + "/" + fSize + "";
            response.setHeader("Content-Range", contentRange);
            //跳过 pos 个文件字节
            Long offset = pos;
            while (offset > 0) {
                Long fileAt = inputStream.skip(offset);
                if (fileAt == -1) {
                    throw new RuntimeException("文件断点设置失败!");
                }
                offset -= fileAt;
            }
            byte[] buffer = new byte[1024 * 10];
            int length;
            while ((length = inputStream.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, length);
            }
        } catch (Exception e) {
            LOGGER.error("下载异常:" + e);
        } finally {
            try {
                if (null != out) out.flush();
                if (null != out) out.close();
                if (null != inputStream) inputStream.close();
            } catch (IOException e) {
                LOGGER.error("关闭数据流异常:" + e);
            }
        }
    }