File Upload ASP.NET MVC 3.0

user637197 picture user637197 · Mar 4, 2011 · Viewed 357.6k times · Source

(Preface: this question is about ASP.NET MVC 3.0 which was released in 2011, it is not about ASP.NET Core 3.0 which was released in 2019)

I want to upload file in asp.net mvc. How can I upload the file using html input file control?

Answer

Darin Dimitrov picture Darin Dimitrov · Mar 4, 2011

You don't use a file input control. Server side controls are not used in ASP.NET MVC. Checkout the following blog post which illustrates how to achieve this in ASP.NET MVC.

So you would start by creating an HTML form which would contain a file input:

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

and then you would have a controller to handle the upload:

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");        
    }
}