【问题标题】:Store PDF for a limited time on app server and make it available for download在应用服务器上存储 PDF 并提供下载
【发布时间】:2014-10-15 08:14:21
【问题描述】:

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

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

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

【问题讨论】:

    标签: jsf tomcat pdf primefaces download


    【解决方案1】:

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

    另见:

    【讨论】:

    • 只是一个观察,这行:String tempDir = (String) getServletContext().getAttribute(ServletContext.TEMPDIR); 给出 ClassCastException 因为它返回一个文件而不是一个字符串。
    【解决方案2】:

    您的问题含糊不清,但如果我的理解良好:

    首先,如果您想在有限的时间内存储 PDF,您可以创建一个每天或每周或任何您需要的清理 PDF 的作业。

    对于下载端,您可以使用<p:fileDownload> (http://www.primefaces.org/showcase/ui/file/download.xhtml) 从应用服务器下载任何文件。

    【讨论】:

      猜你喜欢
      • 2016-08-06
      • 2022-01-21
      • 1970-01-01
      • 2012-12-08
      • 1970-01-01
      • 1970-01-01
      • 2015-08-08
      • 1970-01-01
      相关资源
      最近更新 更多