Upload File To Server in ASP.Net MVC 4

Introduction

This article explains how to upload a file to a server in ASP.NET MVC 4.

Step 1: Create New Project

Go to "File" -> "New" -> "Project..." then select "ASP.NET MVC4 Web Application" then enter Application Name then click "OK" then select "Internet Application" then select "View Engine Razor" then click "OK".

Step 2: Add a new controller

Go to Solution Explorer then right-click on the Controllers folder from Solution Explorer then seelct "Add" > "Controller" then enter the Controller name then select the Templete "Empty MVC Controller".

Step 3: Add new action into your controller for uploading file

Here I added a "file” action for the file uploading. You can access the posted file directly through the HttpPostedFilesBase object due to model binding.

  1. public ActionResult file()  
  2. {  
  3.     return View();  
  4. }  
  5. [HttpPost]  
  6. public ActionResult file(HttpPostedFileBase file)  
  7. {  
  8.     if (file != null && file.ContentLength > 0)  
  9.     try  
  10.     {  
  11.         string path = Path.Combine(Server.MapPath("~/Content/files"),  
  12.         Path.GetFileName(file.FileName));  
  13.         file.SaveAs(path);  
  14.         ViewBag.Message = "File uploaded successfully";  
  15.     }  
  16.     catch (Exception ex)  
  17.     {  
  18.         ViewBag.Message = "ERROR:" + ex.Message.ToString();  
  19.     }  
  20.     else  
  21.     {  
  22.         ViewBag.Message = "You have not specified a file.";  
  23.     }  
  24.     return View();  
  25. }  
Step 4: Add view for the action.

Right-click on the Action Method then select "Add View" then enter the View Name then select "View Engine" then "Add".

Our form method is POST and the form encoding type is "multipart/form-data". These parameters are required for uploading binary data to the server.
  1. @{  
  2.     ViewBag.Title = "file";  
  3. }  
  4.   
  5. <h2>Upload file</h2>  
  6. @using (Html.BeginForm ("file""upload", FormMethod.Post,   
  7.                          new { enctype = "multipart/form-data" }))   
  8. {   
  9.     <input type="file" name="file" id="file"/><br><br>   
  10.     <input type="submit" value="Upload file"/>   
  11.     <br><br>   
  12.     @ViewBag.Message   
  13. }  
Your view will look like:

 



After uploading the file you can see your file in your project directory location ~/Content/files.