Share and Learn To Write Code!

Programming articles, which help you to build your application. If something you are stuck to code and complete the program, just find here your question-related articles.

Share with   

How to upload and preview image in angular 8 javascript framework

We are going to preview selected image at time of add image operation in angular 8 web app.
image upload   angular   javascript   angular 7   angular 8  

Image Upload & Preview in Angular 8


We need image upload program code for upload image for gallary view or anything that time its help to what we are selecting image from the local storage i.e. my computer. We are going to make this using angular 8 javascript framework.


Prerequisite

  1. Node JS. To install node js please click here.
  2. Angular CLI to install angular cli in your system follow this article.


Example for upload and preview image in angular 8


1) Create Angular App. If you dont know how to start with angular. Follow this article How to install angular 8 in windows operating system.


2) Add this image upload code to app.component.html file

// src > app > app.component.html

<hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>

<!-- This is for preview Image -->
<img [src]="url" height="200"> <br/>

<!-- This is for upload Image -->
<input type='file' (change)="onSelectFile($event)">


3) Add this typescript code to app.component.ts file

// src > app > app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})

export class AppComponent  {
  name = 'Angular 8';
  url = '';
  onSelectFile(event) {
    if (event.target.files && event.target.files[0]) {
      var reader = new FileReader();
      reader.readAsDataURL(event.target.files[0]); // read file as data url
      reader.onload = (event) => { // called once readAsDataURL is completed
        this.url = event.target.result;
      }
    }
  }
}


Above code is used to get file and read file to preview image.


In that code FileReader() method is used for read the selected file.


readAsDataURL is method to read the get the base 64 image string


onload is method to preview this base 64 image to html view part.


Output of the above program



After choose file you will be see image preview above the choose file option


0replies
Leave a reply
46
Registerd Users
87
Total Subscribers
59
Total Articles
38906
Total Views