将动态内容压缩为ServletOutputStream

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

例如,我创建了一个Excel工作簿和一个StringBuffer,其中包含带有SQL模板的字符串。 在压缩文件并写入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()方法中创建一个使用ServletOutputStream初始化的ZipOutputStream并直接写入它:

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