使用Spring MVC在Browser new窗口中显示存储在Web服务器上的PDF文件 [英] Display the PDF file stored on the webserver on Browser new window using Spring MVC

查看:82
本文介绍了使用Spring MVC在Browser new窗口中显示存储在Web服务器上的PDF文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在浏览器中显示PDF文件.我使用Spring MVC.有没有不使用AbstractPdfView就可以做到这一点的方法?我不想在运行时渲染PDF.所有PDF文件都将存储在我的网络服务器中.

I have a requirement to show PDF files in a browser. I use Spring MVC. Is there a way I can do this without using AbstractPdfView? I do not want to render the PDF at runtime. All the PDF files will be stored in my webserver.

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

This is the code I am using. But this directly downloads the file instead of showing it up in a browser.

@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();
}

推荐答案

删除行

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

此行恰好告诉浏览器显示下载/保存对话框,而不是直接显示PDF.

This line precisely tells the browser to display a download/save dialog rather than displaying the PDF directly.

哦,请确保在finally块中关闭输入sytream.

Oh, and make sure to close the input sytream in a finally block.

这篇关于使用Spring MVC在Browser new窗口中显示存储在Web服务器上的PDF文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆