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

Angular form validation with example

August 30, 2021August 30, 2021

Angular has in-build form validation rules to validate the inputs and show errors in the ui with ease. Before reading you should have knowledge of angular, installation process, components and angular FormGroup. Steps to create a reactive form in angular Create a new or existing angular project, you can also…

Read More

How many type of methods in Restful api?

August 28, 2021February 22, 2024

Restful api is very useful today while creating a mobile application or web application. Restful api or Http request methods There is 4 types of method of http request. Post Get Put Delete Patch 1. Post method Post method is widely used to fetch the content of a form or…

Read More
Javascript Laravel Multi Select Tag Autocomplete Using Select2

Laravel Multi Select Tag Autocomplete Using Select2

July 19, 2022July 19, 2022

In this article we will learn to use Laravel Multi Select Tag Autocomplete Using Select2. Select2 is useful when we want live search of bulk data or to convert the existing select boz with multi features like search, multi select and options customizations. In this article we will cover multiple…

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

  • 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 Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version