How to download a file in asp net core

Introduction

Downloading a file in ASP.NET Core can be achieved using various methods. In this article, we will explore different to download a file in ASP.NET Core.

Method 1: Using FileResult

The simplest way to download a file in ASP.NET Core is by using the FileResult . This class represents a file result that can be returned from an action method.

Here's an example of how to use FileResult to download a file:

public IActionResult DownloadFile()
{
    string filePath = "path/to/file.pdf";
    string fileName = "file.pdf";
    return File(filePath, "application/pdf", fileName);
}

In the above example, we specify the file path, content type, and file name as to the File method. The method then a FileResult , which triggers the file download in the .

Method 2: Using PhysicalFileResult

If you want to download a file from a path on the , you can use the PhysicalFileResult class. This class is derived from FileResult and provides options for serving physical files.

Here's an example of how to use PhysicalFileResult to download a file:

public IActionResult DownloadPhysicalFile()
{
    string filePath = "path/to/file.pdf";
    string fileName = "file.pdf";
    return PhysicalFile(filePath, "application/pdf", fileName);
}

In the above example, we specify the physical file path, content type, and file name as parameters to the PhysicalFile method. The method then returns a PhysicalFileResult object, which triggers the file download in the browser.

Method 3: Using FileStreamResult

If you need more control over the file stream, you can use the FileStreamResult class. This class allows you to read the file stream and provide additional options for serving files.

Here's an example of how to use FileStreamResult to download a file:

public IActionResult DownloadFileStream()
{
    string filePath = "path/to/file.pdf";
    string fileName = "file.pdf";
    FileStream fileStream = new FileStream(filePath, FileMode.Open);
    return new FileStreamResult(fileStream, "application/pdf")
    {
        FileDownloadName = fileName
    };
}

In the above example, we a FileStream object to read the file stream. We then pass this object along with the content type to the FileStreamResult constructor. Finally, we set the FileDownloadName property to specify the file name for download.

Conclusion

Downloading a file in ASP.NET Core can be achieved using various methods. In this article, we explored three different approaches: using FileResult, PhysicalFileResult, and FileStreamResult. Choose the method that best suits your requirements and implement it in your ASP.NET Core application.

Rate this post

Leave a Reply

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

Table of Contents