Saturday, March 4, 2017

FileUpload in ASP.Net MVC

Here I will show you How to upload files in Asp.Net MVC.
Previously I had shown How to...
MVC:
Output:

Create a Project using Visual Studio. In Index.cshtml file ADD below code.  

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <h3>Upload Files</h3>
    <br />
    <input type="file" name="files" multiple class="btn btn-default" />
    <br />
    <button type="submit" class="btn btn-primary">Upload</button>
}

In the HomeController.cs file ADD the below code.
  

[HttpPost]
public ActionResult Index(IEnumerable Files)
{
 try
 {
  foreach (var file in Files)
  {
   if (file != null && file.ContentLength > 0)
   {
    file.SaveAs(Path.Combine(Server.MapPath("/uploads/" + file.FileName)));
   }
  }
 }
 catch (Exception ex)
 {
  string Msg = ex.Message;
 }
 return View();
}

No comments:

Post a Comment