Angular Multiple Image Upload with Preview Example

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

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

Steps to implement Angular Multiple Image Upload with Preview

Create New App

Create new angular project using the following command

ng new angular-image-upload-example

In this example I have used bootstrap styling. If you want you can use in your project to by following this guide Install Bootstrap in Angular

Update Module

Now we will import required module for Angular Images 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 images to php 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 Image Upload Example';
  successMessage: string = '';
  images: string[] = [];
  uploadForm: FormGroup;
  constructor(private http: HttpClient) {
    this.initForm();
  }
  initForm() {
    this.uploadForm = new FormGroup({
      file: new FormControl('', [Validators.required]),
    });
  }
  onFileChange(event: any) {
    if (event.target.files && event.target.files[0]) {
      var filesAmount = event.target.files.length;
      for (let i = 0; i < filesAmount; i++) {
        var reader = new FileReader();
        reader.onload = (event: any) => {
          console.log(event.target.result);
          this.images.push(event.target.result);
          this.uploadForm.patchValue({
            fileSource: this.images,
          });
        };
        reader.readAsDataURL(event.target.files[i]);
      }
    }
  }
  save() {
    this.http
      .post('http://localhost:8000/upload.php', this.uploadForm.value)
      .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 Images. 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 Images 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>
      <div class="pt-4 d-flex">
        <div *ngfor="let url of images">
          <img class="image-preview" [src]="url">
          <br>
        </div>
      </div>
      <button class="btn btn-primary mt-4" [disabled]="uploadForm.invalid" type="submit">
        Submit
      </button>
    </form>
  </div>
</div>

Update CSS Style


 .image-preview {
  box-shadow: 0 1px 3px rgb(0 0 0 / 8%), 0 4px 8px rgb(0 0 0 / 4%);
  border: 1px solid #ccc;
  border-radius: 8px;
  margin-left: 10px;
  display: block;
  max-width: 230px;
  max-height: 155px;
  width: auto;
  height: auto;
}

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 Image Upload with Preview Example

When you will upload images in Angular it will preview as shown in below image.

Angular Multiple Image Upload with Preview

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

Angular Multiple Image Upload with Preview Example

PHP API Setup

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

Let’s create upload.php which will store all images 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/";
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
   
foreach ($request->fileSource as $key => $value) {
   
    $image_parts = explode(";base64,", $value);
   
    $image_type_aux = explode("image/", $image_parts[0]);
   
    $image_type = $image_type_aux[1];
  
    $image_base64 = base64_decode($image_parts[1]);
  
    $file = $folderPath . uniqid() . '.'.$image_type;
  
    file_put_contents($file, $image_base64);
}

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 images in angular.

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


Also Read :