Angular 11 Image Upload and Preview Tutorial Example

In this angular 11 image upload and preview example, we will profoundly ascertain how to upload an image and preview the uploaded image in an angular app using the JavaScript FileReader object and Angular Reactive forms.

Ideally, FileReader API is used to upload image in Angular 11; furthermore, you can create image previews for file uploads using this File Api. Similarly, if you are working on vanilla JavaScript, then you go with the FileReader object.

Theoretically, whether it is a single image or multiple, images you can create image uploading and show preview in angular with File API.

Here are the quick overview of this immaculate tutorial; we will install a basic angular app and configure Reactive forms in angular. To create a simple file upload and preview form, we will set an onChange event to the input field. This event will invoke the file uploading method when the user uploads an image; after uploading the image file, we will show an image preview in our angular demo app.

Install Angular App

We assume you have already set up node and npm tools on your system, head over to console and use the following command to install angular cli tool:

npm install -g @angular/cli

Next, execute command to create a new angular app:

ng new ng-demo-app

Get inside the application folder:

cd ng-demo-app

Add Forms Module

This step guides on how to add reactive forms module in angular app. Consequently, open the app.module.ts file and import FormsModule and ReactiveFormsModule from ‘@angular/forms’ package, furthermore also add these modules in imports array:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { HttpClientModule } from '@angular/common/http'; 
import { ReactiveFormsModule, FormsModule } from '@angular/forms';


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

export class AppModule { }

Implement Image Upload and Preview

Let us start implementing image upload and preview in angular, create a basic file upload form, which mainly contains an input field and image tag, which will display the upload image preview.

Open and update the code in app.component.html file:

<form [formGroup]="uploadForm" (ngSubmit)="upload()">

  <div class="preview" *ngIf="imgFile">
    <img [src]="imgFile" style="width:400px; height:250px">
  </div>

  <div class="form-group">
    <label for="name">File Name</label>
    <input class="form-control" id="file" formControlName="file" type="text">
    <div *ngIf="uf.name.touched && uf.name.invalid" class="alert alert-danger">
      <div *ngIf="uf.name.errors.required">Name is required.</div>
    </div>
  </div>

  <div class="form-group">
    <label for="file">File</label>
    <input type="file" class="form-control" id="file" formControlName="file" (change)="onImageChange($event)">
    <div *ngIf="uf.file.touched && uf.file.invalid" class="alert alert-danger">
      <div *ngIf="uf.file.errors.required">Image file is required.</div>
    </div>
  </div>

  <button class="btn btn-success" type="submit">Upload File</button>

</form>

Import the FormGroup, FormControl, Validators modules to deal with form values, onImageChange() methods is built with FileReader object, which mainly handles file uploading, whereas the upload() handles the file upload request; this method is empowered by HttpClient api.

Open and update the code in app.component.ts file:

import { Component } from '@angular/core';
import { FormGroup, Validators, FormControl } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
    
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {
  imgFile: string;

   uploadForm = new FormGroup({
    name: new FormControl('', [Validators.required]),
    file: new FormControl('', [Validators.required]),
    imgSrc: new FormControl('', [Validators.required])
  });
  
  constructor(private httpClient: HttpClient) { }
    
  get uf(){
    return this.uploadForm.controls;
  }
   
  onImageChange(e) {
    const reader = new FileReader();
    
    if(e.target.files && e.target.files.length) {
      const [file] = e.target.files;
      reader.readAsDataURL(file);
    
      reader.onload = () => {
        this.imgFile = reader.result as string;
        this.uploadForm.patchValue({
          imgSrc: reader.result
        });
   
      };
    }
  }
   
  upload(){
    console.log(this.uploadForm.value);
    this.httpClient.post('http://localhost:8888/file-upload.php', this.uploadForm.value)
      .subscribe(response => {
        alert('Image has been uploaded.');
      })
  }
}

Let us create the basic upload API using PHP, creating the php_api folder in your angular project, mainly at the root.

Secondly, create an upload folder in the php_api folder to store uploaded files; moreover, make a new file-upload.php in the php_api directory to handle the file uploading, and don’t forget to add the following code inside of it.

<?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");
      
    $folder = "upload/";
    $postdata = file_get_contents("php://input");
    $request = json_decode($postdata);
      
    $img = explode(";base64,", $request->fileSource);
      
    $img_aux = explode("image/", $img[0]);
      
    $image_type = $img_aux[1];
      
    $img_base64 = base64_decode($img[1]);
      
    $image = $folder . uniqid() . '.png';
      
    file_put_contents($image, $img_base64);
  
?>

Run Angular Project

You can run the angular app using ng command:

ng serve

To start the PHP File Upload API, use the suggested command on another terminal window:

php -S localhost:8888

Type the given url on the browser to check the image upload in angular:

http://localhost:4200

Conclusion

The angular image upload and preview tutorial is completed, now we have learned how how to upload an image and show upload image preview in angular with the help of reactive forms and JavaScript FileReader object.