How to upload and display image using Angular 8

Introduction

In this tutorial we will upload and display image using Angular. In this example we will allow to upload only single image and display the uploaded image on the web page. We have seen how to upload file using Angular, but here we are uploading and displaying the image.

Prerequsites

Knowledge of Angular

Setup Project

Read tutorial Create new Angular project on Windows before proceeding further.

Create a project called angular-image-upload-display anywhere on the disk space on your computer system.

Once your project downloads the necessary libraries, make sure your newly created project compiles and opens in browser successfully. To check this navigate to the directory angular-image-upload-display and execute the following command:

ng serve --open

So you will see that a browser gets opened with URL http://localhost:4200.

Now stop the server and create the required code for uploading and displaying the image using Angular.

Image Upload Form

Edit the app.component.html file to create the file upload form using Angular:

<div style="text-align:center">
	<div [innerHtml]='msg' *ngIf="msg" style="color: red;"></div>
	<div><img [src]="url" *ngIf="url"></div>
	<p>
		<input type="file" (change)="selectFile($event)">
	</p>
</div>

We have two <div/>s and one <p/> with <input> type file.

The first <div/> shows error message and second <div/> has the <img> tag to display image once an image successfully uploaded.

<input> is used to select the file for uploading and on change event the selectFile($event) function gets called.

File Upload Component

Edit app.component.ts and paste the below source code:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {	
	url;
	msg = "";
	
	selectFile(event) {
		if(!event.target.files[0] || event.target.files[0].length == 0) {
			this.msg = 'You must select an image';
			return;
		}
		
		var mimeType = event.target.files[0].type;
		
		if (mimeType.match(/image\/*/) == null) {
			this.msg = "Only images are supported";
			return;
		}
		
		var reader = new FileReader();
		reader.readAsDataURL(event.target.files[0]);
		
		reader.onload = (_event) => {
			this.msg = "";
			this.url = reader.result; 
		}
	}
}

We have basic validation, such as, whether file has been selected for upload and whether the selected file is only image type or not.

Next we create FileReader object and read the file data as URL.

Finally we render the image with onload event.

Testing the Application

When you run the application, you will get screen at URL http://localhost:4200 and you can try yourself to upload and display the image.

Source Code

Download

Thanks for reading.

Leave a Comment