In ASP.NET MVC, the FileContentResult
class is used to return binary data as a file download. It is useful when you want to return a file from your controller action, such as a PDF or an image file.
Here is an example of how to use FileContentResult
in ASP.NET MVC:
csharppublic ActionResult DownloadFile()
{
byte[] fileContents = GetFileContents(); // Retrieve the binary data of the file
string fileName = "example.pdf"; // Set the name of the file
return File(fileContents, "application/pdf", fileName);
}
In this example, the DownloadFile
action returns a PDF file as a download. It first retrieves the binary data of the file using the GetFileContents
method. It then sets the content type of the response to "application/pdf" and the file name to "example.pdf" using the File
method.
You can also set additional parameters to control the behavior of the download, such as the lastModified
parameter to specify the last modified date of the file, or the fileDownloadName
parameter to specify a different name for the downloaded file.
csharppublic ActionResult DownloadFile()
{
byte[] fileContents = GetFileContents(); // Retrieve the binary data of the file
string fileName = "example.pdf"; // Set the name of the file
DateTime lastModified = GetLastModifiedDate(); // Retrieve the last modified date of the file
return File(fileContents, "application/pdf", fileName, lastModified, "MyDownload.pdf");
}
In this example, the DownloadFile
action sets the last modified date of the file to GetLastModifiedDate()
and the downloaded file name to "MyDownload.pdf".
I hope this helps you understand how to use FileContentResult
in ASP.NET MVC.
Comments
Post a Comment