之前写了一份读取服务器word、txt文档,页面转成PDF预览的文章,因为前端页面在没有安装解析插件的情况下,一般word、txt等文档是无法直接预览的。如果有需要的可以去之前的文章查看。
今天主要写一个前端页面直接读取服务器的PDF文件并在Html预览的功能。上传文件这些功能就不介绍了,下面直接看代码。
首先看下文件存储到数据库的路径
Html页面:
<td>
<a th:href="@{'/culture/viewcontent?id='+${it.id}}"style="color: blue">阅读</a>
</td>
controller层
@ResponseBody
@RequestMapping("viewcontent")
public voidviewcontent(HttpServletRequest request, HttpServletResponse response, Culture exper)
throws IOException {
ModelAndView mv = new ModelAndView("meditation/view_culture");
exper = cultureService.selectCultureByID(exper);// 查询对象存放路径
String filePath = exper.getFilePath();
response.setContentType("application/pdf");
FileInputStream in = new FileInputStream(new File(filePath));
OutputStream out = response.getOutputStream();
byte[] b = new byte[512];
while ((in.read(b)) != -1) {
out.write(b);
}
out.flush();
in.close();
out.close();
}
相对比较简单,后台获取PDF文件路径,然后将其以流的方式进行传输,当然后台处理的方式有很多种,本文只是举了一个常用的例子。
注意点:不需要再去定义一个专门显示PDF的页面,controller也不需要返回值,如果给了返回值,getOutputStream()方法会被重复调用,出现getOutputStream() has already been called for this response的异常,因为页面内置对象out会处理后台传递的数据,这样就会重复调用getOutputStream()。