To enable file uploads with `multipart/form-data` using Angular’s `HttpClient`, follow these steps:
import { Component } from ‘@angular/core’;
import { HttpClient } from ‘@angular/common/http’;
constructor(private http: HttpClient) { }
uploadFile(event: any) {
const file = event.target.files[0];
const formData = new FormData();
formData.append('file', file);
// Perform the HTTP request
this.http.post('http://your-api-endpoint', formData).subscribe((response) => {
console.log('File uploaded successfully');
},(error) => {
console.error('Error uploading file:', error);
});
}
<input type="file" (change)="uploadFile($event)">
Subsequently, the `FormData` object is sent as the payload in a `POST` request using the `HttpClient`’s `post` method.
Ensure that you have appropriate server-side implementation to receive and handle the uploaded file correctly.
Work with our skilled Angular developers to accelerate your project and boost its performance.
Hire Angular Developers