File Uploading in ASP.NET MVC

Simple File uploading in ASP.NET MVC:

As given in the following code, create form with the upload box and don’t forget to include the enctype in the form tag, which represents the content type of the request.

Note: enctype="multipart/form-data" is mandatory because it represents the file type. 

  1. <form action="/sample/upload" method="post" enctype="multipart/form-data">  
  2.    Sample Upload:<br/>  
  3.   
  4.    <input type="file" name="file" id="file" />  
  5.   
  6.    <input type="submit" value="Upload" />  
  7.   
  8. </form>  

In controller page get the file from the client request using Request instance example: Request.Files["file"];

  1. [HttpPost]  
  2.   
  3. public ActionResult Upload()    
  4. {  
  5.   
  6.    string location = @"e:\location\";  
  7.   
  8.    HttpPostedFileBase file= Request.Files["file"];  
  9.   
  10.    if(file!= null && file.ContentLength > 0)    
  11.    {  
  12.   
  13.       var fileName = Path.GetFileName(file.FileName);  
  14.   
  15.       file.SaveAs(Path.Combine(location, fileName));  
  16.   
  17.    }  
  18.   
  19.    return RedirectToAction("Index");  
  20.