gpt4 book ai didi

java - 将动态内容压缩到 ServletOutputStream

转载 作者:行者123 更新时间:2023-11-29 03:16:44 26 4
gpt4 key购买 nike

我想压缩动态创建的内容并直接写入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;
}

最佳答案

创建一个 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
}
}

关于java - 将动态内容压缩到 ServletOutputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26113345/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com