Implement file downloading functionality

This commit is contained in:
aditya.chandel
2025-01-16 14:27:14 -07:00
parent 3ced7472e9
commit c7069132b6
9 changed files with 85 additions and 2 deletions
@@ -0,0 +1,36 @@
import {Injectable, inject} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
@Injectable({
providedIn: 'root',
})
export class FileService {
private readonly url = 'http://localhost:8080/v1/book';
private readonly http = inject(HttpClient);
downloadFile(bookId: number): void {
const downloadUrl = `${this.url}/${bookId}/download`;
this.http.get(downloadUrl, {responseType: 'blob', observe: 'response'})
.subscribe({
next: (response) => {
const contentDisposition = response.headers.get('Content-Disposition');
const filename = contentDisposition
? contentDisposition.match(/filename="(.+?)"/)?.[1] || `book_${bookId}.pdf`
: `book_${bookId}.pdf`;
this.saveFile(response.body as Blob, filename);
},
error: (err) => console.error('Error downloading file:', err),
});
}
private saveFile(blob: Blob, filename: string): void {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}
}