我想通过spring-mvc-rest Controller 返回生成的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 [...]

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

任何提示表示赞赏!

最佳答案

我使用您的代码创建了示例,但是非常相似的方法正在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);
}

否则您可以尝试这个答案Open ResponseEntity PDF in new browser tab

08-06 15:19