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
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

How To Drop Foreign Key In Laravel 10 Migration
How To Drop Foreign Key In Lar...

In this article, we will explore the process of removing foreign key constraints in Laravel 10 migrations. We will delve...

Read More

Apr-28-2023

Laravel 11 Livewire Toastr Notification
Laravel 11 Livewire Toastr Not...

Hello, laravel web developers! In this article, we'll see how to add toastr notification in livewire laravel 11. Her...

Read More

May-31-2024

How To Use Image Intervention In Laravel 9
How To Use Image Intervention...

In this article, we will see how to use image intervention in laravel 9. Here, we will learn about image intervention an...

Read More

Feb-13-2023