Donald
Donald

Reputation: 339

Display the PDF file stored on the webserver on Browser new window using Spring MVC

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

Upvotes: 2

Views: 5984

Answers (1)

JB Nizet
JB Nizet

Reputation: 692181

Remove the line

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

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

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

Upvotes: 4

Related Questions