To enable file uploads with `multipart/form-data` using Angular’s `HttpClient`, follow these steps:

1. Begin by importing the necessary modules in your component file:

import { Component } from ‘@angular/core’;
import { HttpClient } from ‘@angular/common/http’;

2. Inject the `HttpClient` into your component’s constructor:

constructor(private http: HttpClient) { }

3. Create a method that will handle the file upload process:

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);
});
}

4. In your component’s template, include an `< input type="file" />` element and bind it to the `uploadFile` method:

<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.

Support On Demand!

Angular