If you're looking to download a file, follow these three steps:
1- Send the appropriate request from the Angular side
download(): Observable<HttpResponse<Blob>> {
return this.http.get<HttpResponse<Blob>>(someURL, {
observe: 'response',
responseType: 'blob'
}); as any }
2- In your backend, make sure to set the necessary headers in the response. The following code snippet is for .NET Framework 4.7 and will return CSV file contents:
var contents = new byte[0]; // Insert your file contents here
var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new
ByteArrayContent(contents)};
response.Content.Headers.ContentDisposition = new
ContentDispositionHeaderValue("attachment")
{
FileName = file.Name
}
response.Content.Headers.Add("Access-Control-Expose-Headers", "Content-
Disposition");
response.Content.Headers.ContentType = new MediaTypeHeaderValue ("text/csv");
return response;
3- Finally, subscribe to the http request on the Angular side:
const result
= this.service.download()
.subscribe(res=> {
let contentDisposition = res.headers.get('content-disposition');
let filename = contentDisposition.split(';')[1].split('filename')
[1].split('=')[1].trim();
let blob = res.body;
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
document.body.appendChild(link);
link.click();
window.URL.revokeObjectURL(url);
link.parentNode.removeChild(link);
});