Angular 17 File Upload Tutorial with Example

To upload a file in Angular 17; Simply setup the Angular application and create a file upload component and implement the file upload functionality in components and then import this component into a main TypeScript file.

How to Upload a File in the Angular 17 Application

Here are steps to building file upload in angular 17 application:

Step 1: Install and SetUp the New Angular Project

Open your cmd or terminal window and run ng new file-upload-app to install and create a new one using Angular CLI to create angular project into your system:

ng new file-upload-app
cd file-upload-app

Step 2: Build the File Upload Component

Run ng generate component file-upload command on cmd or terminal window to create a new component to handle file uploading:

ng generate component file-upload

Step 3: Create File Upload Form

Navigate to project directory and open the file-upload.component.html file, and create file upload form into it, like the 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 File Upload

Simply open file-upload.component.ts file and implement typescript code for file 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-file-upload',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule, HttpClientModule],
  templateUrl: './file-upload.component.html',
  styleUrl: './file-upload.component.css'
})
export class FileUploadComponent {

  /*------------------------------------------
  --------------------------------------------
  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 File Upload Form Component (Optional)

You can style the file-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 File Upload Component to App Module

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

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';

import { FileUploadComponent } from './file-upload/file-upload.component';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, RouterOutlet, FileUploadComponent],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'file-app';
}

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

<app-file-upload></app-file-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 file upload feature in your Angular application!

Conclusion

In this tutorial, you learned how to implement file 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 *