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 10 Delete Multiple Records Using Checkbox
Laravel 10 Delete Multiple Rec...

In this article, we will see laravel 10 delete multiple records using the checkbox. Here, we will learn about how to del...

Read More

Mar-03-2023

How to Install Composer on Ubuntu 22.04
How to Install Composer on Ubu...

Hey there! If you're diving into the world of PHP development on your Ubuntu 22.04 machine, you'll likely come a...

Read More

Jan-10-2024

How to Downgrade PHP 8.2 to 8.1 in Ubuntu
How to Downgrade PHP 8.2 to 8....

Hey there, I recently found myself in a situation where I needed to downgrade my PHP version from 8.2 to 8.1 on my Ubunt...

Read More

Nov-01-2023

Laravel 8 One To Many Polymorphic Relationship
Laravel 8 One To Many Polymorp...

In this tutorial we will learn about laravel 8 one to many polymorphic relationship. A one-to-many polymorphic rela...

Read More

Nov-19-2021