In ASP.NET MVC, the FileResult
class is used to return a file to the client as the HTTP response. Here's an example of how to use FileResult
in a controller action method:
csharppublic FileResult MyAction()
{
// Get the file data
var fileData = GetFileData();
// Return the file as a FileResult
return File(fileData, "application/pdf", "MyFile.pdf");
}
In this example, the MyAction
method gets the file data and returns it as a FileResult
using the File
method. The File
method takes three parameters: the file data as a byte array, the MIME type of the file, and the name of the file that the client should receive. The method returns a FileResult
, which tells the MVC framework to send the file to the client as the HTTP response.
You can also use the File
method to return files from the file system. Here's an example:
csharppublic FileResult MyAction()
{
// Get the file path
var filePath = Server.MapPath("~/Content/MyFile.pdf");
// Return the file as a FileResult
return File(filePath, "application/pdf", "MyFile.pdf");
}
In this example, the MyAction
method gets the file path and returns the file as a FileResult
using the File
method. The File
method takes the file path as the first parameter instead of the file data. The Server.MapPath
method is used to map the virtual path "~/Content/MyFile.pdf"
to the physical file path on the server.
You can also use the FileStreamResult
class to return a file as a stream instead of a byte array. Here's an example:
csharppublic FileStreamResult MyAction()
{
// Get the file stream
var fileStream = GetFileStream();
// Return the file stream as a FileStreamResult
return new FileStreamResult(fileStream, "application/pdf");
}
In this example, the MyAction
method gets the file stream and returns it as a FileStreamResult
. The FileStreamResult
constructor takes two parameters: the file stream and the MIME type of the file. The FileStreamResult
class is useful when you want to return large files, as it allows you to return the file as a stream without loading the entire file into memory.
Comments
Post a Comment