How to Use Angular 8|9 HttpClient API to Post FormData?

By Digamber Rawat Last updated on
In this Angular FormData tutorial, we will understand how to use Angular 8|9 HttpClient API to Post FormData to a web server. Forms are an essential part of any web or mobile applications, and Forms allow us to gather data from the users and send that data to the webserver.

We are going to learn about the FormData object and how to use it in an Angular application. Its a JavaScript object, which allows us to develop a set of key/value data structure representing form fields and their respective values.

In this step by step article, we will take the help of Angular 8|9 HttpClient API to send FormData to a web server by using the Http POST method.

FormData Methods

You can initialize FormData object by creating an instance from new FormData interface as given below.

const formData = new FormData()

FormData Methods

Once the FormData instance is created then there are various methods available through FormData, which allows you to manage the data as per your requirement.

Methods Description
FormData.append() It includes a new value on a pre-existing key within a FormData object. If the key already exists, then the value will be added to that key without removing the first key.
FormData.delete() It deletes a key and value pair from the FormData object.
FormData.entries() FormData returns an iterator which allows looping over a set of key-value pair presenting in the object.
FormData.get() It returns the value associated with a given set of a key from the FormData object. However, if more values appended, then it will return the first value.
FormData.getAll() Returns all the values associated with a key from the FormData object.
FormData.has() It returns true if the key exists in FormData object.
FormData.keys() Returns an iterator which allows looping over all the keys of the key-value data structure in this object.
FormData.set() It is used to set the value into the FormData object with the particular key. Value is replaced if a key already exists in the FormData object.
FormData.values() Returns an iterator which allows looping over all the values existing in this object

You can check out more about the FormData object here.

Setting up Node & Express Server

For the demo purpose, we are using the existing REST API built with Node, Express, MongoDB, and Multer NPM modules. By using this existing node server you can easily store the user data such as name and avatar (profile image) to the mongoDB database.

Git clone the node server repo in the root of the Angular project.

git clone https://github.com/SinghDigamber/nodejs-file-upload-server.git backend

# Cloning into 'backend'...
# remote: Enumerating objects: 4017, done.
# remote: Counting objects: 100% (4017/4017), done.
# remote: Compressing objects: 100% (2958/2958), done.
# remote: Total 4017 (delta 858), reused 4013 (delta 857), pack-reused 0
# Receiving objects: 100% (4017/4017), 3.98 MiB | 1.14 MiB/s, done.
# Resolving deltas: 100% (858/858), done.
# Checking out files: 100% (3947/3947), done.

Next, navigate to the backend folder and run following command.

$ cd backend

$ npm install

Next, run the given below command to start the mongoDB database.

mongod

Next, run the nodemon server:

nodemon

Once your server is up and running, then you can check your Node server app on the following Urls: http://localhost:4000

  • /api: Users List
  • /api/create-user: Create User

Set up Angular App

Run following command to install the basic Angular app:

ng new angular-formdata

# ? Would you like to add Angular routing? Yes
# ? Which stylesheet format would you like to use? CSS

Run the command to install the Bootstrap 4.

npm install bootstrap

Go to angular.json file and inject the bootstrap style sheet inside the styles array like given below.

"styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
          "src/styles.css"
         ]

Now, your Angular app is ready to be started via following command.

ng serve --open

Now, create a component where we will put all of our form data logic in an Angular app.

ng g c file-upload

Build Form with Reactive Forms and Bootstrap 4

In this step we will create a Form for user, by using this form user can submit data and send it on the web server. We will be using Angular’s Reactive Forms approach to get and set the data, first import the ReactiveFormsModule in the app.module.ts file.

import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [...],
  imports: [
    ReactiveFormsModule
  ],
  bootstrap: [...]
})

export class AppModule { }

Then create a form with the help of Bootstrap 4 and Reactive Forms APIs such as FormBuilder and FormGroup.

Go to app/file-upload.component.html file and add the following code:

<div class="container">
    <form [formGroup]="form" (ngSubmit)="submitForm()">
        <div class="form-group">
            <input type="file" (change)="uploadFile($event)">
        </div>

        <div class="form-group input-group-lg">
            <input class="form-control" placeholder="Name" formControlName="name">
        </div>

        <div class="form-group">
            <button class="btn btn-danger btn-block btn-lg">Create</button>
        </div>
    </form>
</div>

Next, go to file-upload.component.ts file and add the following code inside of it. Here, we are setting up the user entered data in the Reactive Forms form: FormGroup object (name, avatar).

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from "@angular/forms";

@Component({
  selector: 'app-file-upload',
  templateUrl: './file-upload.component.html',
  styleUrls: ['./file-upload.component.css']
})

export class FileUploadComponent implements OnInit {
  form: FormGroup;

  constructor(public fb: FormBuilder) {
    this.form = this.fb.group({
      name: [''],
      avatar: [null]
    })
  }

  ngOnInit() { }

  uploadFile(event) {
    const file = (event.target as HTMLInputElement).files[0];
    this.form.patchValue({
      avatar: file
    });
    this.form.get('avatar').updateValueAndValidity()
  }

  submitForm() {
    console.log(this.form.value)
  }

}

Angular FormData

POST FormData with Angular HttpClient API

To make the HTTP POST request in Angular, first import the HttpClientModule API in app.module.ts file.

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [...],
  imports: [
     HttpClientModule
  ],
  bootstrap: [...]
})

export class AppModule { }

In the next step, import HttpClient in file-upload.component.ts file, then inject it into the constructor. The Angular HTTP API will allow you to make GET, POST, DELETE or UPDATE request in your Angular app.

import { HttpClient } from '@angular/common/http';

constructor(
    private http: HttpClient
) {...}

Create formData instance from FormData object and use the append() method to set the values. Define the name and avatar value in the append method from the Reactive Forms form (FormGroup) object.

submitForm() {
  var formData: any = new FormData();
  formData.append("name", this.form.get('name').value);
  formData.append("avatar", this.form.get('avatar').value);

  this.http.post('http://localhost:4000/api/create-user', formData).subscribe(
    (response) => console.log(response),
    (error) => console.log(error)
  )
}

Next, make the HTTP POST request in Angular. Pass the /create-user API in the first argument and pass the formData in the second argument.

Angular Post FormData

Final file-upload.component.ts file:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from "@angular/forms";
import { HttpClient } from '@angular/common/http';


@Component({
  selector: 'app-file-upload',
  templateUrl: './file-upload.component.html',
  styleUrls: ['./file-upload.component.css']
})

export class FileUploadComponent implements OnInit {
  form: FormGroup;

  constructor(
    public fb: FormBuilder,
    private http: HttpClient
  ) {
    this.form = this.fb.group({
      name: [''],
      avatar: [null]
    })
  }

  ngOnInit() { }

  uploadFile(event) {
    const file = (event.target as HTMLInputElement).files[0];
    this.form.patchValue({
      avatar: file
    });
    this.form.get('avatar').updateValueAndValidity()
  }

  submitForm() {
    var formData: any = new FormData();
    formData.append("name", this.form.get('name').value);
    formData.append("avatar", this.form.get('avatar').value);

    this.http.post('http://localhost:4000/api/create-user', formData).subscribe(
      (response) => console.log(response),
      (error) => console.log(error)
    )
  }

}

Conclusion

Finally, we have learned how to use Angular 8|9 HttpClient API to Post FormData (multipart/form-data). I hope this tutorial helped you a lot, please consider it sharing with others.

Git Repo

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.