In this example, you can browse files on the server and download a file from the selected file list.
Filecontroller:
Code
Public class filecontroller: Controller
{
// Action for list all the files in "~ /App_data/download "Directory
Public actionresult list ()
{
// Retrive file list
Directoryinfo dir = new directoryinfo (server. mappath ("~ /App_data/download /"));
// Filter it via LINQ to object
VaR files = from F in Dir. getfiles ("*. *", searchoption. topdirectoryonly)
Where F. extension! = "EXE"
Select F;
// Call the corresponding View
Return view (files. tolist ());
}
// Action for return the binary stream of a specified file
Public actionresult download (string FN)
{
// Check whether requested file is valid
String PFN = server. mappath ("~ /App_data/download/"+ FN );
If (! System. Io. file. exists (PFn ))
{
Throw new argumentexception ("invalid file name or file not exists! ");
}
// Use binarycontentresult to encapsulate the filecontent and return it
Return new binarycontentresult ()
{
Filename = FN,
Contenttype = "application/octet-stream ",
Content = system. Io. file. readallbytes (PFn)
};
}
}
Binarycontentresult class definition:
Code
Public class binarycontentresult: actionresult
{
// Default constructor
Public binarycontentresult ()
{
}
// Properties for encapsulating HTTP headers
Public String contenttype {Get; set ;}
Public String filename {Get; set ;}
Public byte [] content {Get; set ;}
// Underlying code which set the httpheaders and output file content
Public override void executeresult (controllercontext context)
{
Context. httpcontext. response. clearcontent ();
Context. httpcontext. response. contenttype = contenttype;
Context. httpcontext. response. addheader ("content-disposition ",
"Attachment; filename =" + filename );
Context. httpcontext. response. binarywrite (content );
Context. httpcontext. response. End ();
}
}
From the above definition, we can see that we can reload different actionresults. The actionresult class is defined as follows:
Code
Namespace system. Web. MVC
{
// Summary:
// Encapsulates the result of an action method and is used to perform a framework-level
// Operation on the Action method's behalf.
Public abstract class actionresult
{
Protected actionresult ();
// Summary:
// Enables processing of the result of an action method by a custom type that
// Inherits from system. Web. MVC. actionresult.
//
// Parameters:
// Context:
// The context within which the result is executed.
Public abstract void executeresult (controllercontext context );
}
}
I think this example is good and the idea is clear. What impressed me most about this example is to provide a solution for downloading an MVC file. We can also define an actionresult class that meets our own needs.