How To Image Upload With Preview In Angular 15

Websolutionstuff | Jun-16-2023 | Categories : Angular

In today's world of web development, being able to upload images with a preview feature is a common requirement for many projects. As an Angular developer, I understand the importance of providing a seamless user experience when it comes to image uploads. That's why I'm excited to share this step-by-step guide on implementing image upload functionality with a preview feature in Angular 15.

Throughout this tutorial, I will guide you through the process of creating an Angular 15 component that empowers users to select an image file from their device and immediately preview it on the screen.

This real-time preview functionality allows users to visually confirm their selection before proceeding with the upload, minimizing errors and enhancing overall user satisfaction.

Together, we will leverage the power of Angular 15 and its extensive toolset to build a robust image upload solution. We will cover everything you need to know, from setting up the project to creating the necessary components, handling file selection events, displaying the image preview, and adding stylish visual elements.

By the end of this guide, you will have gained the skills and knowledge to implement image upload functionality with a preview feature in Angular 15.

With this valuable expertise, you'll be able to enhance your web applications, provide an intuitive image upload experience, and impress your users with a seamless and interactive process.

So, let's dive in and discover the secrets of image uploads with previews in Angular 15 together.

Step 1: Set Up a New Angular 15 Project

Start by creating a new Angular 15 project using the Angular CLI.

ng new image-upload-app

 

Step 2: Import Module

In this step, we will import the necessary modules, HttpClientModule, FormsModule, and ReactiveFormsModule, into the app.module.ts file. These modules are essential for handling HTTP requests and enabling reactive forms in our Angular application.

src/app/app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
	ReactiveFormsModule,
	HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
 
Step 3: Add HTML Markup

In the app.component.html file add the necessary HTML markup for the image upload form.

src/app/app.component.html

<div class="container mt-5">
	<div class="card">
		<div class="card-header">
			<strong>How To Image Upload With Preview In Angular 15 - Websolutionstuff</strong>
		</div>
		<div class="card-body">
			<form [formGroup]="myForm" (ngSubmit)="submit()">       
				<div class="form-group">
					<label for="name">Name:</label>
					<input formControlName="name" id="name" type="text" class="form-control">
					<div *ngIf="f['name'].touched && f['name'].invalid" class="alert alert-danger mt-1">
						<div *ngIf="f['name'].errors && f['name'].errors['required']">Name is required.</div>
						<div *ngIf="f['name'].errors && f['name'].errors['minlength']">Name should be 3 character.</div>
					</div>
				</div>
				  
				<div class="form-group mt-2">
					<label for="file">File:</label>
					<input formControlName="file" id="file" type="file" class="form-control" (change)="onFileChange($event)">
					<div *ngIf="f['file'].touched && f['file'].invalid" class="alert alert-danger mt-1">
						<div *ngIf="f['file'].errors && f['file'].errors['required']">File is required.</div>
					</div>
				</div>				
				<img [src]="imageSrc" *ngIf="imageSrc" style="height: 300px; width:500px"><br>
				<button class="btn btn-primary mt-2" [disabled]="myForm.invalid" type="submit">Submit</button>
			</form>		  
		</div>
	</div>	
</div>

 

Step 4: Implement the Image Upload Logic

In the app.component.ts file, implement the logic to handle the file selection and preview.

src/app/app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
	imageSrc: string = '';
	 /*------------------------------------------
  --------------------------------------------
  Declare form
  --------------------------------------------
  --------------------------------------------*/
  myForm = new FormGroup({
    name: new FormControl('', [Validators.required, Validators.minLength(3)]),
    file: new FormControl('', [Validators.required]),
    fileSource: new FormControl('', [Validators.required])
  });
  
  /*------------------------------------------
  --------------------------------------------
  created constructor
  --------------------------------------------
  --------------------------------------------*/
  constructor(private http: HttpClient) { }
  
  /**
   * Write code on Method
   *
   * @return response()
   */
  get f(){
    return this.myForm.controls;
  }
  
  /**
   * Write code on Method
   *
   * @return response()
   */
  onFileChange(event:any) {
    const reader = new FileReader();
    
    if(event.target.files && event.target.files.length) {
      const [file] = event.target.files;
      reader.readAsDataURL(file);
    
      reader.onload = () => {
   
        this.imageSrc = reader.result as string;
     
        this.myForm.patchValue({
          fileSource: reader.result as string
        });
   
      };
   
    }
  }
  
  /**
   * Write code on Method
   *
   * @return response()
   */
  submit(){    
    this.http.post('http://localhost:8000/upload.php', this.myForm.value)
      .subscribe(res => {
        console.log(res);
        alert('Uploaded Successfully.');
      })
  }
}

Now that we have implemented the image upload functionality with a preview feature in our Angular application, we need to create an API file using PHP to handle the actual upload and storage of the images.

In this step, we will create an upload.php file that will be responsible for receiving the uploaded image file and saving it to a designated "upload" folder.

upload.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);
      
    $image_parts = explode(";base64,", $request->fileSource);
      
    $image_type_aux = explode("image/", $image_parts[0]);
      
    $image_type = $image_type_aux[1];
      
    $image_base64 = base64_decode($image_parts[1]);
      
    $file = $folderPath . uniqid() . '.png';
      
    file_put_contents($file, $image_base64);
  
?>

 

Step 5: Test the Image Upload

Start the Angular development server using the ng serve command and open the app in your browser. Try selecting an image file using the file input field. The selected image should be displayed in the preview area.

ng serve

To run the PHP file on a different port, you can use a PHP development server. Open your terminal or command prompt, navigate to the directory where the upload.php file is located, and run the following command.

php -S localhost:8000

Now, in your Angular application, make sure to update the API URL in your image upload component to point to the correct port and file.

 

Step 6: Conclusion

By following this step-by-step guide, you have successfully implemented image upload functionality with a preview feature in Angular 15. Users can now select an image file, preview it before uploading, and enjoy a seamless image upload experience.

how-to-image-upload-with-preview-in-angular-15

 


You might also like:

Recommended Post
Featured Post
How To Validate Password And Confirm Password Using JQuery
How To Validate Password And C...

In this article, we'll explore a simple way to validate passwords and confirm passwords using jQuery. Password valid...

Read More

Sep-02-2020

How to Install Zoom in Ubuntu 22.04 using Terminal
How to Install Zoom in Ubuntu...

Greetings Ubuntu enthusiasts! If you're ready to dive into the world of video conferencing on your Ubuntu 22.04...

Read More

Jan-19-2024

Laravel 9 Socialite Login with Facebook Account
Laravel 9 Socialite Login with...

In this article, we will see laravel 9 socialite login with a facebook account. Many websites provide different typ...

Read More

Apr-16-2022

Localization - Laravel Localization Example
Localization - Laravel Localiz...

In this article, we will see localization - laravel localization example. Laravel's localization features provide a...

Read More

Nov-06-2020