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 Set focus on input angular example

Set focus on input angular example

September 25, 2022March 16, 2024

Angular is a great framework for building front-end web applications. One of its many features is the ability to set focus on input angular element. This can be useful in a variety of situations, such as when you want to focus on a particular input field after a user clicks…

Read More
Javascript get radio input value in jQuery

How to get radio input value in jQuery ?

October 31, 2021November 5, 2023

While submitting a form or validating a form using the jQuery, we can get all the values of form easily but radio button works differently and we need some extra efforts to fetch the value of radio input. So in this article i will demonstrate to fetch the value of…

Read More
Softwares disable change detection anagular

How to disable automatic change detection strategy in angular component?

July 4, 2021November 8, 2023

In angular all components by default take the changes as any event occur, but sometime we disable automatic change detection strategy in angular. Thus, to detach the two way binding in component we can use changeDetection strategy in component metadata. Angular Change Detection Strategy is simple to implement using the…

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

  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
  • Understanding High Vulnerabilities: A Deep Dive into the Weekly Summary
  • Building a Million-Dollar Brand: The Journey of Justin Jackson
  • Mastering Schedule Management with Laravel Zap
  • The Resilience of Nature: How Forests Recover After Fires
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version