
Angular File Upload - Web API
1: Create a file input in the template: In the HTML template, you need to add a file input element. This input element will allow the user to choose a file to upload.:
file-upload.component.html
<input type="file" (change)="handleFileInput($event.target.files)"/>
<button type="button" (click)="uploadFile()">Upload</button>
2: Create file-upload.component.ts to handle file uploads: Create a component that will allow users to select files to upload. Here's an example of how the component may look like:
file-upload.component.ts
import { Component } from '@angular/core';
import { FileUploadService } from './file-upload.service';
@Component({
selector: 'app-file-upload',
templateUrl: './file-upload.component.html'
})
export class FileUploadComponent {
fileToUpload: File = null;
constructor(private fileUploadService: FileUploadService) { }
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}
uploadFile() {
this.fileUploadService.upload(this.fileToUpload).subscribe(() => {
console.log('File uploaded successfully.');
}, (error) => {
console.error('Error uploading file:', error);
});
}
}
3: Create a file upload service: Create a file upload service that will handle the file upload functionality. This service should have a method that will make a POST request to the server to upload the file. Here's an example of how the file upload service may look like:
file-upload.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable()
export class FileUploadService {
constructor(private http: HttpClient) { }
upload(file: File) {
const formData = new FormData();
formData.append('file', file, file.name);
const headers = new HttpHeaders();
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
return this.http.post('/api/upload', formData, { headers: headers });
}
}