Download Sample Source Code - Working With Files ASP_NET MVC 5


 

Now that we have see how to post file and how to upload file on server.

  1. ASP.NET MVC Working With Files - Setting up form method and content type (Post Files)

  2. ASP.NET MVC Working With Files - Uploading File On Server

In order to upload multiple file you just need to add input control in view of type=”file”.
 

 

View -

 

 

@using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new {enctype="multipart/form-data"})){
  
 

   <input type="file" name="FileUpload1" multiple/><br />

    <input type="submit" name="Submit" id="Submit" value="Upload" />
}

 

OR

(If you have specific number of files to upload you can define as follows - (max upload as 5 files))

 

@using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new {enctype="multipart/form-data"})){
  
 <input type="file" name="FileUpload1" /><br />
   <input type="file" name="FileUpload2" /><br />
   <input type="file" name="FileUpload3" /><br />
   <input type="file" name="FileUpload4" /><br />
   <input type="file" name="FileUpload5" /><br />
    <input type="submit" name="Submit" id="Submit" value="Upload" />
}

 

Post method -

 

public class HomeController : Controller
{

 [HttpPost]
 public ActionResult UploadFile()
 {    
   
foreach (int i; i< in Request.Files.Count; i++)

{

  HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFile;

  if (hpf.ContentLength == 0)

     continue;

 //You have to make sure ‘FileUploads’ directory exists

  string savedFileName = Path.Combine(

     AppDomain.CurrentDomain.BaseDirectory+ "FileUploads/",

     Path.GetFileName(hpf.FileName));

  hpf.SaveAs(savedFileName);

}


   return View();
 }
}