Download Sample Source Code - Working With Files ASP_NET MVC 5

 


We have seen how to post files (ASP.NET MVC Working With Files - Setting up form method and content type), files will be available in post method defined in controller. Using Request.Files and HttpPostedFile we are going to upload using following code.

 

This is generic code, will work with uploading multiple files (if multiple files are posted)

 

 

public class HomeController : Controller
{

 

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

{

  HttpPostedFileBase hpf = Request.Files[file];

  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();
 }
}