te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>java - Large file download using Servlet with Streaming without browser buffering - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - Large file download using Servlet with Streaming without browser buffering - Stack Overflow

programmeradmin3浏览0评论

I am developing a Java 8 servlet to download a zipped resource. The file size can vary significantly, sometimes reaching up to 700MB. For testing, I am using a 350MB ZIP file.

The expected behavior is that the file should start downloading immediately while streaming, but instead, the browser buffers the file before prompting the user to save it. This results in a delay of 30-40 seconds before the save dialog appears.

My Servlet Code:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    String strCryptedURL = request.getParameter(DownloadFolderServlet.URL_PARAM_NAME);
    String strURL = PasswordUtil.isPasswordEncrypted(strCryptedURL) ? PasswordUtil.decryptPassword(strCryptedURL) : strCryptedURL;

    try {
        URL url = new URL(strURL);
        String userInfo = url.getUserInfo();

        if (userInfo == null || !userInfo.contains(":")) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing credentials for WebDAV.");
            return;
        }

        String[] userPass = userInfo.split(":", 2);
        String username = userPass[0];
        String password = userPass[1];

        String sanitizedURL = url.getProtocol() + "://" + url.getHost() + ":" + url.getPort() + url.getPath();

        HttpURLConnection fileConn = (HttpURLConnection) new URL(sanitizedURL).openConnection();
        fileConn.setRequestMethod("GET");
        fileConn.setConnectTimeout(10000);
        fileConn.setReadTimeout(60000);

        String encodedAuth = Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
        fileConn.setRequestProperty("Authorization", "Basic " + encodedAuth);

        if (fileConn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            response.sendError(fileConn.getResponseCode(), "Error retrieving file from WebDAV.");
            return;
        }

        String fileName = url.getPath().substring(url.getPath().lastIndexOf("/") + 1);

        response.reset();
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.setHeader("Content-Transfer-Encoding", "binary");

        response.setHeader("Transfer-Encoding", "chunked"); // Tried enabling chunked encoding

        response.flushBuffer();

        try (InputStream inputStream = fileConn.getInputStream();
             OutputStream outputStream = response.getOutputStream()) {

            byte[] buffer = new byte[8192]; // 8 KB buffer
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
                outputStream.flush(); // Ensuring data is sent immediately
            }
            
        }
    } catch (Exception e) {
        e.printStackTrace();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error while downloading the ZIP file.");
    }
}

I have tried:

  1. Setting Transfer-Encoding: chunked
  2. Ensuring Content-Type: application/octet-stream
  3. Using flushBuffer()
  4. Explicitly avoiding Content-Length (to prevent buffering)

Expected Behavior: The browser should prompt the user immediately and start downloading progressively instead of waiting for the entire file to be received.

Questions:

  1. Is there anything in my implementation that causes the browser to buffer everything before showing the save prompt?
  2. Is there a way to force the browser to stream the file as soon as bytes are available?
发布评论

评论列表(0)

  1. 暂无评论