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

How to submit multipart form data in angular reactive form ?

Aman Jain, September 12, 2021October 31, 2021

In this tutorial, you will learn uploading a multipart reactive form in angular using HttpClient. In a webpage uploading files as multipart form data is a important aspect.

If you are a new then you can read What is Angular and how to install angular ?

So, for this tutorial we required knowledge of Angular component, html, typescript and php.

Step 1 : Create a component

You can create component using command line or manually

ng g component UploadFile

Step 2 : Import HttpClientModule and ReactiveFormModule in app.module.ts

Import two important module HttpClientModule and ReactiveFormModule form @angular/common/http and @angular/forms

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { HttpClient } from '@angular/common/http';
import { HttpClientModule } from '@angular/common/http';
import { UploadFileComponent } from './upload-file/upload-file.component';

@NgModule({
  imports: [BrowserModule, FormsModule, ReactiveFormsModule, HttpClientModule],
  declarations: [AppComponent, UploadFileComponent, HelloComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}

Step 3: Create form group and upload function

Now, we are importing FormGroup, HttpClient, FormControl and Validators.

Here, we create two fields name and image. Next we created onChange function to handle the file input change event. then we have uplaodFile method to upload the multipart data from FormData class.

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-upload-file',
  templateUrl: './upload-file.component.html',
  styleUrls: ['./upload-file.component.css']
})
export class UploadFileComponent implements OnInit {
  form: FormGroup = new FormGroup(
    {
      name: new FormControl("", [Validators.required, Validators.minLength(4)]),
      image: new FormControl("", [Validators.required, Validators.email]),
    }

  );
  constructor(public http: HttpClient) { }

  ngOnInit(): void {
  }

  onChange(e: any) {
    let extensionAllowed: any = { "png": true, "jpeg": true };
    let file = e.target.files[0];
    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;
      }
    }
    this.form.controls["image"].setValue(file);
  }
  uplaodFile() {
    let form = this.form.value;
    const uploadData = new FormData();
    for (let input_name in form) {
      if (form[input_name] instanceof Blob) // check is file
      {
        uploadData.append(input_name, form[input_name], form[input_name].name ? form[input_name].name : "");
      }
      else
        uploadData.append(input_name, form[input_name]);
    }

    return this.http.post('https://readerstacks.com/demo/php.php', uploadData)
      .subscribe(data => {
        alert(JSON.stringify(data));
      });  }

}

Step 4 : Create html file and form

Here, we have created a form with 2 inputs named as name and image. formGroup attribute to bind the form with angular reactive form.

<form [formGroup]="form" (submit)="uplaodFile()">
    <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 
            (change)="onChange($event)"
             multiple 
             placeholder="Pictures"   
             type="file" required>
        </div>
    </div>
    
    <div class="form-group btn-group">

        <button class="" type="submit"  >Submit</button>
    </div>
</form>

Output:

Screenshot 2021 09 12 at 11.16.44 AM

Php FIle: index.php

<?php
echo json_encode(["post"=>$_POST,"file"=>$_FILES]);
?>

Live Preview:

Related

Javascript Angular

Post navigation

Previous post
Next post

Related Posts

Angular How to Use Interface in Angular with Example

How to Use Interface in Angular with Example?

August 6, 2022March 16, 2024

Interface in angular or in any programming languages is pattern which bind component or class to use same implementation across the modules. In this article we will cover the use of interface in angular with example. In Angular interface can be used on service, factory, component or any type of…

Read More
Javascript Angular If Else

How to use NgIf, Ngif else and elseif in angular 12 ?

April 2, 2022November 7, 2023

In this tutorial we will learn to use angular if else, ngIf, ngif else and elseif. if else is used to make conditional statement in template same as we can also use if else. As we all programmers know if or if else condition is used to create conditional statements…

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

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