ngOnInit() { // Get the file this.http.get('/api/file') .subscribe( response => { // Get the file data this.file = response.data; }, error => { // Handle the error console.log(error); } ); }
downloadFile() { // Create a blob from the file data const blob = newBlob([this.file], { type: 'application/pdf' });
// Create an anchor element with the download attribute const anchor = document.createElement('a'); anchor.href = window.URL.createObjectURL(blob); anchor.download = 'my-file.pdf';
// Append the anchor element to the document body document.body.appendChild(anchor);
// Click the anchor element to download the file anchor.click(); }
}
โค้ด HTML
1 2
<h1>{{ title }}</h1> <button (click)="downloadFile()">Download File</button>