如何在弹簧 mvc rest 控制器中返回二进制数据而不是 base64 编码的 byte[]

2022-09-04 19:35:30

我想通过spring-mvc-rest控制器返回生成的pdf文件。这是我当前使用的代码的缩短版本:

@RestController
@RequestMapping("/x")
public class XController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ResponseEntity<byte[]> find() throws IOException {
        byte[] pdf = createPdf();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(new MediaType("application", "pdf"));
        headers.setContentDispositionFormData("attachment", "x.pdf");
        headers.setContentLength(pdf.length);
        return new ResponseEntity<byte[]>(pdf, headers, HttpStatus.OK);
    }
}

这几乎可以正常工作,它只是将实际的字节数组作为base64编码:(

curl -i 'http://127.0.0.1:8080/app/x'

Server: Apache-Coyote/1.1
Content-Disposition: form-data; name="attachment"; filename=x.pdf"
Content-Type: application/pdf
Content-Length: 138654
Date: Fri, 08 Jan 2016 11:25:38 GMT

"JVBERi0xLjYNJeLjz9MNCjMyNCAwIG9iag [...]

(顺便说一句,响应甚至不包含结束:)"

任何提示赞赏!


答案 1

这个问题是由Spring试图将响应编码为Json引起的。

您的请求可能指定了,并且由于Spring忽略了响应实体的,因此发现最佳编码是。Accepts = "*/*"ContentTypeapplication/json

最简单的解决方法是将 a 添加到您的请求映射中,这样您的代码就会变成:produces

@RestController
@RequestMapping(value = "/x",
                produces = "application/pdf") // <-- Add this
public class XController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ResponseEntity<byte[]> find() throws IOException {
        byte[] pdf = createPdf();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);
        headers.setContentDispositionFormData("attachment", "x.pdf");
        headers.setContentLength(pdf.length);
        return new ResponseEntity<byte[]>(pdf, headers, HttpStatus.OK);
    }
}

答案 2

我使用您的代码创建了该示例,但是在我的Web应用程序中执行他的工作非常相似的方法:

@RequestMapping(value = "/", method = RequestMethod.GET)
public void downloadFile(HttpServletResponse response,
                         HttpServletRequest request) throws IOException
{
    byte[] pdf = createPdf();

    response.setContentType("application/x-download");
    response.setHeader("Content-Disposition", "attachment; filename=foo.pdf");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.getOutputStream().write(pdf);
}

否则,您可以尝试这个答案 在新浏览器选项卡中打开响应实体PDF


推荐