Implement file downloading functionality
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user