pdf文件无法';使用ajax无法保存
我有这样的rest端点:pdf文件无法';使用ajax无法保存,ajax,spring,pdf,download,http-post,Ajax,Spring,Pdf,Download,Http Post,我有这样的rest端点: @PostMapping(value = "/pdf") public ResponseEntity<byte[]> downloadPdf(@RequestBody ReportData reportData) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_PDF); headers.setCacheCo
@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);
}
}
但这只给了我一个空的pdf如果我用rest客户端点击这个按钮并从那里下载pdf,我可以看到正确的pdf。我已经更改了ajax请求,如bellow及其工作方式
$.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);
}
});
$.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);
}
});