在MongoDB中,“证书”集合具有“ _id,studentID,文件”字段。只需为每个文档输入“ _id”和“ studentID”的数据类型为字符串,文件数据类型为Binary(由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”, “ dateTime”:ISODate(“ 2019-01-23T11:45:52.254 + 01:00”), “ studentID”:“ stu123”, “ schoolName”:“ XXX小学”, “文件”:BinData(0,“ JVBERi0xLjcNCiW1tbW1DQoxIDAgb2Jq ...更多101410字节-应用程序/ pdf” ) }
certificate.model.ts :文件
export class Certificate {
_id: string;
dateTime: string;
studentID: string;
schoolName: string;
file: any;
}
然后在Frontend Angular中使用( user.service.ts )从Node( 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文件二进制数据。
答案 0 :(得分:0)
如评论中所述,可以使用this answer来解决您的问题,并进行以下修改:
开始时,您必须将数据转换为blob。在您的情况下,将是:
public getPDFFromFile(file /* place here the correct type of your class*/): Blob {
return new Blob([file.buffer])
}
那么您应该可以使用上述答案。如MongoDB文档所述,您可以通过buffer
类型的Buffer
属性访问内部二进制数据。