4

In Angular I'm trying to download an excel file from my Web API Server

If I call my API from an <a> component just like this:

<a href="http://localhost:55820/api/download">Download</a>

The file downloads fine and without handling the response I get the desired behaviour:

Success download

How can I get the same result making the request from my Angular DownloadService and handling the result on .subscribe()?

this.downloadService.download()
      .subscribe(file => {/*What to put here for file downloading as above*/});

Note that the server creates the response like this:

byte[] b = File.ReadAllBytes(HttpRuntime.AppDomainAppPath + "/files/" + "file.xlsx");
var dataStream = new MemoryStream(b);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(dataStream);
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "File";
response.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping("file.xlsx"));
return response;

Thanks in advance! :)

Iñigo
  • 1,877
  • 7
  • 25
  • 55

3 Answers3

2

try this work around:

.subscribe(file => 
{  
   const a = document.createElement('a');
   a.setAttribute('type', 'hidden');  
   a.href = URL.createObjectURL(file.data);  
   a.download = fileName + '.xlsx';  
   a.click(); 
   a.remove();
}); 
anthony willis muñoz
  • 2,346
  • 3
  • 16
  • 33
Efraim Newman
  • 927
  • 6
  • 21
1

The comment above should work, but here is another way

.subscribe(file) {
  const blob = new Blob([file], { type: 'text/csv' }); // you can change the type
  const url= window.URL.createObjectURL(blob);
  window.open(url);
}
anthony willis muñoz
  • 2,346
  • 3
  • 16
  • 33
  • That works fine, but the name of the resulting file cannot be changed. I combined it with [this solution](https://stackoverflow.com/questions/43235129/typescript-blob-filename-without-link/43235224) and it works perfectly. – Iñigo Aug 06 '19 at 08:12
0

You can add js-file-download library which supports all browsers

npm install js-file-download --save

you can use window.URL.createObjectURL(blob); but IE does not support it...

here is my code for downloading Excel files from the Backend

import axios from 'axios';
import * as FileSaver from 'file-saver';

const result: any = await axios.create().post("http://localhost:8080/file",
{
   responseType: "arraybuffer",
});

let blob = new Blob([result.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
FileSaver.saveAs(blob, "export.xlsx");