Compress dynamic content to ServletOutputStream

▼魔方 西西 提交于 2019-12-08 04:48:24

问题


I want to compress the dynamic created content and write to ServletOutputStream directly, without saving it as a file on the server before compressing.

For example, I created an Excel Workbook and a StringBuffer that includes strings with the SQL template. I don't want to save the dynamic content to .xlsx and .sql file on the server before zipping the files and writing to ServletOutputStream for downloading.

Sample Code:

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:


Create an HttpServlet and in the doGet() or doPost() method create a ZipOutputStream initialized with the ServletOutputStream and write directly to it:

    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
    }
}


来源:https://stackoverflow.com/questions/26113345/compress-dynamic-content-to-servletoutputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!