file upload component added (version 1)

This commit is contained in:
2026-07-09 11:37:12 +02:00
parent b12e254cae
commit 233a2d2fca
3 changed files with 519 additions and 0 deletions
@@ -0,0 +1,88 @@
<div class="file-upload-container">
<!-- Drop Zone -->
<div
#dropZone
class="drop-zone"
[class.drag-over]="isDragging"
(click)="fileInput.click()">
<mat-icon class="upload-icon">attach_file</mat-icon>
<p class="drop-text">Drag & drop files here or click to browse</p>
<small class="file-info">
Supported: {{ requiredFileType }} (Max: {{ maxFileSize / 1024 / 1024 }}MB,
{{ maxFiles }} files)
</small>
</div>
<!-- Hidden File Input -->
<input
#fileInput
type="file"
[accept]="
typeof requiredFileType === 'string'
? requiredFileType
: requiredFileType.join(',')
"
multiple
(change)="onFileChange($event)"
style="display: none" />
<!-- File List -->
@if (files.length > 0) {
<div class="file-list">
@for (file of files; track file.id) {
<mat-card class="file-card">
<div class="file-header">
<div class="file-preview">
@if (file.file.type.startsWith('image/')) {
<img [src]="file.previewUrl" alt="Preview" />
} @else {
<mat-icon class="file-icon">{{
getIcon(file.file.type)
}}</mat-icon>
}
</div>
<div class="file-info">
<div class="file-name">{{ file.file.name }}</div>
<div class="file-size">
{{ (file.file.size / 1024 / 1024).toFixed(2) }} MB
</div>
</div>
</div>
<!-- Progress Bar -->
@if (file.progress > 0) {
<div class="progress-container">
<mat-progress-bar
mode="determinate"
[value]="file.progress"
class="progress-bar"></mat-progress-bar>
<span class="progress-text">{{ file.progress }}%</span>
</div>
}
<!-- Actions -->
<div class="file-actions">
<button
mat-icon-button
(click)="downloadFile(file.id)"
matTooltip="Download">
<mat-icon>download</mat-icon>
</button>
<button
mat-icon-button
(click)="cancelUpload(file.id)"
matTooltip="Cancel">
<mat-icon>cancel</mat-icon>
</button>
<button
mat-icon-button
(click)="removeFile(file.id)"
matTooltip="Remove">
<mat-icon>delete</mat-icon>
</button>
</div>
</mat-card>
}
</div>
}
</div>
@@ -0,0 +1,145 @@
.file-upload-container {
width: 100%;
max-width: 600px;
margin: 0 auto;
}
.drop-zone {
border: 2px dashed #ccc;
border-radius: 12px;
padding: 40px 20px;
text-align: center;
cursor: pointer;
transition: all 0.3s ease;
background-color: #f9f9f9;
.upload-icon {
font-size: 48px;
color: #1976d2;
margin-bottom: 12px;
}
.drop-text {
font-size: 16px;
color: #555;
margin-bottom: 8px;
}
.file-info {
font-size: 12px;
color: #888;
}
&.drag-over {
border-color: #1976d2;
background-color: #e3f2fd;
}
}
.file-list {
margin-top: 16px;
}
.file-card {
margin-bottom: 12px;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
.file-header {
display: flex;
align-items: center;
gap: 12px;
padding: 12px;
background-color: #f5f5f5;
}
.file-preview {
width: 50px;
height: 50px;
border-radius: 8px;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
background-color: #ddd;
img {
width: 100%;
height: 100%;
object-fit: cover;
}
.file-icon {
font-size: 32px;
color: #666;
}
mat-icon {
font-size: 32px;
color: #666;
}
}
.file-info {
flex: 1;
font-size: 14px;
.file-name {
font-weight: 500;
color: #333;
}
.file-size {
font-size: 12px;
color: #888;
}
}
.progress-container {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
background-color: #e8f5e9;
.progress-bar {
flex: 1;
}
.progress-text {
font-size: 12px;
color: #2e7d32;
}
}
.file-actions {
display: flex;
gap: 4px;
padding: 8px 12px;
background-color: #f0f0f0;
button {
padding: 4px;
}
}
}
/* Responsive */
@media (max-width: 600px) {
.drop-zone {
padding: 30px 16px;
}
.file-card {
.file-header {
flex-direction: column;
text-align: center;
}
.file-preview {
width: 60px;
height: 60px;
}
}
}
@@ -0,0 +1,286 @@
import {
Component,
Input,
Output,
EventEmitter,
ViewChild,
ElementRef,
OnDestroy,
OnInit,
} from '@angular/core';
import { HttpClient, HttpEventType } from '@angular/common/http';
import { Subscription } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { MatCardModule } from '@angular/material/card';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatIconModule } from '@angular/material/icon';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatChipsModule } from '@angular/material/chips';
import { MatDividerModule } from '@angular/material/divider';
export interface FileUploadItem {
file: File;
previewUrl?: string;
progress: number;
error?: string;
id: string;
}
@Component({
selector: 'app-file-upload',
imports: [
MatCardModule,
MatProgressBarModule,
MatIconModule,
MatTooltipModule,
MatChipsModule,
MatDividerModule,
],
templateUrl: 'file-upload.component.html',
styleUrls: ['file-upload.component.scss'],
})
export class FileUploadComponent implements OnInit, OnDestroy {
@Input()
uploadUrl: string = '';
@Input()
requiredFileType: string | string[] = 'application/pdf';
@Input()
maxFileSize: number = 10 * 1024 * 1024; // 10MB
@Input()
maxFiles: number = 5;
@Input()
autoUpload: boolean = false;
@Output()
filesSelected = new EventEmitter<FileUploadItem[]>();
@Output()
uploadProgressChange = new EventEmitter<{ id: string; progress: number }>();
@Output()
uploadComplete = new EventEmitter<FileUploadItem[]>();
@Output()
uploadError = new EventEmitter<{ id: string; error: string }>();
@ViewChild('fileInput', { static: true })
fileInput!: ElementRef<HTMLInputElement>;
@ViewChild('dropZone', { static: true })
dropZone!: ElementRef<HTMLDivElement>;
files: FileUploadItem[] = [];
uploadSub: Subscription = Subscription.EMPTY;
isDragging = false;
constructor(private http: HttpClient) {}
ngOnInit() {
this.setupDragAndDrop();
}
ngOnDestroy() {
if (this.uploadSub) {
this.uploadSub.unsubscribe();
}
}
private setupDragAndDrop() {
const zone = this.dropZone.nativeElement;
zone.addEventListener('dragover', (e) => {
e.preventDefault();
this.isDragging = true;
});
zone.addEventListener('dragleave', () => {
this.isDragging = false;
});
zone.addEventListener('drop', (e) => {
e.preventDefault();
this.isDragging = false;
const files = e.dataTransfer?.files;
if (files) {
this.handleFiles(files);
}
});
}
onFileChange(event: Event) {
const input = event.target as HTMLInputElement;
if (input.files) {
this.handleFiles(input.files);
}
}
private handleFiles(files: FileList) {
if (this.files.length + 1 > this.maxFiles) {
this.uploadError.emit({
id: this.generateId(),
error: `Maximum ${this.maxFiles} files allowed`,
});
return;
}
const fileArray = Array.from(files);
const validFiles: File[] = [];
fileArray.forEach((file) => {
if (!this.isValidFile(file)) {
return;
}
validFiles.push(file);
});
if (validFiles.length === 0) return;
const newFiles = validFiles.map((file) => ({
file,
id: this.generateId(),
progress: 0,
previewUrl: this.getPreviewUrl(file),
}));
this.files = [...this.files, ...newFiles];
this.filesSelected.emit(this.files);
if (this.autoUpload) {
this.uploadAll();
}
}
private isValidFile(file: File): boolean {
const type = file.type;
const size = file.size;
const allowedTypes = Array.isArray(this.requiredFileType)
? this.requiredFileType
: this.requiredFileType.split(',');
const isValidType = allowedTypes.some((t) => {
if (t.includes('/')) return type.startsWith(t);
if (t === 'image') return type.startsWith('image/');
if (t === 'pdf') return type === 'application/pdf';
if (t === 'text') return type.startsWith('text/');
return false;
});
if (!isValidType) {
this.uploadError.emit({
id: this.generateId(),
error: `File type not allowed: ${file.name}`,
});
return false;
}
if (size > this.maxFileSize) {
this.uploadError.emit({
id: this.generateId(),
error: `File too large: ${file.name} (${(size / 1024 / 1024).toFixed(2)}MB)`,
});
return false;
}
if (this.files.length + 1 > this.maxFiles) {
this.uploadError.emit({
id: this.generateId(),
error: `Maximum ${this.maxFiles} files allowed`,
});
return false;
}
return true;
}
private getPreviewUrl(file: File): string | undefined {
const type = file.type;
if (type.startsWith('image/')) {
return URL.createObjectURL(file);
}
return undefined;
}
private generateId(): string {
return Math.random().toString(36).substr(2, 9);
}
getIcon(fileType: string): string {
if (fileType.startsWith('image/')) {
return 'image';
}
if (fileType === 'application/pdf') {
return 'picture_as_pdf';
}
if (fileType.startsWith('text/')) {
return 'description';
}
return 'insert_drive_file';
}
uploadAll() {
if (!this.uploadUrl) {
console.error('Upload URL is required!');
return;
}
this.uploadSub = this.http
.post(
this.uploadUrl,
this.files.map((f) => f.file),
{
reportProgress: true,
observe: 'events',
},
)
.pipe(finalize(() => this.reset()))
.subscribe((event) => {
if (event.type === HttpEventType.UploadProgress) {
const index = Math.floor((event.loaded / event.total!) * 100);
const id = this.files[0]?.id;
if (id) {
this.files = this.files.map((f) => ({
...f,
progress: index,
}));
this.uploadProgressChange.emit({ id, progress: index });
}
}
});
}
cancelUpload(id: string) {
const file = this.files.find((f) => f.id === id);
if (file) {
this.files = this.files.filter((f) => f.id !== id);
this.uploadError.emit({ id, error: 'Upload cancelled' });
}
}
reset() {
this.uploadSub.unsubscribe();
this.uploadSub = Subscription.EMPTY;
}
removeFile(id: string) {
this.files = this.files.filter((f) => f.id !== id);
}
downloadFile(id: string) {
const file = this.files.find((f) => f.id === id);
if (file) {
const url = URL.createObjectURL(file.file);
const a = document.createElement('a');
a.href = url;
a.download = file.file.name;
a.click();
URL.revokeObjectURL(url);
}
}
}