How to Image Upload with Preview in Angular 17

Websolutionstuff | Apr-01-2024 | Categories : Angular

In this article, we'll see how to image upload with a preview in angular 17. Here, we'll learn about the angular 17 upload image with a preview of the image. For this, we'll set angular 17 to create components and also create an API to upload images.

In this guide, we'll create a reactive form using a form group and on the change event, we'll add the image file to the form group element. Then click on the submit button we'll call the API to store the image on the server.

Step-by-Step Guide to Image Upload with Preview in Angular 17

image_upload_angular_17

Step 1: Create Angular 17 Project

In this step, we'll create an angular 17 application with the following command.

ng new angular-17-image-upload

 

Step 2: Create Image Upload Component

Then, we'll create an ImageUpload composer using the following command.

ng g c ImageUpload

Next, update the component ts file and HTML file:

src/app/image-upload/image-upload.component.ts

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
  
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { FormGroup, FormControl, Validators } from '@angular/forms';
  
import { HttpClientModule, HttpClient } from '@angular/common/http';
  
@Component({
  selector: 'app-image-upload',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule, HttpClientModule],
  templateUrl: './image-upload.component.html',
  styleUrl: './image-upload.component.css'
})
export class ImageUploadComponent {
  
  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(){
    console.log(this.myForm.value);
    this.http.post('http://localhost:8000/upload.php', this.myForm.value)
      .subscribe(res => {
        console.log(res);
        alert('Uploaded Successfully.');
      })
  }
  
}

 

 

Then, we'll update our HTML file. In this, we'll create a simple form for uploading images and add a submit button.

src/app/image-upload/image-upload.component.html

<h1>How to Image Upload with Preview in Angular 17 - Websolutionstuff</h1>
     
<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">
            <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">
        <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">
            <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">
          
    <button class="btn btn-primary" [disabled]="myForm.invalid" type="submit">Submit</button>
</form>

 

Step 3: Import Component

Now, we'll import the previously created ImageUploadComponent to the app.component.ts file.

src/app/app.component.ts

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
  
import { ImageUploadComponent } from './image-upload/image-upload.component';
  
@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, RouterOutlet, ImageUploadComponent],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'image-app';
}

 

Step 4: Use New Component

In this step, we'll use the component in the HTML file.

src/app/app.component.html

<app-image-upload></app-image-upload>

 

 

Step 5: Create API Endpoint

Next, we'll create an API file using PHP. So, create an upload.php file with an upload folder and run with a different port.

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 6: Run Angular App

Now, we'll run the angular 17 application using the following command.

ng serve

Run PHP API:

php -S localhost:8000
 

You might also like:

Recommended Post
Featured Post
Getting Started with Laravel in CodeLobster IDE
Getting Started with Laravel i...

Laravel is probably one of the most promoted PHP frameworks at the moment. It has a huge team and an excellent knowledge...

Read More

Jan-16-2022

CRUD Operation In PHP
CRUD Operation In PHP

In this tutorial, I will show you how to create a CRUD operation with login-logout in PHP. So, if you are a newcomer in...

Read More

Jul-20-2020

Laravel 8 Eloquent whereHas Condition
Laravel 8 Eloquent whereHas Co...

In this example we will see laravel 8 eloquent whereHas() condition. you will learn about wherehas() condition in l...

Read More

Oct-06-2021

How To Store JSON Data In Database Laravel 9
How To Store JSON Data In Data...

In this article, we will see how to store JSON data in the database laravel 9. Laravel 9 stores JSON data in M...

Read More

Sep-28-2022