2

我需要在浏览器中显示 PDF 文件。我使用 Spring MVC。有没有办法在不使用 AbstractPdfView 的情况下做到这一点?我不想在运行时呈现 PDF。所有的 PDF 文件都将存储在我的网络服务器中。

这是我正在使用的代码。但这会直接下载文件,而不是在浏览器中显示。

@RequestMapping(value = "/download" , method = RequestMethod.GET)
public void doDownload(HttpServletRequest request,
       HttpServletResponse response) throws IOException {

   // get absolute path of the application
   ServletContext context = request.getSession().getServletContext();
   String appPath = context.getRealPath("");
   String filename= request.getParameter("filename");
   filePath = getDownloadFilePath(lessonName);

   // construct the complete absolute path of the file
   String fullPath = appPath + filePath;       
   File downloadFile = new File(fullPath);
   FileInputStream inputStream = new FileInputStream(downloadFile);

   // get MIME type of the file
   String mimeType = context.getMimeType(fullPath);
   if (mimeType == null) {
       // set to binary type if MIME mapping not found
       mimeType = "application/pdf";
   }
   System.out.println("MIME type: " + mimeType);


   String headerKey = "Content-Disposition";

   response.addHeader("Content-Disposition", "attachment;filename=report.pdf");
   response.setContentType("application/pdf");

   // get output stream of the response
   OutputStream outStream = response.getOutputStream();

   byte[] buffer = new byte[BUFFER_SIZE];
   int bytesRead = -1;

   // write bytes read from the input stream into the output stream
   while ((bytesRead = inputStream.read(buffer)) != -1) {
       outStream.write(buffer, 0, bytesRead);
   }

   inputStream.close();
   outStream.close();
}
4

1 回答 1

4

删除线

response.addHeader("Content-Disposition", "attachment;filename=report.pdf");

这一行准确地告诉浏览器显示下载/保存对话框,而不是直接显示 PDF。

哦,确保在 finally 块中关闭输入系统。

于 2013-04-02T20:03:02.633 回答