在HTTP POST上,我必须返回PDF文档。我正在与邮递员进行测试,并且工作正常。当我尝试在Angular应用中使用它时,出现此错误(出于格式化原因,以图片形式发布):
所以我的回答有问题,但是我找不到错误。
创建响应的位置:
public ResponseEntity<byte[]> compareWithLocal(CompareJob compareJob) {
logger.info(compareJob);
File leftFile = compareJob.getFile1();
File rightFile = compareJob.getFile2();
byte[] document = null;
HttpHeaders header = new HttpHeaders();
try {
final CompareResult result = new PdfComparator(leftFile, rightFile, new CompareResultWithPageOverflow()).compare();
if (result.isEqual()) {
logger.info("Compare job is: equal");
} else {
String path = System.getProperty("java.io.tmpdir");
System.out.println("File written to: " + path);
result.writeTo(path + "demo");
compareJob.setCompareResultFile(new File(path + "demo.pdf"));
// TODO: Delete temp
logger.info("Compared file path: " + compareJob.getCompareResultFile());
document = FileCopyUtils.copyToByteArray(compareJob.getCompareResultFile());
header.setContentType(new MediaType("application", "pdf"));
header.set("Content-Disposition", "inline; filename=" + compareJob.getCompareResultFile().getName());
header.setContentLength(document.length);
logger.info(document);
}
} catch (IOException e) {
e.printStackTrace();
}
return new ResponseEntity<byte[]>(document, header, HttpStatus.OK);
}
在调用该方法以创建响应的位置:
@PostMapping("/pdfdiffLocal")
ResponseEntity<byte[]> pdfDiffLocal(@RequestParam("file1") MultipartFile file1, @RequestParam("file2") MultipartFile file2) {
logger.info("Received File 1: " + file1.getOriginalFilename() + ", File 2: " + file2.getOriginalFilename());
PdfDiffCompare pdfDiffCompare = new PdfDiffCompare();
File converted1 = convert(file1);
logger.info("File 1: " + converted1);
File converted2 = convert(file2);
logger.info("File 2: " + converted2);
CompareJob compareJob = new CompareJob(converted1, converted2);
logger.info("Compare Job after convert. F1: " + compareJob.getFile1() + " F2: " + compareJob.getFile2());
ResponseEntity<byte[]> returnComparison = pdfDiffCompare.compareWithLocal(compareJob);
logger.info(returnComparison);
return returnComparison;
}
这是我在ResponseEntity上登录的内容:
<200 OK OK,[B@50fdfe86,{Content-Type=[application/pdf], Content-Disposition=[inline; filename=demo.pdf], Content-Length=[838078]}>
我称之为后端的角部分:
comparePdfDiff() {
console.log('Submitted PDF Diff');
let formModel = this.prepareSave();
this.loading = true;
console.log('Formmodel: ', formModel);
this.http.post('http://localhost:8080/pdfdiffLocal', formModel)
.subscribe((response: ApiResponseModel) => {
console.log('response: ', response);
this.router.navigate(['/pdfdiff']);
let returnValue = JSON.stringify(response);
console.log('parsed: ', returnValue);
this.comparejobdataService.pdfFile.push(response.pdfFile);
});
setTimeout(() => {
this.loading = false;
}, 10000);
}
感谢您的帮助!