jsf - 在应用服务器上限时存储 PDF 并提供下载

标签 jsf tomcat pdf primefaces download

嘿,我正在使用 PrimeFaces 5/JSF 2 和 tomcat!

有人可以告诉我或给我一个关于如何在应用程序服务器(我使用的是 tomcat)上有限时间存储 pdf 文件然后下载它(如果这是用户请求的话)的想法。此功能与发票有关,因此我无法使用 dataExporter。

更具体地说,我几乎实现了这一点,但我不太确定。一个大问题是……我在哪里存储生成的文件?我浏览了一圈,有人说将文件保存在 webApp 或 tomcat 目录中是不行的。我还有什么其他解决方案?

最佳答案

利用File#createTempFile()设施。 servletcontainer 管理的临时文件夹作为应用程序范围的属性可用 ServletContext.TEMPDIR作为关键。

String tempDir = (String) externalContext.getApplicationMap().get(ServletContext.TEMPDIR);
File tempPdfFile = File.createTempFile("generated-", ".pdf", tempDir);
// Write to it.

然后将自动生成的文件名传递给负责提供它的人。例如

String tempPdfFileName = tempPdfFile.getName();
// ...

最后,一旦负责服务的人以文件名作为参数被调用,例如a simple servlet ,然后按如下方式流式传输:

String tempDir = (String) getServletContext().getAttribute(ServletContext.TEMPDIR);
File tempPdfFile = new File(tempDir, tempPdfFileName);
response.setHeader("Content-Type", "application/pdf");
response.setHeader("Content-Length", String.valueOf(tempPdfFile.length()));
response.setHeader("Content-Disposition", "inline; filename=\"generated.pdf\"");
Files.copy(tempPdfFile.toPath(), response.getOutputStream());

另见:

关于jsf - 在应用服务器上限时存储 PDF 并提供下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25430677/

相关文章:

java - JSF + Tomcat 丢失 CSS

bash - 如何使用 PDFTK(或其他命令行应用程序)查找和替换现有 PDF 文件中的文本

tomcat - 单独的异常日志文件

apache - 无法在 Windows 7 上启动 Tomcat 7 服务

java - 如何从 Tomcat 应用程序的类路径中获取所有 jar?

Javascript:模拟 PDF 打印

python - 如何在 Sphinx 文档中包含 PDF?

java - 持久性错误消息 : An instance of a null PK has been incorrectly provided for the find operation

jquery - 如何将 primefaces 按钮悬停效果添加到 html 按钮

jsf - 如何为空输入组件设置自定义非空值 dispite INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL = true