Download File Excel in Angular 2
download-file.component.ts
import { Component, OnInit } from '@angular/core';
import { ApiService } from 'src/app/shared/services/api.service';
@Component({
selector: 'app-download-file',
templateUrl: './download-file.component.html',
styleUrls: ['./download-file.component.scss'],
})
export class downloadFileComponent implements OnInit {
constructor(
private api: ApiService,
) {}
ngOnInit(): void {}
public onDownload(id: number): void {
const bodyParams = { id: id };
const header = {
observe: 'response',
responseType: 'blob' as 'json',
};
this.api.post('/outputExcel', bodyParams, header).subscribe(
(res: any) => {
/* Get filename */
const disposition = res?.headers.get('Content-Disposition');
const filename = decodeURIComponent(disposition?.split(';')[1]?.split('filename')[1]?.split('=')[1]?.trim()?.slice(1, -1));
/* Get blob */
const blob = new Blob([res.body], {
type:
'application/vnd.openxmlformats officedocument.spreadsheetml.sheet',
});
const url = window.URL.createObjectURL(blob);
// const fileName = `[Report]_${new Date().getTime()}.xlsx`;
/* Download */
this.downloadURI(url, fileName);
},
(err) => {
alert('Download failed');
}
);
}
public downloadURI(uri: string, name?: string): void {
const link = document.createElement('a');
// If you don't know the name or want to use
// the webserver default set name = ''
if (name) {
link.setAttribute('download', name);
}
link.href = uri;
document.body.appendChild(link);
link.click();
link.remove();
}
}
0 nhận xét:
Post a Comment