【发布时间】:2019-11-21 18:56:02
【问题描述】:
我正在尝试通过我的 Spring 控制器发送生成的 PDF,当我将它保存为服务器上的文件并打开它时,我已经验证它看起来很好。当我发送请求时,它会打开一个新选项卡并且 pdf 是空白的。有正确的页数和一切,只是空白。
我已经从浏览器保存了PDF,并与在服务器上生成并保存的PDF进行了比较,浏览器中的PDF更大,这让我相信编码错误。但是我查看了许多其他发送 PDF 的 Spring 控制器示例,并且我的代码与他们的代码相同。控制器发回一个 ResponseEntity(我也试过 ResponseEntity)
@RequestMapping(value = "/generatePDF", method = RequestMethod.POST, produces = "application/pdf")
public ResponseEntity<byte[]> generatePDF(@RequestBody UserObject userObject) {
//Generation of PDF
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
headers.setContentDispositionFormData("inline", "document.pdf");
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
try {
File file = new File("/path/to/document.pdf");
byte[] filecontent = Files.readAllBytes(file.toPath());
return new ResponseEntity(filecontent,headers, HttpStatus.OK);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
发出请求的javascript是:
$.ajax({
type: "POST",
url: "myURL",
contentType: "application/json",
data : JSON.stringify(data),
async: false,
success: function(response) {
console.log(response)
window.open(URL.createObjectURL(new File([response], "document.pdf")));
}
});
打开一个新选项卡,但 pdf 为空白,并且二进制数据在服务器上保存的数据与从浏览器下载的数据看起来不同
【问题讨论】:
-
您好,尝试添加 headers.add("content-disposition", "inline;filename=" + filename);让我知道结果