How to download a file in Angular .NET

broggi

Broggi Quentin

Posted on January 27, 2023

How to download a file in Angular .NET

In this article, I will show you how to download a file in an Angular project with a .NET 5+ Web Api.

.NET Side

You need to create a controller, for example DownloadController, with a DownloadFile Api of HttpGet type. If you want you can send the file name to be downloaded as a parameter for this Api.

First, transform your file into a byte array or via a memoryStream, then return it in a FileContentResult by passing your byte array, the "application/octet-stream" type and the name of your file.


[Route("api/[controller]")]
public class DownloadController : Controller
{

        [HttpGet]
        public async Task<IActionResult> DownloadFile()
        {
            //Set your file path here
            var path = Path.Combine(Directory.GetCurrentDirectory(), "Ressources", "Example.docx");
            //Check if the file exists
            if (!System.IO.File.Exists(path))
                return NotFound();
            //Get Bytes array of your file, you can also to do a MemoryStream
            Byte[] bytes = await System.IO.File.ReadAllBytesAsync(path);

            //Return your FileContentResult
            return File(bytes, "application/octet-stream", "Example.docx");

        }
}

Enter fullscreen mode Exit fullscreen mode

Angular Side

In your service create a function to call the .Net Api, you need to specify ‘blob’ for the responseType like this :

  downloadFile() {
    return this.http.get('http://localhost:5000/api/download/', { responseType: 'blob' });
  }

Enter fullscreen mode Exit fullscreen mode

In Angular the best library to download file is file-saver that you can install with :
npm i file-saver

Write a function in your component to call your service.

  download() {
    this.fileService.downloadFile()
      .subscribe(data => saveAs(data, 'Example.docx'));
  }

Enter fullscreen mode Exit fullscreen mode

Then add the import for use file-saver.

import { saveAs } from "file-saver";
Enter fullscreen mode Exit fullscreen mode

And it works.

💖 💪 🙅 🚩
broggi
Broggi Quentin

Posted on January 27, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related