Java/JSP提供下载测试文件,可自定义文件大小,可断点续传

2020-12-25 266点热度 0人点赞 0条评论

为了测试服务器速度,有时候需要提供下载文件,这里写了一个Java代码,可提供下载测试文件、可断点续传,还可以让客户端请求的时候自定义下载文件的大小,这样省去找一个固定大小的文件丢到服务器上的麻烦了。

新建一个download_test.jsp
<%@ page import="java.io.OutputStream" %>
<%@ page import="java.text.DecimalFormat" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

    <%!
        String formatFileSize(long size) {
            if (size <= 0) return "0";
            final String[] units = new String[]{"B", "kB", "MB", "GB", "TB"};
            int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
            return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
        }

        byte[] long2Bytes4(long longValue) {
            return new byte[]{(byte) (longValue >>> 24), (byte) (longValue >>> 16),
                    (byte) (longValue >>> 8), (byte) longValue};
        }
    %>
    <%
        String flimb = request.getParameter("flimb");//file length in MB
        long fileLength = 0;
        if (flimb != null) {
            fileLength = Long.parseLong(flimb) * 1024 * 1024;
        }
        if (fileLength > 0) {
            OutputStream os = response.getOutputStream();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition",
                    String.format("attachment; filename=\"%s\"", "test_download_file_" +
                            formatFileSize(fileLength).replace(",","").replace(" ", "") + ".dat"));

            long pos = 0, last = fileLength - 1, sum = 0;//pos开始读取位置;  last最后读取位置;  sum记录总共已经读取了多少字节
            if (null != request.getHeader("Range")) {//断点续传
                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                // 情景一:RANGE: bytes=2000070- 情景二:RANGE: bytes=2000070-2000970
                String numRang = request.getHeader("Range").replaceAll("bytes=", "");
                String[] strRange = numRang.split("-");
                if (strRange.length == 2) {
                    pos = Long.parseLong(strRange[0].trim());
                    last = Long.parseLong(strRange[1].trim());
                } else {
                    pos = Long.parseLong(numRang.replaceAll("-", "").trim());
                }
            }
            if (last >= fileLength) {
                last = fileLength - 1;
            }

            long rangLength = last - pos + 1;// 总共需要读取的字节
            response.addHeader("Content-Length", String.valueOf(rangLength));
            // Content-Range: bytes 10-1033/304974592
            response.setHeader("Content-Range", "bytes " + pos + "-" + last + "/" + fileLength);

            int bufferLength = 4096;

            byte[] buffer = new byte[bufferLength];
            long now = System.currentTimeMillis();
            byte[] currentTimeMillisBytes = new byte[]{(byte) (now >>> 24), (byte) (now >>> 16), (byte) (now >>> 8), (byte) now};
            System.arraycopy(currentTimeMillisBytes, 0, buffer, 0, currentTimeMillisBytes.length);
            int length;
            while (sum < rangLength) {
                length = rangLength - sum <= bufferLength ? (int) (rangLength - sum) : bufferLength;
                os.write(buffer, 0, length);
                sum = sum + length;
            }

            os.flush();
        }

    %>

    <title>Download Test</title>
</head>
<body>
Test
</body>
</html>
如何调用

直接用浏览器或者下载工具下载链接(参数100表示文件大小100MB):

http://ip:port/download_test.jsp?flimb=100

Python版本看这里:https://blog.terrynow.com/2020/12/26/python-flask-download-test-server/

admin

这个人很懒,什么都没留下

文章评论

*

code