后台
@RequestMapping(value = "/file", method = RequestMethod.GET)
public ResultJson getGuidePDFInfoByDirectory(@RequestParam String fileDirectory){
// System.out.println("收到加载pdf文件请求,路径为:");
// System.out.println(fileDirectory);
String path = "static/pdf/upload/" + fileDirectory;
// String path = "static/pdf/upload/Use a GHOST-CAP in acute brain injury.pdf";
byte[] buffer = null;
try {
ClassPathResource classPathResource = new ClassPathResource(path);
File file = classPathResource.getFile();
// System.out.println("读取文件:");
// System.out.println(file.getName());
InputStream inputStream = classPathResource.getInputStream();
//输出文件
InputStream fis = new BufferedInputStream(inputStream);
buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
}catch (FileNotFoundException e){
System.out.println("文件不存在或者文件不可读或者文件是目录");
}catch (IOException e){
e.printStackTrace();
}
String json = new String(Base64.getEncoder().encode(buffer));
return ResultJson.success(json);
}
前端
ts文件
// 根据文件路径返回pdf文件并在新的页面显示
public openPdf() {
let url = `api/file?fileDirectory=${this.selectedPDFInfo.fileDirectory}`;
this.guidePDFinfoService.downloadFile(url).subscribe(
(res) => {
//Base64解密
this.bytes = atob(res);
// 与Buffer配套使用
(window as any).global = window;
// @ts-ignore
window.Buffer = window.Buffer || require('buffer').Buffer;
// 将二进制字符串编码为二进制的buffer
const buf = Buffer.from(this.bytes, 'binary');
//添加进Blob文件
let blob = new Blob([buf], {type:'application/pdf'});
// console.log(blob);
this.pdfViewer.pdfSrc = blob; // pdfSrc can be Blob or Uint8Array
this.pdfViewer.refresh(); // Ask pdf viewer to load/refresh pdf
}
);
}
html模板
<div >
<button nz-button (click)="openPdf()"
>
{{selectedPDFInfo.name}}
</button>
</div>
<div style=" height: 36px;line-height: 36px;">
备注:
</div>
<div>
<textarea rows="4" nz-input [(ngModel)]="selectedPDFInfo.note" >
{{selectedPDFInfo.note}}
</textarea>
</div>
<!-- <div>-->
<!-- <button nz-button (click)="save()">保存文件</button>-->
<!-- </div>-->
<div style="width: 800px; height: 400px">
<ng2-pdfjs-viewer
#pdfViewer
[externalWindow]="true"
[downloadFileName]="this.selectedPDFInfo.name"
[openFile]="false"
[viewBookmark]="false"
[download]="false"></ng2-pdfjs-viewer>
</div>
service.ts
// 从后台获取pdffile
downloadFile(url:string):Observable<any>{
return this.http.get<any>(url);
}