Thursday, May 14, 2020

Download file in Angular 8

Introduction

This post is about how to download file Angular framework. Angular is a UI framework for building rapid application development. Here we will use Angular 8 to download file from server side. You can use any server side technology and integrate this example with it for downloading file from server.
  Download file from server using Angular 7/8

Prerequisites
Angular 8, Node v11.3.0/v12.9.1, npm 6.4.1/6.10.2
Install Modules
Install the required module for Angular 8: execute command npm install file-saver --save in command line tool.
Install the required module for Angular 8: execute command npm install @angular/http@latest in command line tool.
Creating Project
ng new angular-file-download.
Creating Service Class
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});
  }
 Creating Controller Class
 The below code is written in app.component.ts file.
Read : Download file in Angular 7
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.
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');
  }

}
Creating View File
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 Http Module
In our service class we have used Http module which may not be found automatically. So we 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 { }
Testing the Application
Let’s assume that server side application is up and running and the URL http://localhost:8080/employees/download is accessible.

No comments:

Post a Comment