Reputation: 1583
I am returning a file from web API
[HttpGet("[action]")]
public FileResult DownloadExcel()
{
return File($"~/files/Input.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Input.xlsx");
}
Which is working perfectly
Now I want to use it in angular on button click
So I found some code on internet
downloadFile() {
return this.http.get(this.baseUrl + 'api/Common/DownloadExcel/', { responseType: 'blob' })
.map(res => {
return {
filename: 'filename.xlsx',
data: res.blob()
};
}).subscribe(res => {
console.log('start download:',res);
var url = window.URL.createObjectURL(res.data);
var a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.href = url;
a.download = res.filename;
a.click();
window.URL.revokeObjectURL(url);
a.remove(); // remove the element
}, error => {
console.log('download error:', JSON.stringify(error));
}, () => {
console.log('Completed file download.')
});
}
But is give error
Property blob does not exist on type 'Blob'
In below Line
data: res.blob()
I have imported
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map'
What I am missing here ? and is this code right ?
Upvotes: 1
Views: 4947
Reputation: 7231
Try something like this:
service call:
getUploadedFile(url:string){
let headers = new HttpHeaders().append("Authorization", "Bearer " + token)
return this.httpClient.get(url, {responseType: 'arraybuffer',headers:headers});
}
this.type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
In component:
/**
* Method is used to view or download the file
*/
getFile() {
this.uploadFileService.getUploadedFile(this.url).subscribe(respData => {
this.downLoadFile(respData, this.type);
}, error => {
});
}
/**
* Method is use to download file from server.
* @param data - Array Buffer data
* @param type - type of the document.
*/
downLoadFile(data: any, type: string) {
var blob = new Blob([data], { type: type.toString() });
var url = window.URL.createObjectURL(blob);
var pwa = window.open(url);
if (!pwa || pwa.closed || typeof pwa.closed == 'undefined') {
alert('Please disable your Pop-up blocker and try again.');
}
}
Upvotes: 4