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
@@ -9,6 +9,7 @@ import {BookService} from '../../../service/book.service';
import {CheckboxModule} from 'primeng/checkbox';
import {FormsModule} from '@angular/forms';
import {MetadataDialogService} from '../../../../metadata/service/metadata-dialog.service';
import {FileService} from '../../../service/file.service';
@Component({
@@ -26,6 +27,7 @@ export class BookCardComponent implements OnInit {
items: MenuItem[] | undefined;
isHovered: boolean = false;
private fileService = inject(FileService);
private bookService = inject(BookService);
private dialogService = inject(DialogService);
private metadataDialogService = inject(MetadataDialogService);
@@ -66,6 +68,13 @@ export class BookCardComponent implements OnInit {
icon: 'pi pi-info-circle',
command: () => this.metadataDialogService.openBookDetailsDialog(this.book.id),
},
{
label: 'Download',
icon: 'pi pi-download',
command: () => {
this.fileService.downloadFile(this.book.id)
},
},
],
},
];
@@ -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);
}
}