我使用spring boot并使用此代码生成pdf文档。
@GetMapping(value = "/members/{memberId}/contract/{contractId}/generalcontracts", produces = "application/pdf")
public ResponseEntity<byte[]> getMemberContract(@PathVariable("memberId") Long memberId, @PathVariable("contractId") Long contractId) throws IOException {
byte[] content = reportService.generateMemberContractReport(contractId);
return prepareReport(content);
}
private ResponseEntity<byte[]> prepareReport(byte[] content) throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String filename = "report.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(content, headers, HttpStatus.OK);
return response;
}
在js中,我做
<button id="memberPrintReport" type="button" class="btn btn-primary">Imprimer</button>
$("#memberPrintReport").on('click', function (e) {
tryit(getHostName() + "/members/" + memberId + "/contract/" + contractId + "/generalcontracts");
}
function tryit(urlServer) {
var win = window.open('_blank');
downloadFile(urlServer, function (blob) {
var url = URL.createObjectURL(blob);
win.location = url;
});
}
打开一个新标签页,我会在几秒钟内看到一个白色标签错误,然后看到pdf。
我不明白为什么我会在几瞬间得到这个白标错误
白标错误的图像 https://imagebin.ca/v/3Wnqxfpq1yR6
编辑:
function downloadFile(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader("Authorization", "Basic " + $.cookie('authorization'));
xhr.responseType = "blob";
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (success)
success(xhr.response);
}
};
xhr.send(null);
}
修改
可以使用chrome,但不适用于firefox
function tryit(urlServer) {
downloadFile(urlServer, function (blob) {
var url = URL.createObjectURL(blob);
window.open(url, '_blank');
});
}
答案 0 :(得分:0)
您正在执行以下行:var win = window.open('_blank');
导致http://localhost:8080/_blank打开,因为javascript将_blank
理解为url。所以你需要将tryit
功能更新为:
function tryit(urlServer) {
downloadFile(urlServer, function (blob) {
var url = URL.createObjectURL(blob);
window.open(url,'_blank');
});
}