将动态内容压缩为ServletOutputStream

时间:2014-09-30 05:26:05

标签: java servlets zip compression

我想压缩动态创建的内容并直接写入ServletOutputStream,而不是在压缩之前将其保存为服务器上的文件。

例如,我创建了一个Excel工作簿和一个包含SQL模板字符串的StringBuffer。在压缩文件并写入ServletOutputStream进行下载之前,我不想将动态内容保存到服务器上的.xlsx和.sql文件中。

示例代码:

ServletOutputStream out = response.getOutputStream();
workbook.write(byteArrayOutputStream);    
zipIt(byteArrayOutputStream,out);

public static boolean zipIt(ByteArrayOutputStream input, ServletOutputStream output) {
        try {
            ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(output));
            ZipEntry zipEntry = new ZipEntry("test.xlsx");
            zos.putNextEntry(zipEntry);
            if (input != null) {
                zipEntry.setSize(input.size());
                zos.write(input.toByteArray());
                zos.closeEntry();
            }
        } catch (IOException e) {
            logger.error("error {}", e);
            return false;
        }
        return true;
    }

1 个答案:

答案 0 :(得分:4)

创建HttpServlet并在doGet()doPost()方法中创建使用ZipOutputStream初始化的ServletOutputStream并直接写入其中:

    resp.setContentType("application/zip");
    // Indicate that a file is being sent back:
    resp.setHeader("Content-Disposition", "attachment;filename=test.zip");

    // workbook.write() closes the stream, so we first have to
    // write it to a "buffer", a ByteArrayOutputStream
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    workbook.write(baos);
    byte[] data = baos.toByteArray();

    try (ZipOutputStream out = new ZipOutputStream(resp.getOutputStream())) {
        // Here you can add your content to the zip 

        ZipEntry e = new ZipEntry("test.xlsx");
        // Configure the zip entry, the properties of the file
        e.setSize(data.length);
        e.setTime(System.currentTimeMillis());
        // etc.
        out.putNextEntry(e);
        // And the content of the XLSX:
        out.write(data);
        out.closeEntry();

        // You may add other files here if you want to

        out.finish();
    } catch (Exception e) {
        // Handle the exception
    }
}