3

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

Shaun Chua
  • 705
  • 3
  • 13
  • 32

1 Answers1

6

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`);
});
Dmitriy Snitko
  • 931
  • 5
  • 14