Angular Multiple File Upload Example

In this article, I will show you how to upload Multiple file in Angular. We will see Angular multiple file upload with an example. Now let’s start how to implement Angular Multiple File upload step by step.

We will use Angular Reactive Form for Angular Multiple File Upload and we will also create API server to store file using PHP.

Steps to implement Angular Multiple File Upload

Create New App

Create new angular project using the following command

ng new angular-file-upload-example

Update Module

Now we will import required module for Angular Multiple File upload example as shown in below snippet in app.module.ts.

app.module.ts


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

import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';

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

Update Component

Now update the component file, to generate reactive form and send files to api.

app.component.ts


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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  title = 'Angular Multiple File Upload Example';
  successMessage: string = '';
  uploadFiles: string[] = [];
  uploadForm: FormGroup;
  constructor(private http: HttpClient) {
    this.initForm();
  }

  initForm() {
    this.uploadForm = new FormGroup({
      file: new FormControl('', [Validators.required]),
    });
  }
  onFileChange(event: any) {
    for (var i = 0; i < event.target.files.length; i++) {
      this.uploadFiles.push(event.target.files[i]);
    }
  }
  save() {
    const formData = new FormData();
    for (var i = 0; i < this.uploadFiles.length; i++) {
      formData.append('file[]', this.uploadFiles[i]);
    }
    this.http
      .post('http://localhost:8000/upload.php', formData)
      .subscribe(() => {
        this.successMessage = 'Uploaded Successfully';
      });
  }
}

Here in the above snippet we are calling onFileChange() function when someone click on input file. which will open popup to upload multiple files. and when user submit the form it will call save() method which will call api with formData as shown in above code.

Update View

We will update the view to allow user to upload multiple files which we can send to PHP server.

app.component.html


<div class="container pt-5">
  <div class="col-md-4">
    <h2>{{ title }}</h2>

    <form [formgroup]="uploadForm" (ngsubmit)="save()">
      <div class="form-group">
        <input formcontrolname="file" id="file" type="file" multiple="" class="form-control" (change)="onFileChange($event)">
        <div *ngif="
            uploadForm.get('file')?.touched && uploadForm.get('file')?.invalid
          " class="alert alert-danger">
        
          <div class="mt-2" *ngif="
              uploadForm.get('file')?.errors &&
              uploadForm.get('file')?.errors?.['required']
            ">
            File is required.
          </div>
        </div>
      </div>

      <button class="btn btn-primary mt-4" [disabled]="uploadForm.invalid" type="submit">
        Submit
      </button>
    </form>
  </div>
</div>

Once you are done with this, you can run angular project using ng serve command.

Output

and it will show output as shown in below image.

Angular Multiple File Upload Example

It will show the following validation error if no file selected. that’s because we have set validation in view file.

Angular Multiple File Upload Example

PHP API Setup

Now out client project is ready to upload multiple files in Angular. Now we will setup server which will accept files and upload it somewhere.

Let’s create upload.php which will store all files to upload folder.

upoad.php


<?php
  
    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");
        
    $folderPath = "upload/";
      
    $file_names = $_FILES["file"]["name"];
    for ($i = 0; $i < count($file_names); $i++) {
        $file_name=$file_names[$i];
        $extension = end(explode(".", $file_name));
        $original_file_name = pathinfo($file_name, PATHINFO_FILENAME);
        $file_url = $original_file_name . "-" . date("YmdHis") . "." . $extension;
        move_uploaded_file($_FILES["file"]["tmp_name"][$i], $folderPath . $file_url);
    }
  
?>

To run php project run the following command

php -S localhost:8000

and navigate to browser and open client project and now you are ready to upload multiple files in angular.

That’s it. I hope you like this article.


Also Read: