使用Angular和Filesaver.js下载文件无法正常工作

时间:2017-06-02 19:31:12

标签: node.js angular express downloading filesaver.js

我使用Filesaver.js尝试从我的后端下载文件,该文件在Express(nodejs)上。

这是我下载文件的后端代码。它使用中间件来检查身份验证信息。

res.download(url, function (err) {
   if (err) {
      console.log("Error: " + err);
      res.status.send({
         message: "Can not download file"
      });
   }
});

这是我服务的代码:

downloadEventAttachment(attachmentUrl){

    let endPointUrl = this.auth.getServerHost();

    this.authHttp.get(endPointUrl + attachmentUrl)
        .subscribe(res => {
            var blob = new Blob([res], { type: res.headers.get('Content-Type') });
            saveAs(blob);
        }) 
}

问题是生成下载文件但有错误。 如果我下载图像,则表示图像无效。

enter image description here

如果我尝试下载txt文件,则会有以下内容:

Response with status: 200 OK for URL: http://192.168.1.78:8081/calendar/download_eventattachment/728/file-1496421767591.txt

如果我使用邮递员的这个请求,那么图像就会很好地显示出来。

enter image description here

我做错了什么?

非常感谢

[更新1]

我添加了responseType但仍无效:

downloadEventAttachment(attachmentUrl){
        let endPointUrl = this.auth.getServerHost();

        let options = new RequestOptions({ responseType: ResponseContentType.Blob });

        this.authHttp.get(endPointUrl + attachmentUrl, options)
            .subscribe(res => {

                var blob = new Blob([res], { type: res.headers.get('Content-Type') });
                saveAs(blob);
            },
            error => {
                console.log(error);
            })
    }

1 个答案:

答案 0 :(得分:0)

最后以这种方式工作:

downloadEventAttachment(attachmentUrl){
    let endPointUrl = this.auth.getServerHost();
    let options = new RequestOptions({ responseType: ResponseContentType.Blob });
    this.authHttp.get(endPointUrl + attachmentUrl, options)
        .subscribe(res => {
                var file = res.blob();
            });
            saveAs(file);
        },
        error => {
            console.log(error);
        })
}

我认为旧行:var blob = new Blob([res], { type: res.headers.get('Content-Type') });

重叠了回复的内容。