Angular 17 Upload Image Example Tutorial

To upload an image in angular 17 using rest web APIs; Simply install and setup angular 17 application and create an image upload component and use rest web APIs with the HttpClient module to upload an image with components.

How to Upload Image in Angular 17 Application

A step-by-step guide to creating upload image functionality in angular 17 using the HttpClient module & web rest apis:

Step 1: Install and SetUp the New Angular Project

Open your cmd or terminal window and run ng new image-upload-app to install and create a new one using Angular CLI:

ng new image-upload-app
cd image-upload-app

Step 2: Build the Image Upload Component

To create a new component to handle image uploading; simply run the ng generate component image-upload command on cmd or terminal window:

ng generate component image-upload

Step 3: Create Image Upload Form

Navigate to project directory and open the image-upload.component.html file, and create image upload form into it, like following:

<div class="container">
    <div class="form-container">
        <h1>Angular 17 File Upload Tutorial Example - Tusmake.com</h1>

        <form [formGroup]="myForm" (ngSubmit)="submit()">

            <div class="form-group">
                <label for="file">File</label>
                <input
                    formControlName="file"
                    id="file"
                    type="file"
                    class="form-control"
                    (change)="onFileSelected($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>

            <button class="btn btn-primary" [disabled]="myForm.invalid" type="submit">Submit</button>
        </form>
    </div>
</div>

Step 4: Create TypeScript Code for Image Upload

Simply open image-upload.component.ts file and implement typescript code for image upload into it, like following:

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 {

  /*------------------------------------------
  --------------------------------------------
  Declare Form
  --------------------------------------------
  --------------------------------------------*/
  myForm = new FormGroup({
    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()
   */
  onFileSelected(event:any) {

    if (event.target.files.length > 0) {
      const file = event.target.files[0];
      this.myForm.patchValue({
        fileSource: file
      });
    }
  }

  /**
   * Write code on Method
   *
   * @return response()
   */
  submit(){
    const formData = new FormData();

    const fileSourceValue = this.myForm.get('fileSource')?.value;

    if (fileSourceValue !== null && fileSourceValue !== undefined) {
        formData.append('file', fileSourceValue);
    }

    this.http.post('http://127.0.0.1:3000/file-upload', formData)
      .subscribe(res => {
        console.log(res);
        alert('Uploaded Successfully.');
      })
  }
}

Step 5: Style the Image Upload Form Component (Optional)

You can style the image-upload.component.css file as per your application’s design to make it more visually appealing.

/* Styles for form container */
.form-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

/* Styles for form elements */
.form-group {
  margin-bottom: 20px;
}

label {
  font-weight: bold;
}

input[type="file"] {
  display: block;
  margin-top: 5px;
}

.alert {
  margin-top: 10px;
  padding: 10px;
  border-radius: 5px;
}

.alert-danger {
  color: #721c24;
  background-color: #f8d7da;
  border: 1px solid #f5c6cb;
}

/* Styles for the container */
.container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh; /* Use the full height of the viewport */
}

/* Styles for form container */
.form-container {
    width: 800px;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
    background-color: #fff;
}

/* Other styles remain the same */

Step 6: Import Image Upload Component to App Module

Simply app.component.ts file and import the ImageUploadComponent into it, like following:

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';
}

To add image upload html component in app.component.html:

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

Step 7: Run the Application

Run ng serve on cmd or terminal window to start angular application:

ng serve

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

Conclusion

In this tutorial, you learned how to implement image uploading in an Angular application using Angular’s HttpClient module.

Recommended Tutorials

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *