Store PDF for a limited time on app server and make it available for download
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?
Solution 1:
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