File Download In Angular

Introduction

In this article, I will introduce how to download a file in Angular with a button click and show an example.

Prerequisites

  • Basic knowledge of Angular
  • Visual Studio Code
  • Node and NPM installed
  • Bootstrap

For this article, I have created an Angular project using Angular 12. For creating an Angular project, we need to follow the following steps:

Create an Angular Project

Let's create a new angular project by using the following command.

ng new fileDownloadExample
Markup

Open a project in Visual Studio Code using the following commands.

cd fileDownloadExample
Code .
Markup

Now in Visual Studio, your project looks as below.

File Download in Angular

App.Component.html

<a [href]="fileUrl" download="file.txt">DownloadFile</a>
Markup

App.Component.ts

import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    name = 'Angular 5';
    fileUrl;
    constructor(private sanitizer: DomSanitizer) {}
    ngOnInit() {
        const data = 'some text';
        const blob = new Blob([data], {
            type: 'application/octet-stream'
        });
        this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
    }
}
JavaScript

Now Run the project using the following command

npm start
Markup

and click on the link and you will see the downloaded file

File Download in Angular

Summary

In this article, I have discussed the implementation of downloading a file in Angular with a button click.


Similar Articles