Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
angular file upload

How to upload multiple files in angular 12 reactive form

Aman Jain, June 20, 2021November 8, 2023

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:

  • Screenshot 2021 06 20 at 12.35.32 PM
  • Screenshot 2021 06 20 at 12.35.38 PM

Related

Softwares Angular Javascript angularangular php filemultiple file

Post navigation

Previous post
Next post

Related Posts

Javascript Angular conditional validation in reactive forms

Angular conditional validation in reactive forms

September 26, 2022March 16, 2024

This post covers the basis of angular conditional validation in reactive forms. By the end of this post, the reader will know how to set up a simple form and validate it according to different criteria. Conditional validation is when the validity of a form control is determined by something…

Read More

How to create a new project of angular ?

August 29, 2021September 12, 2021

Before start the article i would suggest you to read our article what is angular and installation process. To create a new angular app follow the below steps: Open the terminal or command line Go to the folder in which you want to create your new angular project Example: E:/angular…

Read More
Javascript Password and confirm password validation in javascript

Password and confirm password validation in javascript

September 17, 2021November 21, 2021

In this tutorial, we will cover password strength validation , password not empty validation and confirm password validation. we will check on every submission of form whether the entered password pass or fail the criteria. Password Strength validation in javascript Password field must contain At least 8 characters Should be…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • August 2025
  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Transformative Power of Education in the Digital Age
  • Understanding High Vulnerabilities: A Closer Look at the Week of July 14, 2025
  • Exploring Fresh Resources for Web Designers and Developers
  • The Intersection of Security and Technology: Understanding Vulnerabilities
  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version