利用File#createTempFile() http://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String)设施。 servlet容器管理的临时文件夹可作为应用程序范围的属性使用ServletContext.TEMPDIR http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#TEMPDIR as key.
String tempDir = (String) externalContext.getApplicationMap().get(ServletContext.TEMPDIR);
File tempPdfFile = File.createTempFile("generated-", ".pdf", tempDir);
// Write to it.
然后只需将自动生成的文件名传递给负责提供服务的人即可。例如。
String tempPdfFileName = tempPdfFile.getName();
// ...
最后,一旦负责提供服务的人被调用,并以文件名作为参数,例如一个简单的servlet https://stackoverflow.com/questions/16207479/how-to-show-pdf-document-in-jsp-which-is-included-via-uiinclude/16215286#16215286,然后按如下方式进行流式传输:
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());
也可以看看:
- 如何在基于 servlet 的 Web 应用程序中临时保存生成的文件 https://stackoverflow.com/questions/31255366/java-io-filenotfoundexception-when-trying-to-save-generated-file-in-web-applicat
- 在 servlet 应用程序中保存上传文件的推荐方法 https://stackoverflow.com/questions/18664579/recommended-way-to-save-uploaded-files-in-a-servlet-application