Implement file downloading functionality
This commit is contained in:
@@ -32,6 +32,7 @@ dependencies {
|
|||||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||||
implementation 'org.springframework.boot:spring-boot-starter-websocket'
|
implementation 'org.springframework.boot:spring-boot-starter-websocket'
|
||||||
implementation 'org.springframework.boot:spring-boot-starter-quartz'
|
implementation 'org.springframework.boot:spring-boot-starter-quartz'
|
||||||
|
implementation 'org.springframework.boot:spring-boot-starter-actuator'
|
||||||
|
|
||||||
// Lombok
|
// Lombok
|
||||||
compileOnly 'org.projectlombok:lombok'
|
compileOnly 'org.projectlombok:lombok'
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ public class WebConfig implements WebMvcConfigurer {
|
|||||||
registry.addMapping("/**")
|
registry.addMapping("/**")
|
||||||
.allowedOrigins("*")
|
.allowedOrigins("*")
|
||||||
.allowedMethods("*")
|
.allowedMethods("*")
|
||||||
|
.exposedHeaders("Content-Disposition")
|
||||||
.allowedHeaders("*");
|
.allowedHeaders("*");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -73,4 +73,9 @@ public class BookController {
|
|||||||
booksService.updateReadProgress(request);
|
booksService.updateReadProgress(request);
|
||||||
return ResponseEntity.noContent().build();
|
return ResponseEntity.noContent().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{bookId}/download")
|
||||||
|
public ResponseEntity<Resource> downloadFile(@PathVariable("bookId") Long bookId) {
|
||||||
|
return booksService.prepareFileForDownload(bookId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -22,7 +22,8 @@ public enum ApiError {
|
|||||||
SCHEDULE_REFRESH_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to schedule metadata refresh job. Error: %s"),
|
SCHEDULE_REFRESH_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to schedule metadata refresh job. Error: %s"),
|
||||||
ANOTHER_METADATA_JOB_RUNNING(HttpStatus.CONFLICT, "A metadata refresh job is currently running. Please wait for it to complete before initiating a new one."),
|
ANOTHER_METADATA_JOB_RUNNING(HttpStatus.CONFLICT, "A metadata refresh job is currently running. Please wait for it to complete before initiating a new one."),
|
||||||
METADATA_SOURCE_NOT_IMPLEMENT_OR_DOES_NOT_EXIST(HttpStatus.BAD_REQUEST, "Metadata source not implement or does not exist"),
|
METADATA_SOURCE_NOT_IMPLEMENT_OR_DOES_NOT_EXIST(HttpStatus.BAD_REQUEST, "Metadata source not implement or does not exist"),
|
||||||
INVALID_REFRESH_TYPE(HttpStatus.BAD_REQUEST, "The refresh type is invalid"),;
|
FAILED_TO_DOWNLOAD_FILE(HttpStatus.INTERNAL_SERVER_ERROR, "Error while downloading file, bookId: %s"),
|
||||||
|
INVALID_REFRESH_TYPE(HttpStatus.BAD_REQUEST, "The refresh type is invalid");
|
||||||
|
|
||||||
private final HttpStatus status;
|
private final HttpStatus status;
|
||||||
private final String message;
|
private final String message;
|
||||||
|
|||||||
@@ -20,14 +20,19 @@ import jakarta.validation.Valid;
|
|||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.core.io.Resource;
|
||||||
|
import org.springframework.core.io.UrlResource;
|
||||||
import org.springframework.http.HttpHeaders;
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.net.MalformedURLException;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
@@ -145,4 +150,23 @@ public class BooksService {
|
|||||||
}
|
}
|
||||||
bookRepository.save(book);
|
bookRepository.save(book);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public ResponseEntity<Resource> prepareFileForDownload(Long bookId) {
|
||||||
|
try {
|
||||||
|
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||||
|
String filePath = bookEntity.getPath();
|
||||||
|
Path file = Paths.get(filePath).toAbsolutePath().normalize();
|
||||||
|
Resource resource = new UrlResource(file.toUri());
|
||||||
|
String contentType = Files.probeContentType(file);
|
||||||
|
if (contentType == null) {
|
||||||
|
contentType = "application/octet-stream";
|
||||||
|
}
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.contentType(MediaType.parseMediaType(contentType))
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFileName() + "\"")
|
||||||
|
.body(resource);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -9,6 +9,7 @@ import {BookService} from '../../../service/book.service';
|
|||||||
import {CheckboxModule} from 'primeng/checkbox';
|
import {CheckboxModule} from 'primeng/checkbox';
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
import {MetadataDialogService} from '../../../../metadata/service/metadata-dialog.service';
|
import {MetadataDialogService} from '../../../../metadata/service/metadata-dialog.service';
|
||||||
|
import {FileService} from '../../../service/file.service';
|
||||||
|
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
@@ -26,6 +27,7 @@ export class BookCardComponent implements OnInit {
|
|||||||
items: MenuItem[] | undefined;
|
items: MenuItem[] | undefined;
|
||||||
isHovered: boolean = false;
|
isHovered: boolean = false;
|
||||||
|
|
||||||
|
private fileService = inject(FileService);
|
||||||
private bookService = inject(BookService);
|
private bookService = inject(BookService);
|
||||||
private dialogService = inject(DialogService);
|
private dialogService = inject(DialogService);
|
||||||
private metadataDialogService = inject(MetadataDialogService);
|
private metadataDialogService = inject(MetadataDialogService);
|
||||||
@@ -66,6 +68,13 @@ export class BookCardComponent implements OnInit {
|
|||||||
icon: 'pi pi-info-circle',
|
icon: 'pi pi-info-circle',
|
||||||
command: () => this.metadataDialogService.openBookDetailsDialog(this.book.id),
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -15,7 +15,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="flex gap-4 pr-4">
|
<div class="flex gap-4 pr-4">
|
||||||
<p-button [rounded]="true" [raised]="true" severity="info" (onClick)="readBook(metadata.bookId)" icon="pi pi-eye"></p-button>
|
<p-button [rounded]="true" [raised]="true" severity="info" (onClick)="readBook(metadata.bookId)" icon="pi pi-eye"></p-button>
|
||||||
<p-button [rounded]="true" [raised]="true" severity="info" icon="pi pi-download"></p-button>
|
<p-button [rounded]="true" [raised]="true" severity="info" icon="pi pi-download" (onClick)="download(metadata.bookId)"></p-button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
+6
@@ -9,6 +9,7 @@ import {FormsModule} from '@angular/forms';
|
|||||||
import {Tag} from 'primeng/tag';
|
import {Tag} from 'primeng/tag';
|
||||||
import {Editor} from 'primeng/editor';
|
import {Editor} from 'primeng/editor';
|
||||||
import {Author, Book} from '../../../book/model/book.model';
|
import {Author, Book} from '../../../book/model/book.model';
|
||||||
|
import {FileService} from '../../../book/service/file.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-metadata-viewer',
|
selector: 'app-metadata-viewer',
|
||||||
@@ -20,6 +21,7 @@ import {Author, Book} from '../../../book/model/book.model';
|
|||||||
export class MetadataViewerComponent {
|
export class MetadataViewerComponent {
|
||||||
|
|
||||||
private bookService = inject(BookService);
|
private bookService = inject(BookService);
|
||||||
|
private fileService = inject(FileService);
|
||||||
private metadataCenterService = inject(BookMetadataCenterService);
|
private metadataCenterService = inject(BookMetadataCenterService);
|
||||||
|
|
||||||
metadata$: Observable<Book['metadata'] | null> = this.metadataCenterService.bookMetadata$;
|
metadata$: Observable<Book['metadata'] | null> = this.metadataCenterService.bookMetadata$;
|
||||||
@@ -39,4 +41,8 @@ export class MetadataViewerComponent {
|
|||||||
getAuthorNames(authors: Author[]): string {
|
getAuthorNames(authors: Author[]): string {
|
||||||
return authors.map(author => author.name).join(', ');
|
return authors.map(author => author.name).join(', ');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
download(bookId: number) {
|
||||||
|
this.fileService.downloadFile(bookId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user