动态地将文件流式传输到zip文件响应中

时间:2016-04-28 04:43:27

标签: java sockets http stream

我正在尝试动态压缩我的文件作为对用户的响应,但由于某种原因,它们在途中会稍微损坏。客户端可以接收它们,打开zip文件夹并浏览文件。但是,打开或提取它们是行不通的。

这是我的代码:

private void dynamicallyZipFiles(IHTTPSession session) {
    try {
        // Let's send the headers first
        OutputStream os = session.getOutputStream();
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os, "UTF-8")), false);
        pw.append("HTTP/1.1 200 \r\n");
        printHeader(pw, "Connection", "keep-alive");
        printHeader(pw, "Content-Type", "application/zip, application/octet-stream");
        printHeader(pw, "Content-Disposition", "attachment; filename=\"pack.zip\"");
        printHeader(pw, "Transfer-Encoding", "chunked");
        pw.append("\r\n");
        pw.flush();

        // Send all the files from the list of files
        ChunkedOutputStream cos = new ChunkedOutputStream(os);
        ZipOutputStream zos = new ZipOutputStream(cos);
        final LinkedList<String> files = new LinkedList<String>();
        files.add("file1.txt");
        files.add("file2.txt");

        while (!files.isEmpty()) {
            String file = files.remove();
            File toBeSent = new File(file);
            try {
                ZipEntry ze = new ZipEntry(file);
                zos.putNextEntry(ze);
                InputStream is = (InputStream) new FileInputStream(toBeSent);
                long BUFFER_SIZE = 16 * 1024;
                byte[] buff = new byte[(int) BUFFER_SIZE];
                int len;
                while ((len = is.read(buff)) > 0) {
                    zos.write(buff, 0, len);
                }
                is.close();
                zos.flush();
                cos.flush();
                zos.closeEntry();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // Files have been sent, send the closing chunk
        //cos.write("0\r\n\r\n".getBytes(), 0, "0\r\n\r\n".getBytes().length);
        // The above line of code was the problem! Without it, it works!

        cos.flush();
        zos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
// Helper for printing headers
private void printHeader(PrintWriter pw, String key, String value) {
    pw.append(key).append(": ").append(value).append("\r\n");
}

我已经在这里挣扎了好几个小时了。我认为它必须与关闭块或关闭连接有关?

我不确定关闭流的正确顺序或方式是什么。我相信当你有一些“分层”流并且你关闭最顶层的流时,它会自动关闭下面的所有流?如果你刷新一个流,它会如何冲洗它下面的流呢?用这个我的意思是我的ZipStream,如果我关闭它,它会关闭所有其他流吗?如果我冲洗它,它还会刷新所有其他流吗?

0 个答案:

没有答案