问题描述
我想压缩动态创建的内容,直接写入ServletOutputStream,而不在压缩之前将其保存为服务器上的文件。
I want to compress the dynamic created content and write to ServletOutputStream directly, without saving it as a file on the server before compressing.
例如, Excel工作簿和包含带有SQL模板的字符串的StringBuffer。我不想在压缩文件和写入ServletOutputStream之前将动态内容保存到服务器上的.xlsx和.sql文件。
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.
示例代码:
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; }
推荐答案
创建<$ c $在 doGet()或 doPost()方法中创建一个 HttpServlet code>使用 ServletOutputStream 初始化并直接写入它:
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 } }
这篇关于将动态内容压缩到ServletOutputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!