Implement multi-file uploader

This commit is contained in:
adityachandelgit
2025-04-14 20:24:31 -06:00
committed by Aditya Chandel
parent 2ef67f450a
commit 6a6a129dd1
3 changed files with 214 additions and 92 deletions
@@ -102,7 +102,7 @@ export class AppTopBarComponent implements OnDestroy {
closable: true,
style: {
position: 'absolute',
top: '15%',
top: '10%',
}
});
}
@@ -1,6 +1,6 @@
<div
*ngIf="(libraryState$ | async)?.libraries as libraries"
class="flex flex-col gap-10 p-4 items-center justify-center min-w-[400px] max-w-[600px] w-full">
class="flex flex-col gap-10 p-4 items-center justify-center min-w-[500px] max-w-[700px] w-full">
<p-select
[options]="libraries"
@@ -17,44 +17,94 @@
[disabled]="!selectedLibrary"
class="w-full"></p-select>
<p-fileupload
#fu
mode="basic"
chooseLabel="Choose"
chooseIcon="pi pi-file"
uploadIcon="pi pi-file"
name="file"
[url]="getUploadUrl()"
accept=".pdf,.epub"
maxFileSize="104857600"
(onSelect)="onSelect()"
(onClear)="onClear($event)"
(onUpload)="onUpload($event)"
(onProgress)="onProgress($event)"
(onSend)="onSend($event)"
(onError)="onError($event)"
[disabled]="!selectedLibrary || !selectedPath || isUploading"
class="w-full">
<p-fileupload class="w-full" name="file"
maxFileSize="104857600"
[customUpload]="true"
[multiple]="true" accept=".pdf,.epub"
(onSelect)="onFilesSelect($event)"
(uploadHandler)="uploadFiles($event)"
[disabled]="!selectedLibrary || !selectedPath">
<ng-template #header let-files let-chooseCallback="chooseCallback" let-clearCallback="clearCallback" let-uploadCallback="uploadCallback">
<div class="flex flex-wrap items-center justify-center flex-1 gap-4">
<div class="flex gap-4">
<p-button (onClick)="choose($event, chooseCallback)"
icon="pi pi-images"
[rounded]="true"
[outlined]="true"
[disabled]="isChooseDisabled()"/>
<p-button (onClick)="uploadEvent(uploadCallback)"
icon="pi pi-cloud-upload"
[rounded]="true"
[outlined]="true"
severity="success"
[disabled]="isUploadDisabled()"/>
<p-button (onClick)="onClear(clearCallback)"
icon="pi pi-times"
[rounded]="true"
[outlined]="true"
severity="danger"
[disabled]="!filesPresent() || isUploading"/>
</div>
</div>
</ng-template>
<ng-template #content let-files let-removeFileCallback="removeFileCallback">
<div class="flex flex-col gap-8 px-4">
<div *ngIf="files?.length > 0">
<div class="max-h-96 overflow-y-auto pr-2">
<div class="flex flex-wrap">
<div *ngFor="let uploadFile of this.files; let i = index" class="flex justify-between items-center w-full gap-4">
<div class="flex items-center gap-4 overflow-hidden flex-1">
<p-badge [value]="uploadFile.status" [severity]="getBadgeSeverity(uploadFile.status)" class="shrink-0"/>
<span class="font-semibold text-ellipsis whitespace-nowrap overflow-hidden flex-1">
{{ uploadFile.file.name }}
</span>
<div class="shrink-0">{{ formatSize(uploadFile.file.size) }}</div>
</div>
<ng-container [ngSwitch]="uploadFile.status">
<p-button *ngSwitchCase="'Pending'"
icon="pi pi-times"
(click)="onRemoveTemplatingFile($event, uploadFile.file, removeFileCallback, i)"
severity="danger"
[text]="true"/>
<p-button *ngSwitchCase="'Uploading'"
icon="pi pi-spin pi-spinner"
severity="info"
[text]="true"
[disabled]="true"/>
<p-button *ngSwitchCase="'Uploaded'"
icon="pi pi-check"
severity="success"
[text]="true"
pTooltip="File uploaded"
tooltipPosition="top"
[disabled]="true"/>
<p-button *ngSwitchCase="'Failed'"
icon="pi pi-exclamation-triangle"
severity="danger"
[text]="true"
[disabled]="true"
pTooltip="{{ uploadFile.errorMessage || 'Upload failed' }}"
tooltipPosition="top"/>
</ng-container>
</div>
</div>
</div>
</div>
</div>
</ng-template>
<ng-template #file></ng-template>
<ng-template #empty>
<div class="flex items-center justify-center flex-col text-center">
<i class="pi pi-cloud-upload !border-2 !rounded-full !p-8 !text-4xl !text-muted-color"></i>
<p class="mt-6 mb-2">Drag and drop files here to upload.</p>
<p class="mt-2 mb-2">Only <strong>.epub</strong> and <strong>.pdf</strong> files are supported (max size: 100 MB per file).</p>
</div>
</ng-template>
</p-fileupload>
<div class="flex flex-row items-center justify-between w-full">
<div class="flex flex-row items-center gap-4">
<p-button
icon="pi pi-upload"
label="Upload"
(onClick)="fu.upload()"
severity="info"
[disabled]="!fu.files.length || isUploading"/>
<p *ngIf="isUploading" class="text-base">Progress: {{ progressPercent }}%</p>
<p *ngIf="errorMessage" class="text-base text-red-600">{{ errorMessage }}</p>
</div>
<p-button
icon="pi pi-times"
label="Clear"
(click)="fu.clear()"
severity="warn"
[hidden]="!fu.files.length || isUploading"/>
</div>
</div>
@@ -1,93 +1,165 @@
import {Component, inject} from '@angular/core';
import {FileProgressEvent, FileSendEvent, FileUpload, FileUploadErrorEvent, FileUploadEvent} from 'primeng/fileupload';
import {FileSelectEvent, FileUpload, FileUploadHandlerEvent} from 'primeng/fileupload';
import {Button} from 'primeng/button';
import {LibraryService} from '../../../book/service/library.service';
import {Observable} from 'rxjs';
import {LibraryState} from '../../../book/model/state/library-state.model';
import {AsyncPipe, NgIf} from '@angular/common';
import {AsyncPipe, NgForOf, NgIf, NgSwitch, NgSwitchCase} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {Library, LibraryPath} from '../../../book/model/library.model';
import {MessageService} from 'primeng/api';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {Select} from 'primeng/select';
import {Badge} from 'primeng/badge';
import {LibraryService} from '../../../book/service/library.service';
import {Library, LibraryPath} from '../../../book/model/library.model';
import {LibraryState} from '../../../book/model/state/library-state.model';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../../config/api-config';
import {Book} from '../../../book/model/book.model';
import {HttpClient} from '@angular/common/http';
import {Tooltip} from 'primeng/tooltip';
interface UploadingFile {
file: File;
status: 'Pending' | 'Uploading' | 'Uploaded' | 'Failed';
errorMessage?: string;
}
@Component({
selector: 'app-book-uploader',
standalone: true,
imports: [
FileUpload,
Button,
AsyncPipe,
FormsModule,
NgIf,
Select
Select,
Badge,
NgForOf,
NgSwitchCase,
NgSwitch,
Tooltip
],
templateUrl: './book-uploader.component.html',
standalone: true,
styleUrl: './book-uploader.component.scss'
})
export class BookUploaderComponent {
private uploadUrl = `${API_CONFIG.BASE_URL}/api/v1/files/upload`;
private libraryService = inject(LibraryService);
private messageService = inject(MessageService);
private dynamicDialogRef = inject(DynamicDialogRef);
libraryState$: Observable<LibraryState> = this.libraryService.libraryState$;
files: UploadingFile[] = [];
isUploading: boolean = false;
selectedLibrary: Library | null = null;
selectedPath: LibraryPath | null = null;
isUploading = false;
progressPercent = 0;
errorMessage: string | null = null;
getUploadUrl() {
return `${this.uploadUrl}?libraryId=${this.selectedLibrary?.id}&pathId=${this.selectedPath?.id}`;
private readonly libraryService = inject(LibraryService);
private readonly messageService = inject(MessageService);
private readonly http = inject(HttpClient);
readonly libraryState$: Observable<LibraryState> = this.libraryService.libraryState$;
hasPendingFiles(): boolean {
return this.files.some(f => f.status === 'Pending');
}
onSelect() {
this.errorMessage = null;
filesPresent(): boolean {
return this.files.length > 0;
}
onClear($event: Event) {
this.errorMessage = null;
choose(_event: any, chooseCallback: () => void): void {
chooseCallback();
}
onSend($event: FileSendEvent) {
this.errorMessage = null;
this.isUploading = true;
onClear(clearCallback: () => void): void {
clearCallback();
this.files = [];
}
onProgress($event: FileProgressEvent) {
this.progressPercent = $event.progress;
onFilesSelect(event: FileSelectEvent): void {
const newFiles = event.currentFiles;
for (const file of newFiles) {
const exists = this.files.some(f => f.file.name === file.name && f.file.size === file.size);
if (!exists) {
this.files.unshift({file, status: 'Pending'});
}
}
}
onUpload($event: FileUploadEvent) {
this.dynamicDialogRef.close();
this.messageService.add({severity: 'success', summary: 'Success', detail: 'Book successfully uploaded'});
this.isUploading = false;
this.progressPercent = 0;
onRemoveTemplatingFile(_event: any, _file: File, removeFileCallback: (event: any, index: number) => void, index: number): void {
removeFileCallback(_event, index);
}
onError($event: FileUploadErrorEvent) {
let error: any = $event.error;
if (error?.status === 409) {
this.errorMessage = 'File already exists';
uploadEvent(uploadCallback: () => void): void {
uploadCallback();
}
uploadFiles(event: FileUploadHandlerEvent): void {
if (!this.selectedLibrary || !this.selectedPath) {
this.messageService.add({
severity: 'error',
summary: 'Upload Failed',
detail: 'The file already exists.'
severity: 'warn',
summary: 'Missing Data',
detail: 'Please select a library and path before uploading.',
life: 4000
});
} else {
this.errorMessage = 'Upload failed';
this.messageService.add({
severity: 'error',
summary: 'Upload Failed',
detail: 'There was an error uploading the file.'
return;
}
const libraryId = this.selectedLibrary.id!.toString();
const pathId = this.selectedPath.id!.toString();
const filesToUpload = this.files.filter(f => f.status === 'Pending');
if (filesToUpload.length === 0) return;
this.isUploading = true;
let pending = filesToUpload.length;
for (const uploadFile of filesToUpload) {
uploadFile.status = 'Uploading';
const formData = new FormData();
formData.append('file', uploadFile.file);
formData.append('libraryId', libraryId);
formData.append('pathId', pathId);
this.http.post<Book>(`${API_CONFIG.BASE_URL}/api/v1/files/upload`, formData).subscribe({
next: () => {
uploadFile.status = 'Uploaded';
if (--pending === 0) this.isUploading = false;
},
error: (err) => {
uploadFile.status = 'Failed';
uploadFile.errorMessage = err?.error?.message || 'Upload failed due to unknown error.';
console.error('Upload failed for', uploadFile.file.name, err);
if (--pending === 0) {
this.isUploading = false;
}
}
});
}
this.isUploading = false;
this.progressPercent = 0;
}
isChooseDisabled(): boolean {
return !this.selectedLibrary || !this.selectedPath || this.isUploading;
}
isUploadDisabled(): boolean {
return this.isChooseDisabled() || !this.filesPresent() || !this.hasPendingFiles;
}
formatSize(bytes: number): string {
const k = 1024;
const dm = 2;
if (bytes < k) return `${bytes} B`;
if (bytes < k * k) return `${(bytes / k).toFixed(dm)} KB`;
return `${(bytes / (k * k)).toFixed(dm)} MB`;
}
getBadgeSeverity(status: UploadingFile['status']): 'info' | 'warn' | 'success' | 'danger' {
switch (status) {
case 'Pending':
return 'warn';
case 'Uploading':
return 'info';
case 'Uploaded':
return 'success';
case 'Failed':
return 'danger';
default:
return 'info';
}
}
}