Store PDF for a limited time on app server and make it available for download

前端 未结 2 409
生来不讨喜
生来不讨喜 2020-11-30 12:13

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

Can someone show me or give me an idea on how to store pdfs for a limited time on an application server(I\'m usi

相关标签:
2条回答
  • 2020-11-30 12:25

    Your question is vague, but if my understanding is good:

    First if you want to store the PDF for a limited time you can create a job that clean you PDFs every day or week or whatever you need.

    For the download side, you can use <p:fileDownload> (http://www.primefaces.org/showcase/ui/file/download.xhtml) to download any file from the application server.

    0 讨论(0)
  • 2020-11-30 12:47

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

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

    See also:

    • How to save generated file temporarily in servlet based web application
    • Recommended way to save uploaded files in a servlet application
    0 讨论(0)
提交回复
热议问题