Angular 6:从后端服务器获取文件对象后下载文件

时间:2018-09-11 14:42:42

标签: angular angular6 angular-universal

我有一个结构为{type:“ Buffer”,data:Array(702549)}的File对象类型,我需要在angular 6中做什么才能在浏览器中下载该文件?

我从此函数得到响应:

  getMarketingProposalById(id: string): Observable<MarketingProposal> {
    return this.httpClient.get<MarketingProposal>(this.apiUrl  + id , this.httpOptions).pipe(map(marketingProposal => {
      if (marketingProposal.materials[0] && marketingProposal.materials[0].file) {
        const blob = new Blob([marketingProposal.materials[0].file.data], { type: 'image/png' });
        console.log(blob);
        // saveAs(blob, 'hello.png');
      }
      const marketingProposalObject = this.assignMarketingProposalObject(marketingProposal);
      this.mapStringToDate(marketingProposalObject);
      return marketingProposalObject;
    }));
  }

marketingProposal.materials [0] .file的格式为{type:“ Buffer”,数据:Array(702549)}

1 个答案:

答案 0 :(得分:5)

您可以使用文件保护程序来执行此操作:https://www.npmjs.com/package/file-saver

文件下载代码:

obj.(str)

更新: 我已经根据负载条件创建了一个测试项目:

import { saveAs } from 'file-saver';

loadFile(fileId: number) {
   try {
       let isFileSaverSupported = !!new Blob;
   } catch (e) { 
       console.log(e);
       return;
   }

   this.repository.loadFile(fileId).subscribe(response => {
       let blob = new Blob([response.data], { type: 'application/pdf' });
       saveAs(blob, `file${fileId}.pdf`);
   });
}