Compress dynamic content to ServletOutputStream

旧时模样 提交于 2019-12-06 15:36:31

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