【发布时间】:2015-09-08 22:08:49
【问题描述】:
如何获取位于服务器目录结构中的文件中的 pdf,以便为 Spring MVC 应用程序的用户加载到浏览器中?
我在谷歌上搜索了这个并找到了关于如何生成 PDF 的帖子,但他们的答案在这种情况下不起作用。例如,this other posting 不相关,因为下面我的代码中的res.setContentType("application/pdf"); 不能解决问题。此外,this other posting 描述了如何从数据库中执行此操作,但没有显示完整的工作控制器代码。其他帖子也有类似的问题,导致它们在这种情况下无法正常工作。
我需要简单地提供一个文件(而不是来自数据库),并让用户在他们的浏览器中查看它。我想出的最好的是下面的代码,它要求用户下载 PDF 或在浏览器之外的单独应用程序中查看它。 我可以对下面的特定代码进行哪些具体更改,以便用户在单击链接时自动在浏览器中看到 PDF 内容,而不是被提示下载?
@RequestMapping(value = "/test-pdf")
public void generatePdf(HttpServletRequest req,HttpServletResponse res){
res.setContentType("application/pdf");
res.setHeader("Content-Disposition", "attachment;filename=report.pdf");
ServletOutputStream outStream=null;
try {
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(new File("/path/to", "nameOfThe.pdf")));
/*ServletOutputStream*/ outStream = res.getOutputStream();
//to make it easier to change to 8 or 16 KBs
int FILE_CHUNK_SIZE = 1024 * 4;
byte[] chunk = new byte[FILE_CHUNK_SIZE];
int bytesRead = 0;
while ((bytesRead = bis.read(chunk)) != -1) {outStream.write(chunk, 0, bytesRead);}
bis.close();
outStream.flush();
outStream.close();
}
catch (Exception e) {e.printStackTrace();}
}
【问题讨论】:
标签: spring spring-mvc pdf