How to file upload in mvc?

Total Post:104

Points:728
 1156  View(s)
Ratings:
Rate this:
How can I upload the file using html input file control
  1. Post:194

    Points:1396
    Re: How to file upload in mvc?

    You don't use a file input control. Server side controls are not used 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
            {
                public ActionResult Index()
                {
                    return View();
                }
     
                [HttpPost]
                public ActionResult Index(HttpPostedFileBase file)
                {
                    if (file != null && file.ContentLength > 0)
                    {
                        var fileName = Path.GetFileName(file.FileName);
                        var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                        file.SaveAs(path);
                    }
                    return RedirectToAction("Index");
                }
            }

      Modified On Apr-05-2018 06:48:49 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!