How to Upload a File in ASP.NET MVC 3.0 Using HTML Input File Control

In order to develop a functionality to upload file in ASP.NET MVC 3.0 you must use the Html input file here is the sample code:

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="file" />
    <input type="submit" value="Submit" />
}

As you can see, this code should be added in the .cshtml file. You can definitely add more input fields to build your submit form. But for this example, I have just added one input file along with the submit button. In the tag BeginForm, you need to set ectype to multipart/form-data to enable supporting the binary data in the submit form.

Now, let's explore the server side action in the Controller that will handle the submit event and will read the binary file from the submit request. The action should be of type "HttpPost" because we are posting data to the server:

public class HomeController : Controller
{
    // This action renders the form
    public ActionResult Index()
    {
        return View();
    }

    // This action handles the form POST and the upload
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        // Verify that the user selected a file
        if (file != null && file.ContentLength > 0) 
        {
            // extract only the filename
            var fileName = Path.GetFileName(file.FileName);
            // store the file inside ~/App_Data/uploads folder
            var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
            file.SaveAs(path);
        }
        // redirect back to the index action to show the form once again
        return RedirectToAction("Index");        
    }
}

Let me know if you have any question.

You can also check: How to Upload an Image File in ASP.NET MVC 4

Post a Comment

Previous Post Next Post