在应用服务器上限时存储 PDF 并使其可供下载 [英] Store PDF for a limited time on app server and make it available for download

查看:32
本文介绍了在应用服务器上限时存储 PDF 并使其可供下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hei there, I'm using PrimeFaces 5/JSF 2 and tomcat!

有人可以向我展示或告诉我如何在应用程序服务器上(我使用的是 tomcat)在有限时间内存储 pdf 文件,然后下载它(如果这是用户要求的).此功能与发票有关,因此我无法使用 dataExporter.

Can someone show me or give me an idea on how to store pdfs for a limited time on an application server(I'm using tomcat) and then download it (if that's what the user requests). This functionality relates to invoices so I can't use the dataExporter.

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

To be more specific, I pretty much implemented this but I don't feel so sure about it. One big question is... where do I store my generated files? I've browsed around and people said that it's not ok to save the files in the webApp or in the tomcat directory. What other solutiuon do I have?

推荐答案

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

Make use of File#createTempFile() facility. The servletcontainer-managed temporary folder is available as application scoped attribute with ServletContext.TEMPDIR as key.

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

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

Then just pass the autogenerated file name around to the one responsible for serving it. E.g.

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

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

Finally, once the one responsible for serving it is called with the file name as parameter, for example a simple servlet, then just stream it as follows:

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());

另见:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆