我有这样的休息终点:
@PostMapping(value = "/pdf")
public ResponseEntity<byte[]> downloadPdf(@RequestBody ReportData reportData) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
headers.setContentDispositionFormData(reportData.getFileName(), reportData.getFileName() + ".pdf");
try {
byte[] generatedPdf = downloadService.getPdf(reportData.getUrl(), reportData.getParams(), reportData.getReportName());
return new ResponseEntity<>(generatedPdf, headers, HttpStatus.OK);
} catch (IOException e) {
logger.error("Error downloading report.", e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
我使用这样的ajax来调用它;
$.ajax({
type: 'POST',
contentType: 'application/json',
responseType: 'arraybuffer',
url: 'api/download/pdf',
data: JSON.stringify(constructPostData()),
success: function (result) {
var blob = new Blob([result], {type: "application/pdf"});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = reportName;
link.click();
},
error: function (xhr, status) {
console.log(status);
}
});
但这只会给我一个空的pdf。
如果我用其他客户端点击它,然后从那里下载pdf,则可以看到正确的pdf。
答案 0 :(得分:0)
我已经更改了像波纹管这样的ajax请求及其工作方式
$.ajax({
method: 'POST',
contentType: 'application/json',
xhrFields: {
responseType: 'blob'
},
url: 'api/download/pdf',
data: JSON.stringify(constructPostData()),
success: function (result) {
var link = document.createElement('a');
link.href = window.URL.createObjectURL(result);
link.download = reportName;
link.click();
},
error: function (xhr, status) {
console.log(status);
}
});