从控制器 spring 引导在浏览器中预览 pdf:无法识别的响应类型;将内容显示为文本

preview pdf in browser from controller spring boot: Unrecognized response type; displaying content as text

我想预览用 java 生成的 pdf 文件,但下面的代码给出了这个错误

Unrecognized response type; displaying content as text.

@GetMapping("/previewPDF/{codeStudent}")
    public ResponseEntity<byte[]> previewPDF(@PathVariable("codeStudent") String code) throws IOException {
        
        byte[] pdf = //pdf content in bytes

        HttpHeaders headers = new HttpHeaders();      
        headers.add("Content-Disposition", "inline; filename=" + "example.pdf");
        headers.setContentType(MediaType.parseMediaType("application/pdf"));
        return ResponseEntity.ok().headers(headers).body(pdf); 
    }

更新:这是错误的截图

您需要为您的资源指定响应 PDF 媒体类型。
参见 RFC standart. Full list of Media Types
Spring 有关 produces Media Type 的文档。

    @GetMapping(value = "/previewPDF/{codeStudent}", produces = MediaType.APPLICATION_PDF_VALUE)
    public ResponseEntity<byte[]> previewPDF(@PathVariable("codeStudent") String code) throws IOException

同时为您的 ResponseEntity

设置 PDF 内容类型
    @GetMapping(value = "/previewPDF/{codeStudent}", produces = MediaType.APPLICATION_PDF_VALUE)
    public ResponseEntity<byte[]> previewPDF(@PathVariable("codeStudent") String code) throws IOException {
        byte[] pdf = null;
        HttpHeaders headers = new HttpHeaders();
        String fileName = "example.pdf";
        headers.setContentDispositionFormData(fileName, fileName);        
        headers.setContentType(MediaType.APPLICATION_PDF);
        return ResponseEntity.ok().headers(headers).body(pdf);
    }