How to upload file in ASP.NET MVC3
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.
@{
ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
<p>
To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>
<p>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<label for="file">Upload Image:</label>
<input type="file" name="file" id="file"/>
<input type="submit" value="Upload Image" />
}
</p>
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.