Open ResponseEntity PDF in new browser tab

2020-02-23 08:59发布

I came across a helpful PDF generation code to show the file to the client in a Spring MVC application ("Return generated PDF using Spring MVC"):

@RequestMapping(value = "/form/pdf", produces = "application/pdf")
public ResponseEntity<byte[]> showPdf(DomainModel domain, ModelMap model) {
    createPdf(domain, model);

    Path path = Paths.get(PATH_FILE);
    byte[] pdfContents = null;
    try {
        pdfContents = Files.readAllBytes(path);
    } catch (IOException e) {
        e.printStackTrace();
    }

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    String filename = NAME_PDF;
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(
            pdfContents, headers, HttpStatus.OK);
    return response;
}

I added a declaration that the method returns a PDF file ("Spring 3.0 Java REST return PDF document"): produces = "application/pdf".

My problem is that when the code above is executed, it immediately asks the client to save the PDF file. I want the PDF file to be viewed first in the browser so that the client can decide whether to save it or not.

I found "How to get PDF content (served from a Spring MVC controller method) to appear in a new window" that suggests to add target="_blank" in the Spring form tag. I tested it and as expected, it showed a new tab but the save prompt appeared again.

Another is "I can't open a .pdf in my browser by Java"'s method to add httpServletResponse.setHeader("Content-Disposition", "inline"); but I don't use HttpServletRequest to serve my PDF file.

How can I open the PDF file in a new tab given my code/situation?

3条回答
聊天终结者
2楼-- · 2020-02-23 09:22
/* Here is a simple code that worked just fine to open pdf(byte stream) file 
* in browser , Assuming you have a a method yourService.getPdfContent() that 
* returns the bite stream for the pdf file
*/

@GET
@Path("/download/")
@Produces("application/pdf")
public byte[] getDownload() {
   byte[] pdfContents = yourService.getPdfContent();
   return pdfContents;
}
查看更多
放荡不羁爱自由
3楼-- · 2020-02-23 09:24

What happened is that since you "manually" provided headers to the response, Spring did not added the other headers (e.g. produces="application/pdf"). Here's the minimum code to display the pdf inline in the browser using Spring:

@GetMapping(value = "/form/pdf", produces = "application/pdf")
public ResponseEntity<byte[]> showPdf() {
    // getPdfBytes() simply returns: byte[]
    return ResponseEntity.ok(getPdfBytes());
}
查看更多
我只想做你的唯一
4楼-- · 2020-02-23 09:27

Try

httpServletResponse.setHeader("Content-Disposition", "inline");

But using the responseEntity as follows.

HttpHeaders headers = new HttpHeaders();
headers.add("content-disposition", "attachment; filename=" + fileName)
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(
            pdfContents, headers, HttpStatus.OK);

It should work

Not sure about this, but it seems you are using bad the setContentDispositionFormData, try>

headers.setContentDispositionFormData("attachment", fileName);

Let me know if that works

UPDATE

This behavior depends on the browser and the file you are trying to serve. With inline, the browser will try to open the file within the browser.

headers.setContentDispositionFormData("inline", fileName);

Or

headers.add("content-disposition", "inline;filename=" + fileName)

Read this to know difference between inline and attachment

查看更多
登录 后发表回答