In this I article I will explain how to upload file from the client computer to the server.
Open studio 2010 and create a new ASP.NET MVC 3 Web Application (Razor) project as seen below:
Choose Razor as the view engine and click OK.
Add a controller in your project and give name as HomeController as shown in the below figure:
Add a view (Index) and create a file upload control with the help of HTML as shown below:
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
<h2>Upload File</h2>
<form method="post" enctype="multipart/form-data">
<label>Filename: <input type="file" name="file" /></label>
<input type="submit" value="Submit" />
</form>
</div>
</body>
</html>
After adding a control in view adds the following code in the controller to upload the file on the server:
using System.Web.Mvc;
using System.IO;
using System.Web;
namespace FileUploadDemo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
var fileName = Path.GetFileName(file.FileName);
if (fileName != null)
file.SaveAs(Server.MapPath("~\\files\\" + fileName));
return View();
}
}
}
Run this application , you will see the following screen:
Thanks for reading this article, I think this will help you a lot.
Leave Comment