Spring - 在浏览器中显示 PDF 文件而不是下载

Spring - display PDF-file in browser instead of downloading

我正在尝试使用 spring 在我的浏览器中显示 pdf。 我的问题是浏览器下载文件而不是显示文件。 这是我的代码:

@RequestMapping(value="/getpdf1", method=RequestMethod.GET)
public ResponseEntity<byte[]> getPDF1() {


    HttpHeaders headers = new HttpHeaders();

    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    String filename = "pdf1.pdf";

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

    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(pdf1Bytes, headers, HttpStatus.OK);
    return response;
}

期待您的解答! 谢谢

你快完成了。只需删除

headers.setContentDispositionFormData(filename, filename);

来自您的代码块。将 multipart/form-data 发送到服务器时应使用它。

Content-Disposition 控制下载或在浏览器中查看

在浏览器中查看

headers.add("Content-Disposition", "inline; filename=" + "example.pdf");

下载

headers.add("Content-Disposition", "attachment; filename=" + "example.pdf");

下面的代码片段将帮助您在浏览器上显示文件


@GetMapping(value = "/terms-conditions")
    public ResponseEntity<InputStreamResource> getTermsConditions() {

        String filePath = "/path/to/file/";
        String fileName = "fileName.pdf";
        File file = new File(filePath+fileName);
        HttpHeaders headers = new HttpHeaders();      
        headers.add("content-disposition", "inline;filename=" +fileName);
        
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/pdf"))
                .body(resource);
    }

查看下面的代码:

headers.setContentDisposition(ContentDisposition.inline().filename("example.pdf").build());

它的工作你应该尝试这样做,通过文件名和浏览器中的 opnend 获取

  @GetMapping(value = "/pdf/{filename:.+}") public ResponseEntity<InputStreamResource> getTermsConditions(@PathVariable String filename) {

    File file = storageService.load(filename).getFile();
 
    HttpHeaders headers = new HttpHeaders();      
    headers.add("content-disposition", "inline;filename=" +fileName);
    
    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.parseMediaType("application/pdf"))
            .body(resource);
}

在浏览器中查看(使用内联):

header.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + pdfFile.getName());

下载(使用附件):

header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + pdfFile.getName());