Spread the love

in this tutorial we will learn to upload the files with reactive form in angular. it’s not easy to upload the files along with form data in angular in compare to JQuery and other JavaScript framework. Angular upload a form in JSON and some time it get difficult to obtain the values of form in language like PHP, therefore in this article i will demonstrate you to upload files along with form inputs in angular.

In this tutorial i will take a simple example of form with an input and file input using reactive forms library of angular. I will also show you the output of PHP.

Before start i assume you well know about the components, services, directive and angular generators.

Read More about angular cli, component.

So, let’s begin with simple steps

Step 1: Create a component

Generate a component using angular CLI or you can create manually

ng generate component AngularFileUpload

In this above command AngularFileUpload is our component name and it will generate 4 files which is typescript, html, css and test file.

Step 2: Add reactive form and HttpClient to component

Open the angular-file-upload.component.ts file and start editing it





import { Component, OnInit } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { catchError, map } from 'rxjs/operators';
import { throwError } from 'rxjs';
import { FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-angular-file-upload',
  templateUrl: './angular-file-upload.component.html',
  styleUrls: ['./angular-file-upload.component.css']
})
export class AngularFileUploadComponent implements OnInit {
  form: FormGroup;
  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.form = new FormGroup({
      name: new FormControl('', [Validators.required]),
      email: new FormControl('', [Validators.required]),
      picture: new FormControl('', [Validators.required])

    });


  }

  makeRequest(url: string, form: any, settings: any = { toast: true, hideLoader: false }) {

    let formData = form;
    const uploadData = new FormData(); // Create Form Data object to upload the file in POST FORM

    for (let i in form) {
      if (form[i] instanceof Blob){  //  Check if key value is file
        uploadData.append(i, form[i], form[i].name ? form[i].name : "");
      }
      else
        uploadData.append(i, form[i]);
    }
    
    return this.http.post(url, uploadData)
      .pipe(map((data: any) => {
        //handle api 200 response code here or you wanted to manipulate to response
        return data;
      })
        ,
        catchError((error) => {    // handle error
        
          if (error.status == 404) {
            //Handle Response code here
          }
          return throwError(error);
        })
      );

  }

 

  submit(form) {

    this.makeRequest("http://localhost/test.php", this.form.value).subscribe(data => {

      //handle response
    })
  }

  getFile(e) {

    let extensionAllowed = {"png":true,"jpeg":true};
    console.log(e.target.files);
    if (e.target.files[0].size / 1024 / 1024 > 20) {
      alert("File size should be less than 20MB")
      return;
    }
    if (extensionAllowed) {
      var nam = e.target.files[0].name.split('.').pop();
      if (!extensionAllowed[nam]) {
        alert("Please upload " + Object.keys(extensionAllowed) + " file.")
        return;
      }
    }
    this.form.controls["picture"].setValue(e.target.files[0]);

  }
}



In the above code we have imported catchError, map, HttpClient, header etc.

then we have created a FormGroup and Form Control to initialize the form. to make post request we have also created a function makeRequest by which we are sending picture file object with form data.

Step 3: Add form to view

Now, we have created our component Reactive form and HttpClient, so let’s setup the form now

Html file angular-file-upload.component.html

<form [formGroup]="form" (submit)="submit()">
    <div class="form-group">
        <div class="">

            <input placeholder="Name" formControlName="name" type="text" required>
            <span *ngIf="form.controls.name.touched 
            &&  form.controls.name.invalid">This field is required</span>

        </div>
    </div>

    <div class="form-group">
        <div class="">
            <input placeholder="Email" formControlName="email" type="email" required>
            <span *ngIf="form.controls.email.touched  && form.controls.email.invalid">This field is required</span>
        </div>
    </div>

    <div class="form-group">
        <div class="">
            <input (change)="getFile($event)" placeholder="Picture" formControlName="picture" type="file" required>
            <span *ngIf="form.controls.picture.touched && form.controls.picture.invalid">Please upload file</span>
        </div>
    </div>

    <div class="form-group btn-group">
        <button class="" type="submit" [disabled]="!form.valid || loading">Submit</button>
    </div>
</form>

Let’s test our implementation by running the ng serve and php we can get this form in $_POST and $_FILES

<?php 

print_r($_POST);
print_r($_FILES);


Screenshots:

Thanks for spending time here to learn the file upload with php. you can comment below if you have any doubts.

One thought on “How to upload files with form data in angular 12?

  1. Pingback: Upload multiple files in angular with array - Readerstacks

Leave a Reply