Spread the love

How to upload multiple files in angular 12 reactive form

Uploading multiple files with progress in angular is too easy, you can implement it in your website using the below guideline. i will suggest to read my last post Angular file upload with post form data and php $_FILES to basic needs and uploading.

Steps to Upload multiple images in angular are here

Step 1. First generate the Component using the

ng generate component MultipleUpload

it will generate 4 files typescript, html, css, and unit test file and also import the new component and module in main module of angular application.

Step 2. Open the component file and start editing

In the next step, we are going to import Component to create component , HttpClient to make the request to the server, FormControl and Validators for form.

File /app/multiple-upload.compenent.ts

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-multiple-upload',
  templateUrl: './multiple-upload.component.html',
  styleUrls: ['./multiple-upload.component.css']
})
export class MultipleUploadComponent implements OnInit {
   form: FormGroup;
  constructor(private http: HttpClient) { }

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

    });


  }

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

    let formData = form;
    const uploadData = new FormData();
    for (let i in form) {
      if (form[i] instanceof Blob) // check is file
        uploadData.append(i, form[i], form[i].name ? form[i].name : "");
      else if (form[i] instanceof Array) { //check type of file

        for (let arr in form[i]) {
          for (let lst in form[i][arr]) {
            if (form[i][arr][lst] instanceof Blob) { // check is file
              console.log("" + i + "[" + arr + "][" + lst + "]");
              uploadData.append("" + i + "[" + arr + "][" + lst + "]", form[i][arr][lst], form[i][arr][lst].name ? form[i][arr][lst].name : "");
            }
            else {
              uploadData.append("" + i + "[" + arr + "][" + lst + "]", form[i][arr][lst]);
            }
          }
        }
      }
      else
        uploadData.append(i, form[i]);
    }
    formData = uploadData



    formData.headers = new HttpHeaders({

      'Authorization': 'Bearer your_token'   //add your api token for auth
    }).set('Content-Type', []);;



    if (!settings.hideLoader)
      this.showLoader(true);  // show loader


    return this.http.post(url, formData, { headers: formData.headers })
      .pipe(map((data: any) => {

        if (!settings.hideLoader)
          this.showLoader(false);
        //handle api 200 response code here or you wanted to manipulate to response
        return data;

      })
        ,
        catchError((error) => {    // handle error
          console.log("error.status", error.status)
          if (error.status == 404) {
            //Handle Response code here
          }
          if (!settings.hideLoader)
            this.showLoader(false);

          return throwError(error);


        })
      );

  }

  showLoader(show) {
    //loader code goes here
  }


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

      //handle response
    })
  }
 files=[]
  setFiles(e) {

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


Step 3: Create a html template with form

Now, we are creating a form with formGroup and FormControl to submit the reactive form.

File : /app/multiple-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)="setFiles($event)"
             multiple 
             placeholder="Pictures"   
             type="file" required>
          

        </div>
    </div>
    
    <div class="form-group btn-group">

        <button class="" type="submit"  >Submit</button>
    </div>
</form>

Step 4: Create a file of php to upload on server

Finally, creating a php file to upload on server.

File : test.php

<?php 
print_r($_FILES);

Output Screenshots:

Leave a Reply