您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在有限的时间内将PDF存储在应用服务器上,并使其可供下载

在有限的时间内将PDF存储在应用服务器上,并使其可供下载

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

最后,一旦使用文件名作为参数调用负责提供服务的对象,则只需按如下所示对其进行流处理:

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());
其他 2022/1/1 18:16:29 有622人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶