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
Laravel 9 Group By Query Example
Laravel 9 Group By Query Examp...

In this article, we will see laravel 9 group by query example. how to use group by in laravel 9. As you might expec...

Read More

Mar-29-2022

Laravel tips DB Models and Eloquent - Part 3
Laravel tips DB Models and Elo...

Welcome back to the third installment of our series on Laravel tips for database models and Eloquent. If you've been...

Read More

Oct-16-2023

How To Auto Select Country Using IP Lookup In jQuery
How To Auto Select Country Usi...

In this article, we will see how to auto select a country using IP lookup in jquery. Here, we will learn about auto...

Read More

May-15-2023

7 Easy Steps: Create Laravel 10 Livewire CRUD Operation
7 Easy Steps: Create Laravel 1...

Hey there! I'm diving into the world of Laravel 10 and Livewire, and I'm excited to share a step-by-step guide o...

Read More

Dec-06-2023