mkdir downloadfile
cd downloadfile
mkdir backend
mkdir frontend
cd backend
npm init -y
npm i express
npm i cors
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors') const app = express(); app.use(cors()) app.use(bodyParser.json({ type: "application/json" })); app.use(bodyParser.urlencoded({ extended: false })); app.use(express.static('public')); app.get('/getFile', function (req, res, next) { res.download('./public/profile.jpg', function (err) { if (err) { next(err); } }) }) app.use(function (err, req, res, next) { res.status(err.status).send(err); }) app.listen(8081, function () { console.log("Server listening on port 8081"); }) |
Make a public
folder and store the file
inside it which you need to download inside the angular app
cd frontend
ng new downloadfile
cd downloadfile
npm i file-saver
app.component.html
1 |
<button (click)="getfile()">Download</button> |
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import { Component, OnInit } from '@angular/core'; import { saveAs } from 'file-saver'; import { DownloadfileService } from './downloadfile.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title="download file" constructor(private serv: DownloadfileService) { } ngOnInit(): void { } getfile() { this.serv.getFile().subscribe((data: Blob | MediaSource) => { let downloadURL = window.URL.createObjectURL(data); saveAs(downloadURL); }) } } |
Now make a service
which will actually download the file from the express
server
ng generate service downloadfile
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DownloadfileService { constructor(private http:HttpClient) { } getFile(){ return this.http.get('http://localhost:8081/getfile',{responseType:'blob'}); } } |
Include the httpclient
module inside the app.module.ts
file as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } |