2017-06-02 54 views
1

我使用Filesaver.js尝试从我的后端,这是Express(nodejs)下载文件。下载文件与Angular和Filesaver.js不工作

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

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); 
      }) 
    } 
+0

https://stackoverflow.com/questions/33242959/saving-png-files-with-filesaver-js –

+0

这并不能帮助我的朋友@AhmedMusallam –

+0

你必须设置响应内容类型...看到这里http://talk-about-code.blogspot.de/2017/05/download-file-with-angular2-and.html?m=1 – Ludwig

回答

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') });

重叠响应的内容。