Implement multi-file uploader
This commit is contained in:
committed by
Aditya Chandel
parent
2ef67f450a
commit
6a6a129dd1
@@ -102,7 +102,7 @@ export class AppTopBarComponent implements OnDestroy {
|
|||||||
closable: true,
|
closable: true,
|
||||||
style: {
|
style: {
|
||||||
position: 'absolute',
|
position: 'absolute',
|
||||||
top: '15%',
|
top: '10%',
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
+89
-39
@@ -1,6 +1,6 @@
|
|||||||
<div
|
<div
|
||||||
*ngIf="(libraryState$ | async)?.libraries as libraries"
|
*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
|
<p-select
|
||||||
[options]="libraries"
|
[options]="libraries"
|
||||||
@@ -17,44 +17,94 @@
|
|||||||
[disabled]="!selectedLibrary"
|
[disabled]="!selectedLibrary"
|
||||||
class="w-full"></p-select>
|
class="w-full"></p-select>
|
||||||
|
|
||||||
<p-fileupload
|
<p-fileupload class="w-full" name="file"
|
||||||
#fu
|
maxFileSize="104857600"
|
||||||
mode="basic"
|
[customUpload]="true"
|
||||||
chooseLabel="Choose"
|
[multiple]="true" accept=".pdf,.epub"
|
||||||
chooseIcon="pi pi-file"
|
(onSelect)="onFilesSelect($event)"
|
||||||
uploadIcon="pi pi-file"
|
(uploadHandler)="uploadFiles($event)"
|
||||||
name="file"
|
[disabled]="!selectedLibrary || !selectedPath">
|
||||||
[url]="getUploadUrl()"
|
<ng-template #header let-files let-chooseCallback="chooseCallback" let-clearCallback="clearCallback" let-uploadCallback="uploadCallback">
|
||||||
accept=".pdf,.epub"
|
<div class="flex flex-wrap items-center justify-center flex-1 gap-4">
|
||||||
maxFileSize="104857600"
|
<div class="flex gap-4">
|
||||||
(onSelect)="onSelect()"
|
<p-button (onClick)="choose($event, chooseCallback)"
|
||||||
(onClear)="onClear($event)"
|
icon="pi pi-images"
|
||||||
(onUpload)="onUpload($event)"
|
[rounded]="true"
|
||||||
(onProgress)="onProgress($event)"
|
[outlined]="true"
|
||||||
(onSend)="onSend($event)"
|
[disabled]="isChooseDisabled()"/>
|
||||||
(onError)="onError($event)"
|
|
||||||
[disabled]="!selectedLibrary || !selectedPath || isUploading"
|
<p-button (onClick)="uploadEvent(uploadCallback)"
|
||||||
class="w-full">
|
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>
|
</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>
|
</div>
|
||||||
|
|||||||
@@ -1,93 +1,165 @@
|
|||||||
import {Component, inject} from '@angular/core';
|
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 {Button} from 'primeng/button';
|
||||||
import {LibraryService} from '../../../book/service/library.service';
|
import {AsyncPipe, NgForOf, NgIf, NgSwitch, NgSwitchCase} from '@angular/common';
|
||||||
import {Observable} from 'rxjs';
|
|
||||||
import {LibraryState} from '../../../book/model/state/library-state.model';
|
|
||||||
import {AsyncPipe, NgIf} from '@angular/common';
|
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
import {Library, LibraryPath} from '../../../book/model/library.model';
|
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
import {DynamicDialogRef} from 'primeng/dynamicdialog';
|
|
||||||
import {Select} from 'primeng/select';
|
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 {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({
|
@Component({
|
||||||
selector: 'app-book-uploader',
|
selector: 'app-book-uploader',
|
||||||
|
standalone: true,
|
||||||
imports: [
|
imports: [
|
||||||
FileUpload,
|
FileUpload,
|
||||||
Button,
|
Button,
|
||||||
AsyncPipe,
|
AsyncPipe,
|
||||||
FormsModule,
|
FormsModule,
|
||||||
NgIf,
|
NgIf,
|
||||||
Select
|
Select,
|
||||||
|
Badge,
|
||||||
|
NgForOf,
|
||||||
|
NgSwitchCase,
|
||||||
|
NgSwitch,
|
||||||
|
Tooltip
|
||||||
],
|
],
|
||||||
templateUrl: './book-uploader.component.html',
|
templateUrl: './book-uploader.component.html',
|
||||||
standalone: true,
|
|
||||||
styleUrl: './book-uploader.component.scss'
|
styleUrl: './book-uploader.component.scss'
|
||||||
})
|
})
|
||||||
export class BookUploaderComponent {
|
export class BookUploaderComponent {
|
||||||
|
files: UploadingFile[] = [];
|
||||||
private uploadUrl = `${API_CONFIG.BASE_URL}/api/v1/files/upload`;
|
isUploading: boolean = false;
|
||||||
|
|
||||||
private libraryService = inject(LibraryService);
|
|
||||||
private messageService = inject(MessageService);
|
|
||||||
private dynamicDialogRef = inject(DynamicDialogRef);
|
|
||||||
|
|
||||||
libraryState$: Observable<LibraryState> = this.libraryService.libraryState$;
|
|
||||||
|
|
||||||
selectedLibrary: Library | null = null;
|
selectedLibrary: Library | null = null;
|
||||||
selectedPath: LibraryPath | null = null;
|
selectedPath: LibraryPath | null = null;
|
||||||
isUploading = false;
|
|
||||||
progressPercent = 0;
|
|
||||||
errorMessage: string | null = null;
|
|
||||||
|
|
||||||
getUploadUrl() {
|
private readonly libraryService = inject(LibraryService);
|
||||||
return `${this.uploadUrl}?libraryId=${this.selectedLibrary?.id}&pathId=${this.selectedPath?.id}`;
|
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() {
|
filesPresent(): boolean {
|
||||||
this.errorMessage = null;
|
return this.files.length > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
onClear($event: Event) {
|
choose(_event: any, chooseCallback: () => void): void {
|
||||||
this.errorMessage = null;
|
chooseCallback();
|
||||||
}
|
}
|
||||||
|
|
||||||
onSend($event: FileSendEvent) {
|
onClear(clearCallback: () => void): void {
|
||||||
this.errorMessage = null;
|
clearCallback();
|
||||||
this.isUploading = true;
|
this.files = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
onProgress($event: FileProgressEvent) {
|
onFilesSelect(event: FileSelectEvent): void {
|
||||||
this.progressPercent = $event.progress;
|
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) {
|
onRemoveTemplatingFile(_event: any, _file: File, removeFileCallback: (event: any, index: number) => void, index: number): void {
|
||||||
this.dynamicDialogRef.close();
|
removeFileCallback(_event, index);
|
||||||
this.messageService.add({severity: 'success', summary: 'Success', detail: 'Book successfully uploaded'});
|
|
||||||
this.isUploading = false;
|
|
||||||
this.progressPercent = 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onError($event: FileUploadErrorEvent) {
|
uploadEvent(uploadCallback: () => void): void {
|
||||||
let error: any = $event.error;
|
uploadCallback();
|
||||||
if (error?.status === 409) {
|
}
|
||||||
this.errorMessage = 'File already exists';
|
|
||||||
|
uploadFiles(event: FileUploadHandlerEvent): void {
|
||||||
|
if (!this.selectedLibrary || !this.selectedPath) {
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
severity: 'error',
|
severity: 'warn',
|
||||||
summary: 'Upload Failed',
|
summary: 'Missing Data',
|
||||||
detail: 'The file already exists.'
|
detail: 'Please select a library and path before uploading.',
|
||||||
|
life: 4000
|
||||||
});
|
});
|
||||||
} else {
|
return;
|
||||||
this.errorMessage = 'Upload failed';
|
}
|
||||||
this.messageService.add({
|
|
||||||
severity: 'error',
|
const libraryId = this.selectedLibrary.id!.toString();
|
||||||
summary: 'Upload Failed',
|
const pathId = this.selectedPath.id!.toString();
|
||||||
detail: 'There was an error uploading the file.'
|
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';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user