Uploading Files with FormData and Post Requests Using Angular 14 HttpClient
In this quick tutorial, we’ll learn to upload files in Angular 14 using FormData and POST requests via Angular 14 HttpClient 🤔
✋You need to have an Angular 14 project and Angular CLI installed in your machine.
> ✋✋ Join our Facebook group 👈 to discuss anything related to Angular development.
🚀Setting up Angular 14 HttpClient 👇
You need to start by setting up HttpClient in your project.
Go to the src/app/app.module.ts file and simply import HttpClientModule and add it to the imports array:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
That’s all, you can now inject HttpClient in any service or component and start using it to send HTTP requests to your backend API server or any third-pary API service.
🚀Creating an Angular 14 Component 👇
Let’s now create an Angular component for the UI of our example.
Head over to a new command-line interface and run the following commands:
$ cd ~/angular-formdata-httpclient-example
$ ng generate component home
We simply need to navigate to our project’s folder and generate a component using the ng generate component command.
🚀 Creating an Angular 14 Service 👇
Now, let’s create an Angular 14 service for isolating the code that sends form data to the server.
Head back to your command-line interface and run the following command to generate a new service:
$ ng generate service upload
Next, go to the generated src/app/upload.service.ts
file and add the following imports:
import { HttpClient, HttpEvent, HttpErrorResponse, HttpEventType } from '@angular/common/http';
import { map } from 'rxjs/operators';
Next, you need to inject HttpClient
and define the serverUrl variable which needs to contain your server’s address:
@Injectable({
providedIn: 'root'
})
export class UploadService {
serverUrl: string = "https://file.io";
constructor(private httpClient: HttpClient) { }
}
Next, you need to add the sendFormData()
method that works by invoking the post() method of HttpClient to send a POST request with form data to the backend server:
public sendFormData(formData) { return this.httpClient.post<any>(this.serverUrl, formData, {
reportProgress: true,
observe: 'events'
});
}
🚀 Sending the FormData 👇
Now, you need to inject this service to call this method to send FormData to your server.
Go to the src/app/home/home.component.ts
file, and add the following imports:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';import { HttpEventType, HttpErrorResponse } from '@angular/common/http';import { of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { UploadService } from '../upload.service';
Next, define the fileUpload and files variables and inject UploadService as follows:
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
@ViewChild("fileUpload", {static: false}) fileUpload: ElementRef;
files = [];
constructor(private uploadService: UploadService) { }
Next, define the sendFile() method:
sendFile(file) {
const formData = new FormData();
formData.append('file', file.data);
file.inProgress = true;
this.uploadService.sendFormData(formData).subscribe((event: any) => {
if (typeof (event) === 'object') {
console.log(event.body);
}
});
}
Next, define the sendFiles() method which can be used to upload multiple image files:
private sendFiles() {
this.fileUpload.nativeElement.value = '';
this.files.forEach(file => {
this.sendFile(file);
});
}
Next, define the onClick() method:
onClick() {
const fileUpload = this.fileUpload.nativeElement;fileUpload.onchange = () => {
for (let index = 0; index < fileUpload.files.length; index++)
{
const file = fileUpload.files[index];
this.files.push({ data: file, inProgress: false, progress: 0});
}
this.sendFiles();
};
fileUpload.click();
}
Next, we need to create the HTML template.
Open the src/app/home/home.component.html
file and add the following markup:
<div>
<ul>
<li *ngFor="let file of files">
<span id="file-label">
{{file.data.name}}
</span>
</li>
</ul>
<button (click)="onClick()">
Upload
</button>
<input type="file" #fileUpload id="fileUpload" name="fileUpload" multiple="multiple" accept="image/*" style="display:none;" /></div>
That’s it, you have seen how you can send FormData with a POST request using Angular 14 HttpClient 👏👏👏