In this article I will explain with an example, how to download file as attachment in browser in ASP.Net MVC.
Location of the File
The File to be downloaded is stored in the Folder (Directory) named as Files.
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
This Action method gets called, when Download button is clicked.
Inside this Action method, the path of the File to be downloaded is fetched.
Then, the File is read as Binary Data into a BYTE Array using the ReadAllBytes method of the File class.
Finally, the BYTE Array is sent for download with content type as octet-stream using the File function.
Note: octet-stream is used to send any type of file in the form of BYTE array over the internet.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Download()
{
//Build the File Path.
string path = Server.MapPath("~/Files/Sample.pdf");
//Read the File data into Byte Array.
byte[] bytes = System.IO.File.ReadAllBytes(path);
//Send the File to Download.
return File(bytes, "application/octet-stream", "Sample.pdf");
}
}
View
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Download.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of an HTML INPUT Submit button.
Submitting the Form
When the Submit button is clicked the form will be submitted to the Controller’s Action method.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Download", "Home", FormMethod.Post))
{
<input type="submit" value="Download" />
}
</body>
</html>
Screenshot
Demo
Downloads