In ASP.NET MVC, FileStreamResult is a class that is used to return a file to the client as a file download from a stream.
To use the FileStreamResult, follow these steps:
- Create a controller method that returns an instance of the FileStreamResult class.
csharppublic FileStreamResult DownloadFile()
{
string filePath = Server.MapPath("~/Content/example.pdf");
FileStream fileStream = new FileStream(filePath, FileMode.Open);
return new FileStreamResult(fileStream, "application/pdf");
}
In the controller method, create a FileStream object that represents the file that you want to download. In the example above, the file path is "~/Content/example.pdf".
Specify the content type of the file that you want to download. In the example above, the content type is "application/pdf".
In the view, create a link that calls the controller method that returns the FileStreamResult object.
html<a href="@Url.Action("DownloadFile")">Download PDF</a>
When the link is clicked, the controller method will be called and the FileStreamResult object will be returned, which will prompt the user to download the file.
Note: You should close the FileStream object after it has been used to avoid file locks. You can use the using statement to ensure that the FileStream object is properly disposed of. Here's an example:
csharppublic FileStreamResult DownloadFile()
{
string filePath = Server.MapPath("~/Content/example.pdf");
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
return new FileStreamResult(fileStream, "application/pdf");
}
}
Comments
Post a Comment