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 How to check user agent in angular

How to check user agent in angular ?

October 18, 2022March 16, 2024

In this post, we will show you how to check user agent in Angular. user-agent header is a string that contains information about the browser and operating system. It is set by the browser and sent to the server with every request. It can also be used to determine if…

Read More
Javascript Password and confirm password validation in angular

Password and confirm password validation in angular 14 ?

September 9, 2022March 16, 2024

Angular 14 provides built-in library for validation but it doesn’t have built in validation for password and confirm password. Angular 14 has release and we are excited to work with new feature so i am also updating the most search article with latest version of angular. so in this tutorial…

Read More
Javascript how to install angular

What is Angular and how to install angular ?

August 29, 2021October 1, 2021

Angular is a framework of javascript. It’s used for creating efficient and single page application with ease. We can define the angular as follow: Angular is a component based component framework. Angular is collection of libraries which include routing, forms, validations, http requests etc. Angular is easy to use and…

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

  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version