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.Prerequisites
Angular 8, Node v11.3.0/v12.9.1, npm 6.4.1/6.10.2Install 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';For Angular 8, change the downloadFile() function as below:
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 });
}
}
Creating Controller Class
downloadFile(): Observable<any>{
return this.http.get('http://localhost:8080/employees/download', {responseType: ResponseContentType.Blob});
}
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.
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.
const url= window.URL.createObjectURL(blob);
window.open(url);
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';Creating View File
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');
}
}
The code is written into app.component.ts file.
<div style="text-align:center">Registering Http Module
<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>
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';Testing the Application
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 { }
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