Fix browser freezing when downloading large files (#1304)
This commit is contained in:
@@ -19,8 +19,6 @@ import jakarta.validation.constraints.Min;
|
|||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import org.springframework.core.io.ByteArrayResource;
|
import org.springframework.core.io.ByteArrayResource;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.core.io.Resource;
|
||||||
import org.springframework.http.HttpHeaders;
|
|
||||||
import org.springframework.http.MediaType;
|
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.security.access.prepost.PreAuthorize;
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|||||||
+14
-2
@@ -11,8 +11,8 @@ import com.adityachandel.booklore.util.FileUtils;
|
|||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.core.io.InputStreamResource;
|
||||||
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.MediaType;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
@@ -20,6 +20,7 @@ import org.springframework.stereotype.Service;
|
|||||||
import org.springframework.util.FileSystemUtils;
|
import org.springframework.util.FileSystemUtils;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
|
import java.io.FileInputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
@@ -41,11 +42,22 @@ public class BookDownloadService {
|
|||||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||||
|
|
||||||
Path file = Paths.get(FileUtils.getBookFullPath(bookEntity)).toAbsolutePath().normalize();
|
Path file = Paths.get(FileUtils.getBookFullPath(bookEntity)).toAbsolutePath().normalize();
|
||||||
Resource resource = new UrlResource(file.toUri());
|
File bookFile = file.toFile();
|
||||||
|
|
||||||
|
if (!bookFile.exists()) {
|
||||||
|
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId);
|
||||||
|
}
|
||||||
|
|
||||||
|
InputStream inputStream = new FileInputStream(bookFile);
|
||||||
|
InputStreamResource resource = new InputStreamResource(inputStream);
|
||||||
|
|
||||||
return ResponseEntity.ok()
|
return ResponseEntity.ok()
|
||||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||||
|
.contentLength(bookFile.length())
|
||||||
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFileName() + "\"")
|
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFileName() + "\"")
|
||||||
|
.header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate")
|
||||||
|
.header(HttpHeaders.PRAGMA, "no-cache")
|
||||||
|
.header(HttpHeaders.EXPIRES, "0")
|
||||||
.body(resource);
|
.body(resource);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("Failed to download book {}: {}", bookId, e.getMessage(), e);
|
log.error("Failed to download book {}: {}", bookId, e.getMessage(), e);
|
||||||
|
|||||||
@@ -10,5 +10,6 @@
|
|||||||
} @else {
|
} @else {
|
||||||
<p-confirmDialog />
|
<p-confirmDialog />
|
||||||
<p-toast></p-toast>
|
<p-toast></p-toast>
|
||||||
|
<app-download-progress-dialog/>
|
||||||
<router-outlet></router-outlet>
|
<router-outlet></router-outlet>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,13 +14,14 @@ import {BookdropFileNotification, BookdropFileService} from './bookdrop/bookdrop
|
|||||||
import {DuplicateFileNotification} from './shared/websocket/model/duplicate-file-notification.model';
|
import {DuplicateFileNotification} from './shared/websocket/model/duplicate-file-notification.model';
|
||||||
import {DuplicateFileService} from './shared/websocket/duplicate-file.service';
|
import {DuplicateFileService} from './shared/websocket/duplicate-file.service';
|
||||||
import {Subscription} from 'rxjs';
|
import {Subscription} from 'rxjs';
|
||||||
|
import {DownloadProgressDialogComponent} from './shared/components/download-progress-dialog/download-progress-dialog.component';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-root',
|
selector: 'app-root',
|
||||||
templateUrl: './app.component.html',
|
templateUrl: './app.component.html',
|
||||||
styleUrl: './app.component.scss',
|
styleUrl: './app.component.scss',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [ConfirmDialog, Toast, RouterOutlet]
|
imports: [ConfirmDialog, Toast, RouterOutlet, DownloadProgressDialogComponent]
|
||||||
})
|
})
|
||||||
export class AppComponent implements OnInit, OnDestroy {
|
export class AppComponent implements OnInit, OnDestroy {
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {MetadataRefreshRequest} from '../../metadata/model/request/metadata-refr
|
|||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
import {ResetProgressType, ResetProgressTypes} from '../../shared/constants/reset-progress-type';
|
import {ResetProgressType, ResetProgressTypes} from '../../shared/constants/reset-progress-type';
|
||||||
import {AuthService} from '../../core/service/auth.service';
|
import {AuthService} from '../../core/service/auth.service';
|
||||||
|
import {FileDownloadService} from '../../shared/service/file-download.service';
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
@@ -21,6 +22,7 @@ export class BookService {
|
|||||||
private http = inject(HttpClient);
|
private http = inject(HttpClient);
|
||||||
private messageService = inject(MessageService);
|
private messageService = inject(MessageService);
|
||||||
private authService = inject(AuthService);
|
private authService = inject(AuthService);
|
||||||
|
private fileDownloadService = inject(FileDownloadService);
|
||||||
|
|
||||||
private bookStateSubject = new BehaviorSubject<BookState>({
|
private bookStateSubject = new BehaviorSubject<BookState>({
|
||||||
books: null,
|
books: null,
|
||||||
@@ -355,43 +357,12 @@ export class BookService {
|
|||||||
|
|
||||||
downloadFile(bookId: number): void {
|
downloadFile(bookId: number): void {
|
||||||
const downloadUrl = `${this.url}/${bookId}/download`;
|
const downloadUrl = `${this.url}/${bookId}/download`;
|
||||||
this.http.get(downloadUrl, {responseType: 'blob', observe: 'response'})
|
this.fileDownloadService.downloadFile(downloadUrl, `book_${bookId}`);
|
||||||
.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),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
downloadAdditionalFile(bookId: number, fileId: number): void {
|
downloadAdditionalFile(bookId: number, fileId: number): void {
|
||||||
const downloadUrl = `${this.url}/${bookId}/files/${fileId}/download`;
|
const downloadUrl = `${this.url}/${bookId}/files/${fileId}/download`;
|
||||||
this.http.get(downloadUrl, {responseType: 'blob', observe: 'response'})
|
this.fileDownloadService.downloadFile(downloadUrl, `additional_file_${fileId}`);
|
||||||
.subscribe({
|
|
||||||
next: (response) => {
|
|
||||||
const contentDisposition = response.headers.get('Content-Disposition');
|
|
||||||
const filename = contentDisposition
|
|
||||||
? contentDisposition.match(/filename="(.+?)"/)?.[1] || `additional_file_${fileId}`
|
|
||||||
: `additional_file_${fileId}`;
|
|
||||||
this.saveFile(response.body as Blob, filename);
|
|
||||||
},
|
|
||||||
error: (err) => console.error('Error downloading additional 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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
savePdfProgress(bookId: number, page: number, percentage: number): Observable<void> {
|
savePdfProgress(bookId: number, page: number, percentage: number): Observable<void> {
|
||||||
@@ -510,8 +481,8 @@ export class BookService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
getComicInfoMetadata(bookId: number): Observable<BookMetadata> {
|
getComicInfoMetadata(bookId: number): Observable<BookMetadata> {
|
||||||
return this.http.get<BookMetadata>(`${this.url}/${bookId}/cbx/metadata/comicinfo`);
|
return this.http.get<BookMetadata>(`${this.url}/${bookId}/cbx/metadata/comicinfo`);
|
||||||
}
|
}
|
||||||
|
|
||||||
autoRefreshMetadata(metadataRefreshRequest: MetadataRefreshRequest): Observable<any> {
|
autoRefreshMetadata(metadataRefreshRequest: MetadataRefreshRequest): Observable<any> {
|
||||||
|
|||||||
+33
@@ -0,0 +1,33 @@
|
|||||||
|
<p-dialog
|
||||||
|
[visible]="currentProgress.visible"
|
||||||
|
[header]="'Downloading File'"
|
||||||
|
[modal]="true"
|
||||||
|
[closable]="false"
|
||||||
|
[draggable]="false"
|
||||||
|
[resizable]="false"
|
||||||
|
[style]="{width: '450px'}">
|
||||||
|
|
||||||
|
<div class="download-content">
|
||||||
|
<div class="filename">{{ currentProgress.filename }}</div>
|
||||||
|
|
||||||
|
<div class="progress-bar-container">
|
||||||
|
<div class="progress-bar-background">
|
||||||
|
<div class="progress-bar-fill" [style.width.%]="currentProgress.progress"></div>
|
||||||
|
<div class="progress-bar-label">{{ currentProgress.progress }}%</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="download-info">
|
||||||
|
<span>{{ formatBytes(currentProgress.loaded) }} / {{ formatBytes(currentProgress.total) }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ng-template pTemplate="footer">
|
||||||
|
<p-button
|
||||||
|
label="Cancel"
|
||||||
|
icon="pi pi-times"
|
||||||
|
severity="secondary"
|
||||||
|
(onClick)="cancelDownload()">
|
||||||
|
</p-button>
|
||||||
|
</ng-template>
|
||||||
|
</p-dialog>
|
||||||
+53
@@ -0,0 +1,53 @@
|
|||||||
|
.download-content {
|
||||||
|
padding: 1rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filename {
|
||||||
|
font-weight: 600;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.progress-bar-container {
|
||||||
|
margin: 1rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.progress-bar-background {
|
||||||
|
width: 100%;
|
||||||
|
height: 1rem;
|
||||||
|
background-color: var(--p-surface-400);
|
||||||
|
border-radius: var(--border-radius, 4px);
|
||||||
|
overflow: hidden;
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.progress-bar-fill {
|
||||||
|
height: 100%;
|
||||||
|
background: linear-gradient(90deg, var(--p-primary-500), var(--p-primary-800));
|
||||||
|
transition: width 0.3s ease-out;
|
||||||
|
will-change: width;
|
||||||
|
border-radius: var(--border-radius, 6px);
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.progress-bar-label {
|
||||||
|
position: absolute;
|
||||||
|
top: 50%;
|
||||||
|
left: 50%;
|
||||||
|
transform: translate(-50%, -50%);
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
color: var(--p-text-color);
|
||||||
|
z-index: 1;
|
||||||
|
text-shadow: 0 0 2px rgba(255, 255, 255, 0.8);
|
||||||
|
}
|
||||||
|
|
||||||
|
.download-info {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
color: var(--p-text-color);
|
||||||
|
}
|
||||||
+51
@@ -0,0 +1,51 @@
|
|||||||
|
import {Component, inject, ChangeDetectionStrategy, ChangeDetectorRef, OnDestroy} from '@angular/core';
|
||||||
|
import {CommonModule} from '@angular/common';
|
||||||
|
import {DialogModule} from 'primeng/dialog';
|
||||||
|
import {ButtonModule} from 'primeng/button';
|
||||||
|
import {Subscription} from 'rxjs';
|
||||||
|
import {DownloadProgress, DownloadProgressService} from '../../service/download-progress.service';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-download-progress-dialog',
|
||||||
|
standalone: true,
|
||||||
|
imports: [CommonModule, DialogModule, ButtonModule],
|
||||||
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
|
templateUrl: './download-progress-dialog.component.html',
|
||||||
|
styleUrl: './download-progress-dialog.component.scss'
|
||||||
|
})
|
||||||
|
export class DownloadProgressDialogComponent implements OnDestroy {
|
||||||
|
private downloadProgressService = inject(DownloadProgressService);
|
||||||
|
private cdr = inject(ChangeDetectorRef);
|
||||||
|
private subscription: Subscription;
|
||||||
|
|
||||||
|
currentProgress: DownloadProgress = {
|
||||||
|
visible: false,
|
||||||
|
filename: '',
|
||||||
|
progress: 0,
|
||||||
|
loaded: 0,
|
||||||
|
total: 0
|
||||||
|
};
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.subscription = this.downloadProgressService.downloadProgress$.subscribe(progress => {
|
||||||
|
this.currentProgress = progress;
|
||||||
|
this.cdr.markForCheck();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
ngOnDestroy(): void {
|
||||||
|
this.subscription.unsubscribe();
|
||||||
|
}
|
||||||
|
|
||||||
|
cancelDownload(): void {
|
||||||
|
this.downloadProgressService.cancelDownload();
|
||||||
|
}
|
||||||
|
|
||||||
|
formatBytes(bytes: number): string {
|
||||||
|
if (bytes === 0) return '0 Bytes';
|
||||||
|
const k = 1024;
|
||||||
|
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||||
|
return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
import {Injectable} from '@angular/core';
|
||||||
|
import {BehaviorSubject, Subject} from 'rxjs';
|
||||||
|
|
||||||
|
export interface DownloadProgress {
|
||||||
|
visible: boolean;
|
||||||
|
filename: string;
|
||||||
|
progress: number;
|
||||||
|
loaded: number;
|
||||||
|
total: number;
|
||||||
|
cancelSubject?: Subject<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root'
|
||||||
|
})
|
||||||
|
export class DownloadProgressService {
|
||||||
|
private downloadProgressSubject = new BehaviorSubject<DownloadProgress>({
|
||||||
|
visible: false,
|
||||||
|
filename: '',
|
||||||
|
progress: 0,
|
||||||
|
loaded: 0,
|
||||||
|
total: 0
|
||||||
|
});
|
||||||
|
|
||||||
|
private lastUpdateTime = 0;
|
||||||
|
private updateThrottleMs = 100;
|
||||||
|
private pendingUpdate: DownloadProgress | null = null;
|
||||||
|
private throttleTimer: any = null;
|
||||||
|
|
||||||
|
downloadProgress$ = this.downloadProgressSubject.asObservable();
|
||||||
|
|
||||||
|
isDownloadInProgress(): boolean {
|
||||||
|
return this.downloadProgressSubject.value.visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
startDownload(filename: string, cancelSubject: Subject<void>): void {
|
||||||
|
this.lastUpdateTime = 0;
|
||||||
|
this.pendingUpdate = null;
|
||||||
|
if (this.throttleTimer) {
|
||||||
|
clearTimeout(this.throttleTimer);
|
||||||
|
this.throttleTimer = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.downloadProgressSubject.next({
|
||||||
|
visible: true,
|
||||||
|
filename,
|
||||||
|
progress: 0,
|
||||||
|
loaded: 0,
|
||||||
|
total: 0,
|
||||||
|
cancelSubject
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
updateProgress(loaded: number, total: number): void {
|
||||||
|
const current = this.downloadProgressSubject.value;
|
||||||
|
const progress = total > 0 ? Math.min(100, Math.round((loaded / total) * 100)) : 0;
|
||||||
|
const now = Date.now();
|
||||||
|
|
||||||
|
const newProgress: DownloadProgress = {
|
||||||
|
visible: current.visible,
|
||||||
|
filename: current.filename,
|
||||||
|
progress,
|
||||||
|
loaded,
|
||||||
|
total,
|
||||||
|
cancelSubject: current.cancelSubject
|
||||||
|
};
|
||||||
|
|
||||||
|
if (progress === 100) {
|
||||||
|
if (this.throttleTimer) {
|
||||||
|
clearTimeout(this.throttleTimer);
|
||||||
|
this.throttleTimer = null;
|
||||||
|
}
|
||||||
|
this.downloadProgressSubject.next(newProgress);
|
||||||
|
this.lastUpdateTime = now;
|
||||||
|
this.pendingUpdate = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (now - this.lastUpdateTime >= this.updateThrottleMs) {
|
||||||
|
this.downloadProgressSubject.next(newProgress);
|
||||||
|
this.lastUpdateTime = now;
|
||||||
|
this.pendingUpdate = null;
|
||||||
|
|
||||||
|
if (this.throttleTimer) {
|
||||||
|
clearTimeout(this.throttleTimer);
|
||||||
|
this.throttleTimer = null;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.pendingUpdate = newProgress;
|
||||||
|
|
||||||
|
if (!this.throttleTimer) {
|
||||||
|
const remainingTime = this.updateThrottleMs - (now - this.lastUpdateTime);
|
||||||
|
this.throttleTimer = setTimeout(() => {
|
||||||
|
if (this.pendingUpdate) {
|
||||||
|
this.downloadProgressSubject.next(this.pendingUpdate);
|
||||||
|
this.lastUpdateTime = Date.now();
|
||||||
|
this.pendingUpdate = null;
|
||||||
|
}
|
||||||
|
this.throttleTimer = null;
|
||||||
|
}, remainingTime);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
completeDownload(): void {
|
||||||
|
if (this.throttleTimer) {
|
||||||
|
clearTimeout(this.throttleTimer);
|
||||||
|
this.throttleTimer = null;
|
||||||
|
}
|
||||||
|
this.pendingUpdate = null;
|
||||||
|
|
||||||
|
this.downloadProgressSubject.next({
|
||||||
|
visible: false,
|
||||||
|
filename: '',
|
||||||
|
progress: 0,
|
||||||
|
loaded: 0,
|
||||||
|
total: 0
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
cancelDownload(): void {
|
||||||
|
const current = this.downloadProgressSubject.value;
|
||||||
|
current.cancelSubject?.next();
|
||||||
|
current.cancelSubject?.complete();
|
||||||
|
this.completeDownload();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import {Injectable, inject} from '@angular/core';
|
||||||
|
import {HttpClient, HttpEvent, HttpEventType, HttpResponse} from '@angular/common/http';
|
||||||
|
import {MessageService} from 'primeng/api';
|
||||||
|
import {DownloadProgressService} from './download-progress.service';
|
||||||
|
import {Observable, Subject, throwError} from 'rxjs';
|
||||||
|
import {catchError, finalize, takeUntil, tap} from 'rxjs/operators';
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root'
|
||||||
|
})
|
||||||
|
export class FileDownloadService {
|
||||||
|
private http = inject(HttpClient);
|
||||||
|
private downloadProgressService = inject(DownloadProgressService);
|
||||||
|
private messageService = inject(MessageService);
|
||||||
|
|
||||||
|
downloadFile(url: string, defaultFilename: string): void {
|
||||||
|
const cancelSubject = new Subject<void>();
|
||||||
|
|
||||||
|
this.initiateDownload(url)
|
||||||
|
.pipe(
|
||||||
|
takeUntil(cancelSubject),
|
||||||
|
tap(event => this.handleDownloadProgress(event, defaultFilename, cancelSubject)),
|
||||||
|
finalize(() => this.downloadProgressService.completeDownload()),
|
||||||
|
catchError(error => {
|
||||||
|
this.handleDownloadError(error);
|
||||||
|
return throwError(() => error);
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.subscribe();
|
||||||
|
}
|
||||||
|
|
||||||
|
private initiateDownload(url: string): Observable<HttpEvent<Blob>> {
|
||||||
|
return this.http.get(url, {
|
||||||
|
responseType: 'blob',
|
||||||
|
observe: 'events',
|
||||||
|
reportProgress: true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleDownloadProgress(
|
||||||
|
event: HttpEvent<Blob>,
|
||||||
|
defaultFilename: string,
|
||||||
|
cancelSubject: Subject<void>
|
||||||
|
): void {
|
||||||
|
if (event.type === HttpEventType.Response) {
|
||||||
|
this.handleDownloadComplete(event, defaultFilename);
|
||||||
|
} else if (event.type === HttpEventType.DownloadProgress) {
|
||||||
|
this.updateProgress(event, defaultFilename, cancelSubject);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private updateProgress(
|
||||||
|
event: any,
|
||||||
|
defaultFilename: string,
|
||||||
|
cancelSubject: Subject<void>
|
||||||
|
): void {
|
||||||
|
if (event.total) {
|
||||||
|
if (!this.downloadProgressService.isDownloadInProgress()) {
|
||||||
|
this.downloadProgressService.startDownload(defaultFilename, cancelSubject);
|
||||||
|
}
|
||||||
|
this.downloadProgressService.updateProgress(event.loaded, event.total);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleDownloadComplete(response: HttpResponse<Blob>, defaultFilename: string): void {
|
||||||
|
const filename = this.extractFilenameFromResponse(response, defaultFilename);
|
||||||
|
const blob = response.body;
|
||||||
|
|
||||||
|
if (!blob) {
|
||||||
|
throw new Error('No file content received');
|
||||||
|
}
|
||||||
|
|
||||||
|
this.triggerBrowserDownload(blob, filename);
|
||||||
|
this.showSuccessMessage(filename);
|
||||||
|
}
|
||||||
|
|
||||||
|
private extractFilenameFromResponse(response: HttpResponse<Blob>, defaultFilename: string): string {
|
||||||
|
const contentDisposition = response.headers.get('Content-Disposition');
|
||||||
|
return contentDisposition
|
||||||
|
? contentDisposition.match(/filename="(.+?)"/)?.[1] || defaultFilename
|
||||||
|
: defaultFilename;
|
||||||
|
}
|
||||||
|
|
||||||
|
private triggerBrowserDownload(blob: Blob, filename: string): void {
|
||||||
|
const objectUrl = window.URL.createObjectURL(blob);
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = objectUrl;
|
||||||
|
link.download = filename;
|
||||||
|
link.style.display = 'none';
|
||||||
|
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
document.body.removeChild(link);
|
||||||
|
window.URL.revokeObjectURL(objectUrl);
|
||||||
|
}, 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleDownloadError(error: any): void {
|
||||||
|
if (error?.name !== 'AbortError') {
|
||||||
|
this.messageService.add({
|
||||||
|
severity: 'error',
|
||||||
|
summary: 'Download Failed',
|
||||||
|
detail: 'An error occurred while downloading the file. Please try again.',
|
||||||
|
life: 5000
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private showSuccessMessage(filename: string): void {
|
||||||
|
this.messageService.add({
|
||||||
|
severity: 'success',
|
||||||
|
summary: 'Download Complete',
|
||||||
|
detail: `${filename} has been downloaded successfully.`,
|
||||||
|
life: 3000
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user