如何从获取的二进制数据中在前端Angular中显示pdf(二进制数据是从REST API接收的对象的元素之一)



在MongoDB中,'certificate'集合有'_id,studentID,file'字段。简单地说,我可以为每个文档输入,其中"_id"one_answers"studentID"的数据类型是字符串,文件数据类型是二进制的(这个二进制是MongoDB在插入每个用户pdf文件时自动生成的)。

从提取的数据中,我可以显示成角度(例如StudentID、SchoolName),但只有我不能将提取的二进制数据中的pdf显示成角度

在节点服务器中:(app.js)//给出核心代码以避免读取过长

//用于将数据插入MongoDB

**var fs = require('fs');  
var pdfBinary = fs.readFileSync("./TestingPurpose.pdf"); 
var pdf = new mongodb.Binary(pdfBinary);**
db.collection('Test').insert({                    
dateTime: new Date(dateTime),
studentName: studentName,
Principal: principalName,
file: pdf }
  • 在MongoDB中成功导入数据后,可以看到MongoDB中的数据如下:

    {"_id":"C1135","日期时间":ISODate("2019-01-23T11:45:52.254+01:00"),"studentID":"stud123","学校名称":"XXX小学","file":BinData(0,"JVBERi0xLjcNCiW1tbW1DQoxIDAgb2Jq…more 101410 bytes-application/pdf">)}


证书.model.ts:文件

export class Certificate {
_id: string;
dateTime: string;
studentID: string;
schoolName: string;
file: any;
}

然后在前端角度使用(user.service.ts)从节点(app.js

import { Certificate } from '../model/certificate.model';
cert: Certificate[];
// receiving all students info
getCertificates() {
return this.http.get('http://localhost:5600/aziz/displayAllCertificates');
}
// to get always get an instant update I use refreshGetCertificates()
refreshGetCertificates() {
this.chkSubscrip = this.getCertificates().subscribe((res) => {
this.cert= res as Certificate[];
});
}

在证书组件中:(certificate.component.ts):

export class CertificatesComponent implements OnInit, OnDestroy {
myPDF: any;
constructor(
public userService: UserService,
private dialog: MatDialog,
) { }
ngOnInit() {
this.userService.refreshGetCertificates();
}
pdfView(receiveObj) {
this.forPDF = !this.forPDF;
const myUint8 = new Uint8Array(receiveObj);
this.myPDF= myUint8;
}
}

(certificate.component.html):

<div class="rows">
<ul class="settings_test headerclass text-center">
<li style="float: left">ID</li>
<li>Student-ID</li>
<li>School</li>
<li>PDF View</li>
</ul>
</div>
<div *ngFor="let eachCerts of userService.cert">
<div class="row">
<div class="settings_test">
<li style="width:10%">{{eachCerts._id}}</li>
<li style="width:10%">{{eachCerts.studentID}}</li>
<li style="width:10%">{{eachCerts.schoolName}}</li>
<li style="width:10%"> <button (click) ="pdfView(eachCerts.file)">  View as PDF </button></li>
<object *ngIf=forPDF data="{{myPDF}}" ></object>
</div>
</div>
</div>

在每一行中都会显示ID、StudentID、学校名称和一个按钮("以PDF格式查看"),当点击该按钮时,会出现一个弹出窗口或一个新窗口,显示提取的PDF二进制数据中的PDF文件。

如评论中所述,您可以使用这个答案来解决您的问题,并进行以下修改:

一开始,您必须将数据转换为blob。在你的情况下,这将是:

public getPDFFromFile(file /* place here the correct type of your class*/): Blob {   
return new Blob([file.buffer])
}

那么你应该能够使用上面提到的答案。正如MongoDB文档所指出的,您可以通过类型为Bufferbuffer属性访问内部二进制数据。

最新更新