Reputation: 2016
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:
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! :)
Upvotes: 4
Views: 14001
Reputation: 153
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");
Upvotes: 0
Reputation: 1041
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();
});
Upvotes: 2
Reputation: 2478
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);
}
Upvotes: 1