Download File From Server Using Angular

Table of Contents

Download File – Angular

In this post I am going to show you how to download file from server using Angular framework. Angular is a UI (user Interface) framework for building rapid application development. Here I will use Angular 7/8/10/11/12/13/15 to download file from server side.

You can use any server side technology and integrate this example with it for downloading file from server. I am going to use here Spring Boot framework as a server side technology.

I will provide link as well as button, on which user will click and download the file from server. I will also show how to give end users Save as option while downloading file and how to display file content on the browser.

download file from server using angular

Related Posts:

Prerequisites

Angular 7/8/10/11/12/13/15, Node v11.3.0/v12.9.1/v12.16.3/v14.15.5/16.12.0-16.13.0/18.12.1, npm 6.4.1/6.10.2/6.14.4/6.14.11/8.1.0-8.1.3/8.19.2

Spring Boot REST API to download File

Install Modules

Install the required module for Angular 7/8/10/11/12/13/15: execute command npm install file-saver --save-dev (for 7/10)

download file angular

or npm install @types/file-saver --save-dev (for 11/12/13 version) in command line tool to install file-saver which is required for Save as option.

angular file download

or use the command npm i file-saver --save-dev for Angular version 15.

Install the required module for Angular 8: execute command npm install @angular/http@latest in command line tool.

Go through the following steps for creating Angular project to download file from server using Angular.

Project Setup

Go through the link Creating Angular Project to create a new project. Make sure you give the project name as angular-file-download.

If you are asked to confirm Routing and default StyleSheet type, then you can press y/CSS as answers as shown in below image:

angular download file server

For Angular 11, you will find another option to set whether you want to use stricter type or not. Here I am using stricter type and later I will show you how to use stricter type for response and error.

download file from server using angular

Now I will edit or add the required files under angular-file-download/src/app directory.

Remember the file extension ts (service.ts) indicates TypeScript, which is a file type.

Service Class

Service is one of fundamental blocks of every Angular application. Service is just a TypeScript class with or even without @Injectable decorator.

Once you create the service class you need to register it under app.module.ts file in providers array of @NgModule.

But here I won’t register in providers array of @NgModule, instead I will use @Injectable({providedIn: 'root'}) to register it for the whole application.

@Injectable is a decorator that has a property providedIn. root means that you want to provide the service at the root level (AppModule).

When the service is provided at root level, Angular creates a single, shared instance of service and injects into any class that needs it. Registering the provider in the @Injectable metadata also allows Angular to optimize an application by removing the service if it is not used.

Create service file by executing the command ng g s <service name>.

download file using angular

The below source code is written into file.service.ts file.

import {Injectable} from '@angular/core';
import {HttpResponse} from '@angular/common/http';
import {Http, ResponseContentType} from '@angular/http';
import {Observable} from 'rxjs';

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

  constructor(private http: Http) {}

  downloadFile(): Observable<HttpResponse<Blob>>{		
		return this.http.get('http://localhost:8080/employees/download', { responseType: ResponseContentType.Blob });
   }
   
}

For Angular 8, change the downloadFile() function as below:

downloadFile(): Observable<any>{
		return this.http.get('http://localhost:8080/employees/download', {responseType: ResponseContentType.Blob});
  }

Update for Angular 10/11/12/13/15:

import {Injectable} from '@angular/core';
import {HttpClient, HttpResponse} from '@angular/common/http';

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

  constructor(private http: HttpClient) {}

  downloadFile(): any {
		return this.http.get('http://localhost:8080/employees/download', {responseType: 'blob'});
  }
   
}

In the above service class I am using HTTP GET method to get the file content from the URL http://localhost:8080/employees/download.

Update for Angular 11/12/13/15:

If you are not using stricter type then your code should be working fine as it is working for Angular 10. If you are using stricter type then you need to make changes to the following lines in your src/app/app.component.ts file.

First replace the line this.fileService.downloadFile().subscribe(response => { by the following line:

this.fileService.downloadFile().subscribe((response: any) => {

Second replace the line }), error => console.log('Error downloading the file'), by the following line:

}), (error: any) => console.log('Error downloading the file'),

That’s it for Angular 11.

I am also accepting response as Blob (Binary Large Object). You may also specify any value from supporting values, such as, json, blob, arraybuffer, text. You can have a look for more details on response type.

Controller Class

You need controller class that handles request/response from clients or end users.

I will invoke the service class method in controller class for downloading file.

I have used three ways for downloading file – two ways for Save as functionality and one way to show the file content on browser itself.

The below code is written in app.component.ts file.

Let’s break up the lines inside the download() function.

let blob:any = new Blob([response.blob()], { type: 'text/json; charset=utf-8' });

The above line create a Blob object with file content in response and expecting the file of JSON type.

const url= window.URL.createObjectURL(blob);
window.open(url);

The above two lines create a URL that will open the file in browser in new window. The above line shows the file content on browser, so it does not give you save as option.

fileSaver.saveAs(blob, 'employees.json');

The above line uses ready-made FileSaver module that will open the file with Save as option.

window.location.href = response.url

The above line gives you Save as option but it may not work for Angular 11.

import { Component } from '@angular/core';
import { FileService } from './file.service';
import * as fileSaver from 'file-saver';
import { HttpResponse } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular File Download';
  
  constructor(private fileService: FileService) {}
  
  download() {
    this.fileService.downloadFile().subscribe(response => {
			//let blob:any = new Blob([response.blob()], { type: 'text/json; charset=utf-8' });
			//const url= window.URL.createObjectURL(blob);
			//window.open(url);
			window.location.href = response.url;
			//fileSaver.saveAs(blob, 'employees.json');
		}), error => console.log('Error downloading the file'),
                 () => console.info('File downloaded successfully');
  }
  
}

Update for Angular 10:

import { Component } from '@angular/core';
import { FileService } from './file.service';
import * as fileSaver from 'file-saver';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular File Download';
  
  constructor(private fileService: FileService) {}
  
  download() {
    this.fileService.downloadFile().subscribe(response => {
			let blob:any = new Blob([response], { type: 'text/json; charset=utf-8' });
			const url = window.URL.createObjectURL(blob);
			//window.open(url);
			//window.location.href = response.url;
			fileSaver.saveAs(blob, 'employees.json');
		}), error => console.log('Error downloading the file'),
                 () => console.info('File downloaded successfully');
  }
  
}

For Angular 11 and 12 with Stricter Type:

import { Component } from '@angular/core';
import { FileService } from './file.service';
import * as fileSaver from 'file-saver';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular File Download';
  
  constructor(private fileService: FileService) {}
  
  download() {
    //this.fileService.downloadFile().subscribe(response => {
		this.fileService.downloadFile().subscribe((response: any) => { //when you use stricter type checking
			let blob:any = new Blob([response], { type: 'text/json; charset=utf-8' });
			const url = window.URL.createObjectURL(blob);
			//window.open(url);
			//window.location.href = response.url;
			fileSaver.saveAs(blob, 'employees.json');
		//}), error => console.log('Error downloading the file'),
		}), (error: any) => console.log('Error downloading the file'), //when you use stricter type checking
                 () => console.info('File downloaded successfully');
  }
  
}

For Angular 13/15:

You can use the following code in Angular 13/15:

import { Component } from '@angular/core';
 
import { FileService } from './file.service';
import { saveAs } from 'file-saver';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 
	title = 'Angular File Download From Server';

	constructor(private fileService: FileService) {}

	download() {
		this.fileService.downloadFile().subscribe((response: any) => {
			let blob:any = new Blob([response], { type: 'text/json; charset=utf-8' });
			const url = window.URL.createObjectURL(blob);
			//window.open(url);
			saveAs(blob, 'employees.json');
			}), (error: any) => console.log('Error downloading the file'),
			() => console.info('File downloaded successfully');
	}
 
}

View File

I have created service class to fetch file data from a server URL but I need to provide a link or button for downloading the file.

In the view file I will give users two options for downloading the same file. I will use link as well as button for downloading the same file from the server.

I call the download() function of controller class on click event.

The code is written into app.component.ts file.

<div style="text-align:center">
  <h1>
    Welcome to {{ title }}
  </h1>
</div>
<h2>Click below link to get employee data</h2>
<div>
    <h3>
	Using Link <br/>
	<a href="#" (click)="download()">Download Employee Data</a>
	</h3>
	
	<h3>Using Button</h3>
	<input type="button" (click)="download()" value="Download Employee Data"/>
</div>

Registering HttpModule/HttpClientModule

In the service class I have used Http module which may not be found automatically. So I need to register it in providers array of @NgModule.

So make sure you have the app.modules.ts file with the following content.

In the below source, import {HttpModule} from '@angular/http'; and HttpModule inside imports: [ ] are included.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {HttpModule} from '@angular/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

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

Update for Angular 10:

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 { }

Angular 11/12/13/15:

Same as for Angular 10.

Enough coding! Let’s test our application.

Testing Angular File Download Application

Let’s assume that server side application is up and running and the URL http://localhost:8080/employees/download is accessible.

Run the Angular application angular-file-download by executing command ng serve --open. Your application will open at URL http://localhost:4200 in the browser and the page may look similar to the below image:

download file from server using angular

When you click on link or button for downloading file you will see below page with file save option:

download file from server using angular

When you use the code for displaying data on browser inside download() function of controller code and click on button or link, then you should see below output:

[{"id":1,"name":"Soumitra","email":"soumitra@email.com"},{"id":2,"name":"Liton","email":"liton@email.com"},{"id":3,"name":"Suman","email":"suman@email.com"},{"id":4,"name":"Debabrata","email":"debabrata@email.com"}]

For server side code you can read the post on Download file using Angular and Spring Boot.

Source Code

Download

5 thoughts on “Download File From Server Using Angular

  1. Hi.
    thanks for this article , I am also using the same but In my case .xlsm file will download in bottom and file size is 1 kb only.
    I need to show save dialog box to user so he can save file any where

  2. // controller.ts of angular
    downloadExcel() {
    const params = new HttpParams()
    .set(‘charnDate’, this.charnDateFormated);

    this.charnService.downloadCharnCSVFile(params).subscribe(response => {
    const currentDate = moment().format(‘YYYY_MM_DD_HH:mm:ss’);
    const blob: any = new Blob([response], { type: ‘text/csv; charset=utf-8’ });
    saveAs(blob, currentDate + ‘_charn.csv’);
    },
    error => {
    console.log(‘Error downloading the file’);
    },
    () => {
    console.log(‘File downloaded successfully’);
    });
    }
    // servise.ts
    downloadCharnCSVFile(params: HttpParams): Observable {
    return this.http.get(this.CHARN_DOWNLOAD_URL, {params: params, responseType: ‘blob’});
    }

Leave a Reply

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