File Upload Example using Angular

Introduction

In this tutorial we will see file upload example using Angular. This is a UI side coding example using Angular. It will not upload file definitely but you need to use server side programming to actually upload the file.

Prerequisites

Knowledge of Angular

Create new Angular project on Windows.

Example with Source Code

Setting up Angular project

Create a project called upload-angular anywhere on the physical drive folder by executing the following command in cmd window:

ng new upload-angular

Once your project downloads the necessary libraries, make sure your newly created project compiles and opens in browser successfully. To check this navigate to the directory upload-angular and execute the following command:

ng serve --open

Now stop the server and create the required code for file upload for UI side using Angular.

All the required files and structures will be created by the ng command and you need to mainly edit those files. You need to create only a service class additionally as shown in the below source code.

To know more about Angular style guide, check it here.

Creating File Upload Form

Edit the app.component.html file to create the file upload form using Angular:

<div style="text-align:center">
	<label>
		<input type="file" (change)="selectFile($event)">
		</label>
		<button [disabled]="!selectedFiles" (click)="upload()">Upload</button>
</div>

In the above html form the button is disabled if no file is selected and it is determined on the basis of function selectFile($event).

On clicking on the button, the upload() function gets called and file will be uploaded using the server side code.

Creating File Upload Service

Create below file.service.ts file that will serve the upload of the file to the server:

import {Injectable} from '@angular/core';
import {HttpClient, HttpRequest, HttpEvent} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';

@Injectable({ providedIn: 'root' })
export class FileService {

  constructor(private http: HttpClient) {}

  uploadFile(file: File): Observable<HttpEvent<{}>> {
		const formdata: FormData = new FormData();
		formdata.append('file', file);
		const req = new HttpRequest('POST', 'http://localhost:8085/upload', formdata, {
			  reportProgress: true,
			  responseType: 'text'
		});
	
		return this.http.request(req);
   }
   
}

In the above FileService class we have defined the uploadFile() method, which is called from AppComponent class as shown in the below code section.

The URL specified in the uploadFile() method is the server side REST URL, that is responsible for uploading the file into server.

Creating File Upload Component

Edit app.component.ts and paste the below source code:

import { Component } from '@angular/core';
import { FileService } from './file.service';
import { HttpClient, HttpResponse, HttpEventType } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
	selectedFiles: FileList;
	currentFile: File;

    constructor(private fileService: FileService) {}
	
  selectFile(event) {
    this.selectedFiles = event.target.files;
  }
  
  upload() {
    this.currentFile = this.selectedFiles.item(0);
    this.fileService.uploadFile(this.currentFile).subscribe(event => {
     if (event instanceof HttpResponse) {
        console.log('File is completely uploaded!');
      }
    });
    this.selectedFiles = undefined;
  }
}

In the AppComponent class we have defined upload method that is called from the html form when clicked on the button.

Testing the Application

When you run the application, you will get below home page screen:

file upload example using Angular

When you select a file using a browse button, the upload button will be enabled but you won’t be able to upload the file if your server side code is not there for uploading file to the server:

file upload example using Angular

You can have a look at the tutorial on Angular + Spring Boot file upload example, where Spring Boot will be used as a server side code for uploading file to the server.

Source Code

You can download source code.

Thanks for reading.

File Upload Example using Angular

Leave a Reply

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

Scroll to top