将字节数组转换为blob(pdf文件)并使用angular 5

时间:2018-03-13 07:29:28

标签: asp.net-core angular5

我从服务器端接收了一个字节数组,并将其成功转换为blob。但是,当我尝试下载它时,它会显示文件已损坏。以下是我的代码 -

// In client side controller
this.contractsService.downloadPdf(id)
      .then((result) => {
        var blob = new Blob([result], { type: "application/pdf" });
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = "testing.pdf";
        link.click();
      });

// In client side service
private headers = new HttpHeaders({ 'Content-Type': 'application/json' });
downloadPdf(id: number) {
    return this.http.get(this.apiRoutes.download + "/" + id, { headers: this.headers })
      .map((res: any) => res)
      .toPromise();
  }

非常感谢任何形式的帮助。 谢谢。

2 个答案:

答案 0 :(得分:2)

安装file-saver

npm i --save file-saver@latest

您的服务方式

downloadPdf(id: number) {
    return this.http
              .get(this.apiRoutes.download + "/" + id, { responseType:'blob' })
      .toPromise();
  }

现在在你的组件中

import { saveAs } from 'file-saver'

this.contractsService.downloadPdf(id)
      .then(blob=> {
         saveAs(blob, 'testing.pdf');
      });

这应该可以解决问题。 HttpClient现在将从流中提取文件。还可以查看带有HttpClient的blob文档。

答案 1 :(得分:0)

在客户端服务中,尝试显式设置get请求的响应类型:

downloadPdf(id: number) {
    return this.http.get(this.apiRoutes.download + "/" + id, { headers: this.headers; responseType: 'arraybuffer' })
      .map((res: any) => res)
      .toPromise();
  }