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");
}
}
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' });
}
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'));
}
Then add the import for use file-saver.
import { saveAs } from "file-saver";
And it works.
Top comments (0)