Below is my Typescript code to download file From API
DownloadLM() {
var ID= sessionStorage.getItem("UserID");
return this.http.get(this.baseurl + 'api/DownloadFiles/DownloadLM/' + ID,
{
headers: {
'Content-Type': 'application/json'
},
responseType: 'arraybuffer'
}
)
.subscribe(respData => {
this.downLoad(respData, this.type);
}, error => {
});
}
downLoad(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.');
}
}
This is Fine to download Excel File , but it gives a random name to file which I don't want , I want to set file name of my choice when downloading it ,
Where can I set file name here ? any property of Blob ?
If you want the exact filename of the uploaded file, set a custom header of the filename from backed API stream.
You can use it like this: my Excel API response headers:
content-disposition: inline;filename="salesReport.xls"
content-type: application/octet-stream
date: Wed, 22 Aug 2018 06:47:28 GMT
expires: 0
file-name: salesReport.xls
pragma: no-cache
transfer-encoding: chunked
x-application-context: application:8080
x-content-type-options: nosniff
x-xss-protection: 1; mode=block
Service.ts
excel(data: any) {
return this.httpClient.post(this.config.domain +
`/api/registration/excel/download`,data, {observe: 'response', responseType: 'blob'})
.map((res) => {
let data = {
image: new Blob([res.body], {type: res.headers.get('Content-Type')}),
filename: res.headers.get('File-Name')
}
return data ;
}).catch((err) => {
return Observable.throw(err);
});
}
Component.ts
excelDownload (data) {
this.registration.excel(data).subscribe(
(res) => {
const element = document.createElement('a');
element.href = URL.createObjectURL(res.image);
element.download = res.filename;
document.body.appendChild(element);
element.click();
this.toastr.success("Excel generated successfully");
},
(error) =>{
this.toastr.error('Data Not Found');
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With