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

How to upload files with form data in angular 12?

Aman Jain, June 20, 2021November 8, 2023

in this tutorial we will learn to upload files with form data in angular. it’s not easy to upload the files along with form data in angular in compare to JQuery and other JavaScript framework. Angular upload a form in JSON and some time it get difficult to obtain the values of form in language like PHP, therefore in this article i will demonstrate you to upload files along with form inputs in angular.

In this tutorial i will take a simple example of form with an input and file input using reactive forms library of angular. I will also show you the output of PHP.

Before start i assume you well know about the components, services, directive and angular generators.

Read More about angular cli, component.

So, let’s begin with simple steps

Step 1: Create a component

Generate a component using angular CLI or you can create manually

ng generate component AngularFileUpload

In this above command AngularFileUpload is our component name and it will generate 4 files which is typescript, html, css and test file.

Step 2: Add reactive form and HttpClient to component

Open the angular-file-upload.component.ts file and start editing it





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

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

    });


  }

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

    let formData = form;
    const uploadData = new FormData(); // Create Form Data object to upload the file in POST FORM

    for (let i in form) {
      if (form[i] instanceof Blob){  //  Check if key value is file
        uploadData.append(i, form[i], form[i].name ? form[i].name : "");
      }
      else
        uploadData.append(i, form[i]);
    }
    
    return this.http.post(url, uploadData)
      .pipe(map((data: any) => {
        //handle api 200 response code here or you wanted to manipulate to response
        return data;
      })
        ,
        catchError((error) => {    // handle error
        
          if (error.status == 404) {
            //Handle Response code here
          }
          return throwError(error);
        })
      );

  }

 

  submit(form) {

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

      //handle response
    })
  }

  getFile(e) {

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

  }
}



In the above code we have imported catchError, map, HttpClient, header etc.

then we have created a FormGroup and Form Control to initialize the form. to make post request we have also created a function makeRequest by which we are sending picture file object with form data.

Step 3: Add form to view

Now, we have created our component Reactive form and HttpClient, so let’s setup the form now

Html file angular-file-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)="getFile($event)" placeholder="Picture" formControlName="picture" type="file" required>
            <span *ngIf="form.controls.picture.touched && form.controls.picture.invalid">Please upload file</span>
        </div>
    </div>

    <div class="form-group btn-group">
        <button class="" type="submit" [disabled]="!form.valid || loading">Submit</button>
    </div>
</form>

Let’s test our implementation by running the ng serve and php we can get this form in $_POST and $_FILES

<?php 

print_r($_POST);
print_r($_FILES);


Screenshots:

  • Screenshot 2021 06 20 at 10.12.18 AM
  • Screenshot 2021 06 20 at 10.15.44 AM
  • Screenshot 2021 06 20 at 10.21.32 AM
  • Screenshot 2021 06 20 at 10.21.51 AM

Thanks for spending time here to learn the file upload with php. you can comment below if you have any doubts.

Related

Angular Javascript Softwares angularangular6file uploadphp

Post navigation

Previous post
Next post

Related Posts

Javascript reusable components in angular

How to make reusable components in angular?

September 11, 2021October 4, 2022

Another rich feature of angular is reusability of component, Angular components are those components which we can reuse multiple times in a module or application. Angular reusable component can be dynamic and much flexible to send updates on any event . Before start, I assume you well aware of installation…

Read More
Javascript Arrow function

What is arrow functions in JavaScript / ES6?

June 12, 2021November 8, 2023

arrow functions in JavaScript are introduced in ES6, before es6 we used normal function which needs to write more code to achieve the functionality. let take an example of arrow functions and es5 normal functions are follow: Normal functions of es5 Arrow functions of es6 uhmm! its looking like so…

Read More
Javascript How to create global variable in angular ?

How to create global variables in angular ?

October 3, 2022March 16, 2024

In this article, we will learn about the create global variables in Angular and how to use them. We will also see how to use them across the application by importing the file. There are different ways to create global variables in angular. One way is to use the global…

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

  • 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

  • Mastering Schedule Management with Laravel Zap
  • 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
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version