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

Setting up Angular project

Please make sure you go through the tutorial how to create new Angular project on Windows.

Create a project called upload-angular in your desired directory 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.

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.

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 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.

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.

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

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:

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.

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

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