【发布时间】:2014-04-23 13:17:31
【问题描述】:
以下是我用来尝试流式传输 PDF 的代码。我之前在另一个环境中做过这个确切的事情,但是由于某种原因 StreamingOutput 上的 write() 方法没有被调用。
没有错误被记录,它已经到了在日志中显示“CONT”的地步,所以我知道它至少到达了 StreamingPdfOutput 类的构造函数。
发生的情况是它最终只会向客户端返回 404,即使所有这些代码都在执行(除了 write() 方法)。
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@RequestMapping(value = "/ajax/fetchReportPdf", method = RequestMethod.POST)
public StreamingOutput fetchReportPdf(@RequestBody MyRequest request, @Context HttpServletResponse response)
{
LOG.info("start fetchReportPdf");
// AssessmentResponse response = new AssessmentResponse();
try
{
LOG.info("start pdf gen 3");
File f = pdfUtil.generatePdf();
response.setHeader("Content-Length", "" + f.length());
response.setHeader("Content-Disposition", "attachment; filename=\"report.pdf\"");
LOG.info("start response ok NEW: " + f);
return new StreamingPdfOutput(f);
}
catch (Throwable ex)
{
ex.printStackTrace();
LOG.error("ERR", ex);
}
LOG.info("start err build");
return null;
}
private class StreamingPdfOutput implements StreamingOutput
{
File pdfFile;
public StreamingPdfOutput(File f)
{
LOG.info("CONT");
pdfFile = f;
}
@Override
public void write(OutputStream os) throws IOException, WebApplicationException
{
try
{
LOG.info("COPY: " + pdfFile);
FileUtils.copyFile(pdfFile, os);
FileUtils.deleteQuietly(pdfFile);
}
catch (Throwable t)
{
LOG.error("ERR COPY", t);
}
}
}
【问题讨论】: