【问题标题】:download node stream with angular 2使用角度 2 下载节点流
【发布时间】:2018-03-18 02:25:07
【问题描述】:

我正在尝试使用节点 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);
            });

        });
    });
});

在 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");

        });
}

我得到这个错误:Failed to execute 'createObjectURL' on 'URL' 如果我把这条线改成这个

FileSaver.saveAs(response.blob(), "testdata.pdf");

然后我得到这个错误:Error: The request body isn't either a blob or an array buffer

我不知道我在做什么错,顺便说一句,有没有一种方法可以轻松下载此流,而无需任何像文件保护程序这样的插件?因为如果我只是在浏览器上输入和 api 链接,它会自动下载我的 pdf 文件。

提前谢谢你,丹尼尔。

【问题讨论】:

    标签: javascript node.js angular pdf


    【解决方案1】:

    我假设 angular 部分正在客户端浏览器上运行。 为什么不使用fetch API 向节点请求文件?

    const response = await fetch("http://localhost:3000/pdf/contacts");
    const blob = await response.blob();
    

    要使用它,您需要使用async await syntax,因为从站点请求数据,即使它来自本地服务器,也是一个异步任务,并且您的代码将继续运行,而无需等待请求完成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-21
      • 2018-05-08
      • 2018-03-20
      • 1970-01-01
      • 2017-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多