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 Angular KeyUp Event on Input Example

Angular KeyUp Event on Input Example

September 22, 2022March 16, 2024

Angular KeyUp Event on Input is an Angular event binding it triggers when user interacts with DOM like text based input element and when we key up the input. Input events in angular can be handled using input and output decorators and in this tutorial we will learn Angular KeyUp…

Read More

How to check jQuery checkbox checked or not ?

January 25, 2022January 25, 2022

In this article i will show you multiple way to check or validate if a checkbox is checked or not. Also i will show you to check a checkbox programmatically. In the post we will learn all possibilities to validate a checkbox and how we can check a checkbox using…

Read More
Javascript Laravel Customized Autocomplete JQuery UI

Laravel Customized Autocomplete JQuery UI

July 12, 2022July 12, 2022

Laravel Customized Autocomplete JQuery UI 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 to provide the data in json response. In this tutorial we…

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