【java】web在线打开PDF文件

项目中用java实现,当用户点击那个pdf链接时,不弹出下载提示框,而是以网页的形式打开这个pdf。

1.前端有一个<a>标签,当点击事件发生之后要把文件所在的路径传到后台

2.后台代码如下

    @RequestMapping("showPhoto.do")
   public String getpic(String path, HttpServletRequest request, HttpServletResponse response) throws IOException {
       File file = new File(path);
       if (!file.exists()) {
           request.setAttribute("error", "附件已删除或不存在");
           //      return "/error";
       }
       InputStream in = null;
       OutputStream os = null;
       try {
           response.setContentType("application/pdf"); // 设置返回内容格式
           in = new FileInputStream(file);   //用该文件创建一个输入流
           os = response.getOutputStream();  //创建输出流
           byte[] b = new byte[1024];
           while (in.read(b) != -1) {
               os.write(b);
           }
           in.close();
           os.flush();
           os.close();
       } catch (Exception e) {
           try {
               if (null != in) {
                   in.close();
               }
           } catch (IOException e1) {
               e1.printStackTrace();
           }
           try {
               if (null != os) {
                   os.close();
               }
           } catch (IOException e2) {
               e2.printStackTrace();
           }


       }
       return null;

   }

3.如图所示

【java】web在线打开PDF文件