Q: File Upload ASP.NET MVC 3.0

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

Test Case #12


File ID: #5193851-1-cc


// This action renders the form
public ActionResult Upload()
{
    return View();
}
// This action handles the form POST and the upload
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
// Verify that the user selected a file
    if (file ! = null && file.ContentLength > 0)
    {
// extract only the fielname
        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");
}

  1. Another point is you can replace the controller and action names (strings) in the Html.BeginForm() call like so: `Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" })`. This is useful if it is a partial view that is called from multiple parent views (or similar).
  2. Nice answer. It's also worth noting that if you are trying to upload large files (greater than the default 4 MB) you'll want to set ` <httpruntime maxrequestlength="" x"="" />` in your web.config, where x is the number of KB allowed for upload.
  3. If users need to link to the file from other pages, you can replace ~/App_Data/ with ~/Content/

Comments Quality
Accurate?:
Precise?:
Concise?:
Useful?: