Download Files with Angular from .NET Core Web API

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.

Save Blob From Web API File Response

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");

        }

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

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

import { downloadFile } from 'file-saver';

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' });
  }

// file-downloader.component.ts
this.dataExtractService
  .download(dto)
  .subscribe(
    blob => {
      downloadFile(blob, 'WeeklySummary.xlsx');
    },
    error => {
      console.log("Something went wrong");
    });

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

Download File From URL

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");

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 an enthusiastic software developer, latest web and mobile technology adapter and primary author of onthecode.

Leave a Reply

Close Menu