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 Laravel Dynamic Autocomplete Using Typehead JS

Laravel Dynamic Autocomplete Using Typehead JS

July 16, 2022July 16, 2022

In this article we will learn to use Laravel Dynamic Autocomplete Using Typehead JS. Typehead JS is useful when we want live search of bulk data. Autocomplete search is mostly work of javascript and when we want to fetch live data from database then we require the intervention of laravel…

Read More
Javascript How to convert JSON string to JSON object in angular

How to convert JSON string to JSON object in angular ?

April 13, 2022November 6, 2023

Sometimes in our application we want to convert JSON string to JSON object because the format of response is JSON string rather then JSON object, so in this tutorial i will show you to use JSON string to object and vise versa. JSON are used to communicate between client and…

Read More
Javascript Angular ngClass conditional class Example

Angular ngClass conditional class Example

October 8, 2022March 16, 2024

In this blog post, we’ll explore Angular ngClass conditional class Example in component’s styles based on certain conditions. Sometimes in our application we want dynamically change the color, size, font, background images so Angular provides various ways to conditionally apply classes and style to elements. We’ll discuss how to use…

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

  • 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
  • Understanding High Vulnerabilities: A Deep Dive into the Weekly Summary
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version