DEV Community

Gilad David Maayan
Gilad David Maayan

Posted on

File Upload in Angular 13

Image description
Image Source

What Is Angular?

Angular is a software development framework based on TypeScript. The Angular platform allows you to build scalable, componentized web apps. It provides a developer tool suite to build, test, and revise code. Angular also offers several integrated libraries covering a wide range of features such as form management, server-client communication, and routing.

Angular lets you scale from a single-developer project to an enterprise-grade application. Angular’s design helps simplify the application updating processes, providing the latest development capabilities. Developers can build apps with minimal effort.

Angular Components for File Upload

Angular file upload is based on the following components.

FormData
The FormData component is a data structure that can store key-value pairs. It is specially designed to hold form data and supports JavaScript, allowing you to build objects corresponding to HTML forms. This component is most useful for sending form data to the endpoints of a RESTful API. For instance, you can use the XML HTTP request interface or an HTTP client library to upload one or multiple files.

To create FormData objects, use the new operator to instantiate the FormData interface with the following script:

const formData = new FormData()

The “formData” element refers to a FormData instance. It is possible to call various methods on a FormData object to add data pairs and manipulate them. Every pair includes a key and a value.

HttpClient
Front end apps usually communicate with the server using the HTTP protocol, enabling them to upload and download data and access services on the back end. Angular offers a simplified HTTP client API for Angular-based applications—the HttpClient class in @angular/common/http.

Reactive Form
A reactive form uses an immutable, explicit approach to managing a form’s state at specific points in time. All changes to the form’s state return new states, maintaining the overall model’s integrity throughout the changes. You build reactive forms based on observable streams, providing each form input and value as a part of an input value stream. These streams are accessible synchronously.

Reactive forms offer a straightforward way to test Angular applications because you can verify that the data requested is predictable and consistent. All entities consuming the input value streams can securely access and manipulate the relevant data.

Angular 13 File Upload Example
This is abbreviated from the full tutorial by Tuts Make.

Create Angular App and Import Modules
In this section, we will go through creating an Angular app and learning how to import modules into it.

To create a demo Angular app:
Go to your terminal and use the following command to create a demo Angular application:

ng new my-new-app
Enter fullscreen mode Exit fullscreen mode

Navigate to a TypeScript file named app.module.ts and import the modules needed for the demo Angular application through the following code:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { DemoUploadAppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    DemoUploadAppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [DemoUploadAppComponent]
})
export class DemoUploadAppModule { }
Enter fullscreen mode Exit fullscreen mode

Create File Upload Form
This tutorial creates a demo reactive Angular form that takes a file as input and uses file tags. The frontend view for the form will be in a separate file and the functionality will be stored in another.

To create a reactive form to upload files to a an Angular application:
Go to the app directory and use the following code in the app.component.html to create a view for the form.

<h1>Demo File Upload Form</h1>
Enter fullscreen mode Exit fullscreen mode
User Name User Name is required. User Name should be at least 3 characters. File File is required for upload. Submit Form

In the same app directory, add the following code with formGroup and formControl elements in component.ts file.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class DemoUploadAppComponent {
  myDemoUploadForm = new FormGroup({
    name: new FormControl('', [Validators.required, Validators.minLength(3)]),
    uploadedFile: new FormControl('', [Validators.required]),
    uploadedFileSource: new FormControl('', [Validators.required])
  });

  constructor(private http: HttpClient) { }

  get f(){
    return this.myDemoUploadForm.controls;
  }

  fileChangeHandler(event:any) {

    if (event.target.files.length > 0) {
      const uploadedFile = event.target.files[0];
      this.myDemoUploadForm.patchValue({
        uploadedFileSource: uploadedFile
      });
    }
  }

  submit(){
    const uploadFormData = new FormData();
    uploadFormData.append('uploadedFile', this.myDemoUploadForm.get('uploadedFileSource')?.value);

    this.http.post('http://localhost:8001/upload.php', uploadFormData)
      .subscribe(res => {
        console.log(res);
        alert('Uploaded Successfully.');
      })
  }
}
Enter fullscreen mode Exit fullscreen mode

Add a PHP File for Upload and Start Server
The demo Angular application above requires an upload.php. It helps upload the file the user submits through the form from the app to the server.

To create the PHP file for uploading submitted to the server:
Create an upload.php file in the app directory and put the following in it:

<?php
Enter fullscreen mode Exit fullscreen mode
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");    
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

$uploadFolderPath = "uploadedFile/";
$uploadedFile_tmp = $_FILES['uploadedFile']['tmp_name'];
$uploadedFile_ext = strtolower(end(explode('.',$_FILES['uploadedFile']['name'])));
$uploadedFile = $uploadFolderPath . uniqid() . '.'.$uploadedFile_ext;
move_uploaded_file($uploadedFile_tmp, $uploadedFile);

?>

Use the following commands to start the demo Angular application and kickstart the PHP server:

ng serve
php -S localhost:8001
Enter fullscreen mode Exit fullscreen mode

**

Conclusion

In this article, I showed how to set up file upload in Angular 13 in just a few simple steps:

  1. Create an Angular app and import modules
  2. Create the file upload form
  3. Add a PHP file for upload and start the server

I hope this will help you enable user file uploads in your Angular apps. Happy coding!

Top comments (0)