Working with FormData in Angular 16
MBark July 28, 2023
In this post, we'll look at how to use FormData in Angular to communicate with an ASP.NET Core Web API. FormData is a JavaScript object that allows you to create and deliver data in an HTML form-compatible way. It's very beneficial when dealing with file uploads or sending complex data structures.
Setting up the Web API
First, let's set up our ASP.NET Core Web API backend to receive and process the FormData. We will use a DTO (Data Transfer Object) class to define the structure of the data we expect to receive.
public class Employee { public string Name { get; set; } public int Age { get; set; } public IFormFile File { get; set; } }
In the above code snippet, we define a Employee
class with properties for the name, age, and a file. The IFormFile
type represents an uploaded file.
Next, create an API endpoint to receive the FormData:
[HttpPost] public IActionResult AddEmployee([FromForm] Employee employee) { // Process the data and perform necessary operations // ... return Ok(); }
Here, we define an AddEmployee
action that accepts a Employee
object from the request body using the [FromForm]
attribute.
Implementing the Frontend in Angular
Now let's move on to the Angular frontend and see how we can work with FormData when making requests to our ASP.NET Core Web API.
First, import the necessary Angular modules:
import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http';
Next, create a component and inject the HttpClient in its constructor:
@Component({ selector: 'app-upload', templateUrl: './upload.component.html', styleUrls: ['./upload.component.css'] }) export class UploadComponent { constructor(private http: HttpClient) { } }
Uploading FormData
To upload FormData, we'll need to create an HTML form and handle the submission using Angular.
In your template file (upload.component.html
), add the following markup:
In the above code, we define an HTML form with input fields for name, age, and file. We use Angular's ngModel to bind the input values to component properties.
In your component class (employee.component.ts
), add the following methods:
export class Employee { name: string; age: number; file: File; constructor(private http: HttpClient) { } addEmployee(event: Event): void { event.preventDefault(); const formData = new FormData(); formData.append('name', this.name); formData.append('age', this.age.toString()); formData.append('file', this.file); this.http.post('/api/AddEmployee', formData).subscribe(() => { // Handle success }, (error) => { // Handle error }); } handleFileChange(files: FileList): void { this.file = files.item(0); } }
In the addEmployee
method, we create a new FormData object and append the input values to it. Then, we make a POST request to the /api/upload
endpoint, passing the FormData as the request body.
The handleFileChange
method is triggered when a file is selected. It assigns the selected file to the file
property.