Return or Download File in ASP.NET Core API

Download File in ASPNET Core API download file NET 6 and 7 download file NET 6 download file c

In this article, we will see how to Return or Download File in ASP.NET Core API.

Example: Useful file types like .pdf, .txt, .xlsx, etc in the browser or any other type of application.

We will use ASP.NET Core WebAPI as a sample to verify how to download Files in ASP.NET Core-based API or MVC application.

We will cover the below aspects in today’s article,

Most of the time, we get requirements to download or return the file within the given ASP.NET Core or Angular or any other UI applications dealing with it.

We shall see how to perform a download or file return in ASP.NET core-based application.

This file download or return technique can be used for any ASP.NET Core or Angular app.

The file helper method is built into your controller.

These methods are coming from the FileResult abstract class and give you multiple options for retrieving files to send to the client. 

Using FileStreamResult to Return or Download File in ASP.NET Core API

FileStreamResult classes us useful for Sending binary content.

Here you have a stream and want to return stream content as a file.

Example- Download File in ASP.NET Core API

Download or Return the Image (.png) file in .NET

Here we will be returning an image from the Controller method.

Using the below technique controller can return any other types of images like .bmp or .jpg etc.

For the png file, we need to use mimeType = “image/png”.

        [HttpGet("{id}")]
        [Route("Stream")]
        public async Task<IActionResult> DownloadImage(string id)
        {
            Stream stream  = _fileInterafces.ReadAsStream(id);
            string mimeType = "image/png";
            return new FileStreamResult(stream, mimeType)
            {
                FileDownloadName = "image.png"
            };
        }

Note: _fileInterafces is my custom interface that reads the file and returns streams of bytes

Download or Return PDF(.pdf) file in .NET

As an example, here we will be returning a PDF file from the Controller method.

Using the below technique controller can return any other type of file as well like .doc or .txt etc.

For PDF files we need to use mimeType = “application/pdf.

        [HttpGet("{id}")]
        [Route("Stream")]
        public async Task<IActionResult> DownloadPdfFile(string id)
        {
           
            Stream stream = _fileInterafces.ReadAsStream(id);
            string mimeType = "application/pdf";
            return new FileStreamResult(stream, mimeType)
            {
                FileDownloadName = "FileasStream.pdf"
            };
        }

In about code _fileInterafces can be the provider of your choice or This could be your custom code dealing with the files.

Download or Return Excel(.xlsx) file

Here we will be returning or downloading an Excel file(.xslx) from the Controller method.

Using the below technique Controller can return any other types of images like .xlx or .csv etc.

For excel file we need to use mimeType = “application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

        [HttpGet("{id}")]
        [Route("Stream")]
        public async Task<IActionResult> DownloadXlsxFile(string id)
        {
            Stream stream = _fileInterafces.ReadAsStream(id);
            string mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            return new FileStreamResult(stream, mimeType)
            {
                FileDownloadName = "FileasStream.xlsx"
            };
        }

Using FileContentResult for File Download in .NET

Here we will be returning an Excel file(.xslx) from the Controller method.

Here we will be returning a stream of bytes to an excel file.

Example- Download File

        [HttpGet("{id}")]
        [Route("Stream")]
        public async Task<IActionResult> DownloadfromBytes(string id)
        {
            byte[] byteArr = _fileInterafces.ReadAsByteStream(id);
            string mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            return new FileContentResult(byteArr, mimeType)
            {
                FileDownloadName = "excelfromByte1.xlsx"
            };
        }

Using File class for Download

You can also use the File class for file processing.

Please see the below example to achieve the same.

return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "FileasStream.xlsx");

Difference between FileContentResult and FileStreamResult

As we know FileResult is an abstract base class.

Both FileContentResult & FileStreamResult classes are derived class from the Abstract FileResult class.

FileStreamResult – Sends binary content to the response by using a Stream instance.

Here you have a stream and want to return stream content as a file.

FileContentResult – Sends the contents of a binary file to the response. Here you have a byte array and want to return byte content as a file.

MIME Types for files upload and download

Below are a few examples of MIME – content types for your information.

MIME TypeDescription
text/plainPlain text.
text/htmlHTML.
text/xmlXML data.
text/richtextRich Text Format (RTF).
text/scriptletWindows script component.
audio/x-aiffAudio Interchange File, Macintosh.
audio/basicAudio file, UNIX.
audio/midWindows Internet Explorer 7 and later. MIDI sequence.
audio/wavPulse Code Modulation (PCM) Wave audio, Windows.
image/gifGraphics Interchange Format (GIF).
image/jpegJPEG image.
image/pjpegDefault type for JPEG images.

One can also use the below mime with the content type as “application/octet-stream” which is a binary file and kind of generic and works for most types of files.

To view, one should use an appropriate extension before downloading a file.

  mimeType = "application/octet-stream";

References:

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



7 thoughts on “Return or Download File in ASP.NET Core API

  1. Thanks. This article was helpful. I did write my custom interface in the above code which returns the stream and achieved the result.

  2. Thank you but this line not working or i didnt understand Stream stream = _fileInterafces.ReadAsStream(id);

    What is _fileInterafces ?

    1. Hello Ben, Thanks for your query. It’s actually custom interface which I created for my service. You can create your own method which returns excel as stream and use as above. I can share the code separately if needed. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *