Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - How to download file from Web API on subscribe()

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! :)

like image 881
Iñigo Avatar asked Oct 26 '25 13:10

Iñigo


2 Answers

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();
}); 
like image 182
Efraim Newman Avatar answered Oct 28 '25 04:10

Efraim Newman


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);
}
like image 30
anthony willis muñoz Avatar answered Oct 28 '25 04:10

anthony willis muñoz