Prerequisites

  • Basic knowledge of HTML
  • Knowledge of C#
  • Knowledge of ASP.NET MVC 5

As file upload is the basic need for all the applications. We will learn how to upload a file using ASP.NET MVC 5 using the Razor view.

We have to specify the enctype for the form as multipart/form-data

Index.cshtml

@{
    Layout = null;
}

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <label>Select File</label>
    <input type="file" name="file" />
    <hr />
    <input type="submit" value="Upload" />
    <br />
    <h2 style="color:green">@ViewBag.Response</h2>
}

Controller Side code

public ActionResult Index()
{
    return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
    if (file != null)
    {
        string path = Server.MapPath("~/Files/");
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

        file.SaveAs(path + Path.GetFileName(file.FileName));
        ViewBag.Response = "Successful.";
    }

    return View();
}

Output

file-upload-output