Tuesday, October 8, 2024
Google search engine
HomeLanguagesAngularAngular 16 Image Upload Preview Tutorial

Angular 16 Image Upload Preview Tutorial

Image upload with preview in angular 16 projects; Throughout this tutorial, you will learn how to upload image with preview in a database using the HttpClient module & web rest API with angular 16 projects.

Image Upload with Preview in Angular 16

Steps to upload image with preview in the database with angular 16 using HttpClient module & web rest apis:

  • Step 1: Set up a new Angular project
  • Step 2: Create the Image Upload with Preview Component
  • Step 3: Create the Image Upload with Preview Component Template
  • Step 4: Implement Image Upload Logic
  • Step 5: Style the Image Upload Component (Optional)
  • Step 6: Integrate the Image Upload with Preview Component
  • Step 7: Run the Application

Step 1: Set up a new Angular project

Open your cmd (command prompt) and execute the following commands to install and create a new Angular project and navigate into the project directory:

ng new image-upload-preview
cd image-upload-preview

Step 2: Create the Image Upload with Preview Component

Next, open again your command prompt or cmd to create a new component to handle image uploading:

ng generate component image-upload

Step 3: Create the Image Upload with Preview Component Template

Once you have created a new component named image-upload by using the above-given command, Now you need to open the image-upload.component.html file and add the following code:

<div class="image-upload-container">
  <input type="file" (change)="onFileSelected($event)" accept="image/*">
  <div *ngIf="imageUrl" class="image-preview">
    <img [src]="imageUrl" alt="Preview">
  </div>
  <button *ngIf="selectedImage" (click)="onUpload()">Upload Image</button>
</div>

Step 4: Implement Image Upload Logic

Next, you need to implement image upload logic. So, Open the image-upload.component.ts file and add the following code:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-image-upload',
  templateUrl: './image-upload.component.html',
  styleUrls: ['./image-upload.component.css']
})
export class ImageUploadComponent {
  selectedImage: File | null = null;
  imageUrl: string | ArrayBuffer | null = null;

  constructor(private http: HttpClient) {}

  onFileSelected(event: Event): void {
    const inputElement = event.target as HTMLInputElement;
    const file = (inputElement.files as FileList)[0];

    if (file) {
      this.selectedImage = file;
      this.previewImage(file);
    }
  }

  previewImage(file: File): void {
    const reader = new FileReader();
    reader.readAsDataURL(file);

    reader.onload = () => {
      this.imageUrl = reader.result;
    };
  }

  onUpload(): void {
    if (!this.selectedImage) {
      console.log('Please select an image before uploading.');
      return;
    }

    const formData = new FormData();
    formData.append('image', this.selectedImage);

    this.http.post<any>('http://localhost:5000/upload', formData).subscribe(
      (response) => {
        console.log(response.message);
        this.resetForm();
      },
      (error) => {
        console.error('Image upload failed:', error);
      }
    );
  }

  resetForm(): void {
    this.selectedImage = null;
    this.imageUrl = null;
  }
}

Step 5: Style the Image Upload Component (Optional)

You can style the image-upload.component.css file as per your application’s design to make it more visually appealing. So, Open the image-upload.component.css file and add some basic styling:

.image-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
}

.image-preview {
  margin-top: 20px;
}

img {
  max-width: 100%;
  max-height: 300px;
}

Step 6: Integrate the Image Upload with Preview Component

Next, you need to import image upload component in app.component.html file.

So, Open the app.component.html file and add the following code:

<div class="app-container">
  <h1>Image Upload with Preview in Angular 16 Projects</h1>
  <app-image-upload></app-image-upload>
</div>

Step 7: Run the Application

Finally, you can run your application using Angular CLI:

ng serve

Visit http://localhost:4200 in your web browser to see the application running. Now you should have a functional image upload with preview feature in your Angular application!

Conclusion

Congratulations! You have successfully learned how to implement an image upload functionality with a preview feature in your Angular 16 application.

Recommended Tutorials

RELATED ARTICLES

Most Popular

Recent Comments