这里我创建了用于查看 pdf 部分的 API。 这是我的 API 网址:http://localhost:8082/api/layout/samePdfview/20 问题是当我第一次调用这个 API url 时, 并显示一些错误消息
“java.io.FileNotFoundException:类路径资源[static/layout/pdf/20190215163504_editedLandscape_layoutPort.pdf]无法打开,因为它不存在 ”
当停止服务器并再次运行时,它正在工作,并且显示 pdf。 我找不到问题所在,请任何人帮助我
@RequestMapping(value = "/diffPdfview/{id}", method = RequestMethod.GET ,produces ={MediaType.APPLICATION_PDF_VALUE} )
public ResponseEntity<InputStreamResource> getDiffPdf(@PathVariable("id") int id, HttpServletResponse response) throws IOException {
List<LayoutEntity> getdiffPdf = layoutRepo.findViewImages(id,1);//status=1
String diffPdf = getdiffPdf.get(0).getdLayoutPath();
String diffPdfStr = diffPdf;
diffPdfStr = diffPdfStr.substring(diffPdfStr.lastIndexOf("/"));
return ResponseEntity
.ok()
.body(new InputStreamResource(new ClassPathResource("static/layout/pdf"+diffPdfStr).getInputStream()));
}
最佳答案
试试这个:
public ResponseEntity<byte[]> getDiffPdf(@PathVariable("id") int id, HttpServletResponse response) throws IOException {
List<LayoutEntity> getdiffPdf = layoutRepo.findViewImages(id,1);//status=1
String diffPdf = getdiffPdf.get(0).getdLayoutPath();
String diffPdfStr = diffPdf;
diffPdfStr = diffPdfStr.substring(diffPdfStr.lastIndexOf("/"));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String filename = diffPdfStr;
headers.add("content-disposition", "inline;filename=" + filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
Path pdfPath = Paths.get("static/layout/pdf"+diffPdfStr); //"/path/to/file.pdf"
byte[] pdf = Files.readAllBytes(pdfPath);
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(pdf, headers, HttpStatus.OK);
return response;
}
关于java - Spring Boot 如何做查看 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54708070/