我正在尝试使用 Node js 在服务器端生成 PDF,并在 Angular 4 上将其下载到客户端(就像当您按“下载为 PDF”时 Google Drive 所做的那样)。
Node JS 代码如下所示:
var pdf = require('html-pdf');
app.get('/pdf/contacts', function(req, res) {
Contact.find(function(error, response) {
res.render('pdfs/views/contacts', {name: 'Daniel Pacuraru', contacts: response}, function(error, thtml) {
var opts = {
"format": "A4",
"orientation": "portrait",
"border": "0.4in"
};
pdf.create(thtml, opts).toStream(function(err, stream){
res.attachment('pdfname.pdf');
stream.pipe(res);
});
});
});
});
在 Angular 4 边上,我得到了这样的东西:
import * as FileSaver from 'file-saver';
downloadContacts(): Promise<any> {
return this.http
.get('http://localhost:3000/pdf/contacts')
.toPromise()
.then(response => {
FileSaver.saveAs(response, "testdata.pdf");
});
}
我收到此错误:无法在“URL”上执行“createObjectURL”
,如果我将此行更改为此
FileSaver.saveAs(response.blob(), "testdata.pdf");
然后我收到此错误:错误:请求正文不是 blob 或数组缓冲区
我不知道我做错了什么,顺便说一句,有没有一种方法可以轻松下载这个流,而不需要任何像文件保护程序这样的插件?因为如果我只是在浏览器上输入 api 链接,它会自动下载该 pdf 文件。
提前谢谢你,丹尼尔。
最佳答案
我假设 Angular 部分正在客户端浏览器上运行。
为什么不使用 fetch
API 向 Node 请求文件?
const response = await fetch("http://localhost:3000/pdf/contacts");
const blob = await response.blob();
要使用此功能,您需要使用async wait
syntax ,因为从站点请求数据,即使是从本地服务器请求数据,也是一个异步任务,并且您的代码将继续运行,而无需等待请求完成。
关于javascript - 使用 Angular 2 下载 Node 流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46603039/