If you are a web developer you often need to upload file on the web server or database. In today’s post I am going explain how we can upload file in ASP.NET MVC 3 with razor syntax. So, first thing we need to create a view that will contain the file upload control. I am going to use an existing asp.net mvc template for this demo. So I have just modified the default Index view like following.
@{ ViewBag.Title = "Home Page"; }
@ViewBag.Message
To learn more about ASP.NET MVC visit http://asp.net/mvc.
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { Upload Image: }
Here you can see that I have used Html.Begin form to create a form with multipart as we all know this attribute is required to have to upload any kind of file to the server. Also I have used the simple HTML file control and a submit button to submit a form. Now we are done with HTML so it’s time to write server-side code.Following is a code for that.
[HttpPost] public ActionResult Index(HttpPostedFileBase file) { string path = System.IO.Path.Combine(Server.MapPath("~/Images"), System.IO.Path.GetFileName(file.FileName)); file.SaveAs(path); ViewBag.Message = "File uploaded successfully"; return View(); }
As you can see I have create a new ActionResult Index with parameter and I have given HttpPost attribute to it to get all data from post method of form we are submitting and then I have written a code to save file in Images folder. That’s it. We are dong with coding now its time to run the application. Once you press F5 it will look into the browser like following.
Now once you select file and click on upload image it will upload files and give a message like following.
We are done. Hope you like it. Stay tuned for more updates. Till then Happy programming.