Open ResponseEntity PDF in a new browser tab

I came across useful PDF generation code to show a file to a client in a Spring MVC application ( "Returning a generated PDF file 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 the announcement that the method returns a PDF file ( "Spring 3.0 the Java the REST return statement PDF document" ): produces = "application/pdf".

My problem is that when executing the above code, 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.

" PDF- ( MVC Spring) " , target="_blank" Spring. , , , .

" .pdf Java" , httpServletResponse.setHeader("Content-Disposition", "inline");, HttpServletRequest PDF .

PDF , /​​?

+11
2

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

responseEntity .

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

, , , setContentDispositionFormData, >

headers.setContentDispositionFormData("attachment", fileName);

,

UPDATE

, . inline .

headers.setContentDispositionFormData("inline", fileName);

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

,

+14
/* 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;
}
0

Source: https://habr.com/ru/post/1623413/


All Articles