5

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 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.

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?

Theo
  • 171
  • 2
  • 5
  • 16

2 Answers2

4

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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Just an observation, the line: `String tempDir = (String) getServletContext().getAttribute(ServletContext.TEMPDIR);` gives ClassCastException because it returns a File not a String. – lboullo0 Mar 01 '18 at 17:01
0

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.

faissalb
  • 1,739
  • 1
  • 12
  • 14