Download a File with Asp.Net Core

Tom el Safadi
2 min readJul 28, 2020

One of the things that was always difficult and frustrating to me was how to return a file from a backend and consume it client-side. Thus, I want to provide a detailed and simple answer with a step by step explanation.

In this example we will return an Excel file from the backend. However, this could be any type of file like a PDF, Word, etc.

Lets get started…

1. Create a sample file

I will place a file called “Sample.xlsx” inside the wwwroot folder for the sake of this tutorial. It does not necessarily have to be a static file, instead you can also skip this step and use a dynamically generated file later on.

2. Create an API controller

Next, create an Api Controller with a function that will return our file.

Firstly, we get the path of the “Sample.xlsx” file located inside the wwwroot folder and then convert it to a FileStream.
Note: At this point you can also use your dynamically created file instead of a static one. You only need a FileStream or byte array.

Lastly, we return the file from the backend. As a MIME-type we use the “application/octet-stream” which could basically be any type of binary data.

3. Download the file client-side

For the last part we somehow need to download the file from the backend.
I will use XMLHttpRequest in my case but you could achieve the same using HttpClient if you are using Angular and similarly in other frameworks.
Note: It is not possible to download files with AJAX, you have to use XMLHttpRequest.

The code seems a little bit confusing at the beginning but is actually straightforward.

Firstly, we create the XMLHttpRequest object and set the responseType to “blob”. Then we open the request with the url pointing to the controller and action from the backend. If we receive a 200 status code, we can proceed with our code.

Line 10–16 looks a little bit messy at the beginning but does nothing else than getting the filename from the content-disposition header.

At the end we download the file by creating an invisible anchor element and programmatically triggering the click event.

I hope this article helps some of you guys. If you have questions let me know in the comments.

The repository is available on GitHub: https://github.com/tsafadi/FileDownloadSample

--

--