In this post, I will show you how easy it is to download a file with Angular using file-saver package.

CSV files, Excel spreadsheets, Word documents, PDF reports and images are common types of files that a functional Angular web app needs to be able to download to browser.

In most cases, files are generated by back-end APIs and sent as blobs in HTTP response body. Downloading files in JavaScript is quite a laborious and boring task.

Return File result in Web API

Before diving into Angular, here is the controller action that returns the file as a blob.

[HttpPost] public async Task<IActionResult> Post([FromBody] DataRequestDto dto) { var dtos = new List<MyDto>(); var bytes = _dataExtractService.ExportToWorkbook(dtos); return File(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); }
Code language: C# (cs)

It is important to specify the correct format here. Since I am sending an Excel file, the format is application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.

Start by getting the file-saver package from npm:

npm install file-saver --save
Code language: Bash (bash)

Import file-saver into your component where you want to download the file.

import { downloadFile } from 'file-saver';
Code language: TypeScript (typescript)

Then, download your file at the end of the HTTP call. Please note that you must specify the response type explicitly in the service.

// data-extract.service.ts download(dto: DataRequestDto): Observable<Blob> { return this.http.post<Blob>(`${environment.apiUrl}api/dataextract/report`, dto, { responseType: 'blob' as 'json' }); }
Code language: TypeScript (typescript)
// file-downloader.component.ts this.dataExtractService .download(dto) .subscribe(blob => { downloadFile(blob, 'WeeklySummary.xlsx'); }, error => { console.log("Something went wrong"); });
Code language: TypeScript (typescript)

The file should download as WeeklySummary.xlsx at the end of the HTTP request.

Download file

It is also possible to download a file from a URL using file-saver.

The syntax is very easy, just pass the URL and specify file name for the file.

downloadFile("https://via.placeholder.com/300.png", "image.jpg");
Code language: TypeScript (typescript)

Summary

To summarise, we downloaded a blob instance returned from .Net Core Web API with file-saver. What we discussed is applicable to pretty much any front-end framework as file-saver supports HTML5.

Umut Esen

Umut is a certified Microsoft certified developer and has an MSc in Computer Science. He is currently working as a senior software developer in Edinburgh, UK. He is the primary author and the founder of onthecode.

This Post Has One Comment

  1. Noe

    Excelente Post.

    Me salvo la vida

Leave a Reply