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

Please read tutorial Create new Angular project on Windows before proceeding further.

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 angular-file-upload

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 angular-file-upload 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">
	<div [innerHtml]='msg'></div>
	<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.

A div with id msg will show message after file upload.

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', '<Server URL of the file 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.

We are assuming that the server URL sends text response after file upload operation. If you need different response type then you can change the responseType value.

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 { 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(response => {
		this.selectedFiles.value = '';
     if (response instanceof HttpResponse) {
		 this.msg = response.body;
        console.log(response.body);
      }	  
    });    
  }
}

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

The method upload() will call uploadFile() method in service and finally reset the upload field and will show the message into the msg div.

Updating app.module.ts

Make sure you update the app.module.ts file to include HttpClientModule.

The complete source code for the file is shown below:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
	HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

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.

Let’s say we have uploaded log.txt file, then you will see success message as follows:

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

download source code

Thanks for reading.

1 thought on “File Upload Example using Angular

Leave a Reply

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