Introduction:-

In this article, I will look at how to upload a file using ASP.NET MVC3.

View for Interface:-

Now we need a View to Give the User Interface for upload a file in this application.

In Index.cshtml
@{

    ViewBag.Title = "Http File Upload";
}
<h2>File Upload</h2>
<form method="post" enctype="multipart/form-data">
<label for="file">Upload Image:</label>
<input type="file" name="file" id="file"/ >
<input type="submit" value="Upload Image"/>
</form>

 

 ·          After written above code the output will below.


HTTP File Upload with ASP.NET MVC 3

In HomeController:-
        public class HomeController : Controller
              {
                     //
                     // GET: /Home/ 
                     public ActionResult Index()
                     {
                           return View();
                     } 
                     [HttpPost] //this line for Form method POST in Index.cshtml
                     public ActionResult Index(HttpPostedFileBase file) [1]                      {
                           var fileName = Path.GetFileName(file.FileName);[2]
                           if (fileName != null) [3]
                            file.SaveAs(Server.MapPath("~\\files\\" + fileName)); [4]
                            return View();
                     }
              }      

 

[1]. That the argument to the Index action method is an instance(file) of HttpPostedFileBase.

[2]. Here is declare a fileName variable for contain the file name which you want to upload. GetFileName() is a static method of Path class which is get the file name from file instance through the FileName property.

[3]. Here is check fileName is not null if statement will return true then new line execute.

[4]. SaveAs() a method of  HttpPostedFileBaseclass   Which is save the file in our application folder which is given location in Server.MapPath() method.

 

      ·         Now press Ctrl+F5 for Run the Application.

 

HTTP File Upload with ASP.NET MVC 3

 

 ·        Now select any file for upload through the Browse... button.

 

HTTP File Upload with ASP.NET MVC 3

 

  •     After selected file click Upload File... Button. 

 ·         Now Goto on the solution Explorer and Refresh your Solution Explorer and see your uploaded file in files folder with selected file name.

 

HTTP File Upload with ASP.NET MVC 3


  Modified On Nov-25-2017 12:28:47 AM

Leave Comment