使用ajax时,字节数组pdf文件未在春季启动时下载



除非我安装了互联网下载管理器,否则我的代码不会下载pdf

function downloadPdfDocument(bytes){
$.post("/pdf/" + bytes ).done(function (data) {
}).fail(function() {
$("#cd-errors").show();
$("#cd-errors").html("PDF file could not be downloaded");
});
}
@PostMapping("/pdf/{policyNumber}")
public ResponseEntity<byte[]>  downloadPdf( @PathVariable("policyNumber") String policyNumber) throws IOException, JRException {
//code to prepare parameters 
byte[] contents  = jasperUtils.generateStatement(null, null, null, transactionHistories, statementInformations);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
headers.add("content-disposition", "inline;filename=" + policyNumber + ".pdf");
headers.setContentDispositionFormData(policyNumber + ".pdf", policyNumber + ".pdf");
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
return response;
}

我最终没有使用Ajax。以下代码适用于我的

function downloadPdfDocument(fileName){
var req = new XMLHttpRequest();
req.open("POST", "/pdf/" + fileName, true);
req.responseType = "blob";
fileName += "_" + new Date() + ".pdf";
req.onload = function (event) {
var blob = req.response;
//for IE
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
}
};
req.send();

}

最新更新