Angular 6: Download file after getting File object from backend server

喜你入骨 提交于 2021-01-03 16:11:52

问题


I have a File object type of structure {type: "Buffer", data: Array(702549)}, what do I need to do in angular 6 in order to download this file in browser?

I get my response from this function:

  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 is in the format {type: "Buffer", data: Array(702549)}


回答1:


You can use file-saver to do this: https://www.npmjs.com/package/file-saver

File download code:

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

UPDATE: I'v created a test project according to load conditions:

http.get('http://localhost:4200/assets/image.png', {responseType: 'blob'}).subscribe(response => {
  try {
      let isFileSaverSupported = !!new Blob;
  } catch (e) { 
      console.log(e);
      return;
  }
  let blob = new Blob([response], { type: 'image/png' });
  saveAs(blob, `file.png`);
});


来源:https://stackoverflow.com/questions/52278535/angular-6-download-file-after-getting-file-object-from-backend-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!