1

我正在尝试让 Tomcat 将 servlet 内容写为 bzip2 文件(可能是愚蠢的要求,但对于某些集成工作显然是必要的)。我正在使用 Spring 框架,所以它位于 AbstractController 中。

我正在使用来自 http://www.kohsuke.org/bzip2/的 bzip2 库

我可以很好地将内容 bzip 压缩,但是当文件被写出时,它似乎包含一堆元数据并且无法识别为 bzip2 文件。

这就是我正在做的

// get the contents of my file as a byte array
byte[] fileData =  file.getStoredFile();

ByteArrayOutputStream baos = new ByteArrayOutputStream();

//create a bzip2 output stream to the byte output and write the file data to it             
CBZip2OutputStream bzip = null;
try {
     bzip = new CBZip2OutputStream(baos);
     bzip.write(fileData, 0, fileData.length);
     bzip.close();  
} catch (IOException ex) {
     ex.printStackTrace();
}
byte[] bzippedOutput = baos.toByteArray();
System.out.println("bzipcompress_output:\t" + bzippedOutput.length);

//now write the byte output to the servlet output
//setting content disposition means the file is downloaded rather than displayed
int outputLength = bzippedOutput.length;
String fileName = file.getFileIdentifier();
response.setBufferSize(outputLength);
response.setContentLength(outputLength);
response.setContentType("application/x-bzip2");
response.setHeader("Content-Disposition",
                                       "attachment; filename="+fileName+";)");

这是从 Spring abstractcontroller 中的以下方法调用的

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)  throws Exception

我用不同的方法尝试了一些方法,包括直接写入 ServletOutput,但我很困惑,在网上找不到任何/很多示例。

以前遇到过这种情况的任何人的任何建议都将不胜感激。替代库/方法很好,但不幸的是它必须是 bzip2'd。

4

2 回答 2

3

张贴的方法确实很奇怪。我已经重写,以便更有意义。试试看。

String fileName = file.getFileIdentifier();
byte[] fileData = file.getStoredFile(); // BTW: Any chance to get this as InputStream? This is namely memory hogging.

response.setContentType("application/x-bzip2");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

OutputStream output = null;

try {
     output = new CBZip2OutputStream(response.getOutputStream());
     output.write(fileData);
} finally {
     output.close();
}

你看,只需将响应的输出流包装起来CBZip2OutputStream并写入byte[]它。

您可能会碰巧IllegalStateException: Response already committed在服务器日志中看到后面的内容(顺便说一下正确发送了下载),这意味着 Spring 正在尝试在之后转发请求/响应。我不做Spring,所以不能详细讲,但你至少应该指示Spring远离响应。不要让它做映射,转发或其他什么。我觉得退货null 就够了。

于 2010-02-20T03:22:44.950 回答
2

您可能会发现使用commons -compress中的CompressorStreamFactory更容易一些。它是您已经在使用的 Ant 版本的后继版本,并且与 BalusC 的示例有 2 行不同。

或多或少是图书馆偏好的问题。

OutputStream out = null;
try {
    out = new CompressorStreamFactory().createCompressorOutputStream("bzip2", response.getOutputStream());
    IOUtils.copy(new FileInputStream(input), out); // assuming you have access to a File.
} finally {
    out.close();
}
于 2010-02-20T06:13:59.313 回答