User Id :    Password :      New Member   Forgot Password  
 
How to upload file in ASP.NET MVC3
Description If you are a web developer you often need to upload file on the web server or database. In this post I am going explain how we can upload file in ASP.NET MVC 3 with razor syntax.   No. of Views     2257
  Rating     0
Author Jalpesh Vadgama   Posted On     06 May 2012
Tags ASP.NET,Server Control,ASP.NET-MVC    

Sample Code   Download Code

 

If you are a web developer you often need to upload file on the web server or database. In today’s post I am going explain how we can upload file in ASP.NET MVC 3 with razor syntax.
 

@{
    ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>
<p>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <label for="file">Upload Image:</label>
        <input type="file" name="file" id="file"/>
        <input type="submit" value="Upload Image" />
    }
</p>

 

Here you can see that I have used Html.Begin form to create a form with multipart as we all know this attribute is required to have to upload any kind of file to the server. Also I have used the simple HTML file control and a submit button to submit a form. Now we are done with HTML so it’s time to write server-side code.Following is a code for that.

 

[HttpPost]
       public ActionResult Index(HttpPostedFileBase file)
       {
           string path = System.IO.Path.Combine(Server.MapPath("~/Images"), System.IO.Path.GetFileName(file.FileName));
           file.SaveAs(path);
           ViewBag.Message = "File uploaded successfully";
           return View();
       }


As you can see I have create a new ActionResult Index with parameter and I have given HttpPost attribute to it to get all data from post method of form we are submitting and then I have written a code to save file in Images folder.

That’s it. We are dong with coding now its time to run the application. Once you press F5 it will look into the browser like following.



 

Now once you select file and click on upload image it will upload files and give a message like following.




We are done. Hope you like it. Stay tuned for more updates. Till then Happy programming.

 

 

About Author

About Author I am jalpesh vadgama an Microsoft MVP for Visual C# and BrainBench Certified ASP.NET Developer having more then 5 years of experience in .NET Technology.Please feel free to contact me for any queries via posting comments on my blog I will try to reply as early as possible. Please also visit my blog at http://jalpesh.blogspot.com/ Jalpesh Vadgama
No Photo
 
Country India
Company N/A
Home Page http://jalpesh.blogspot.com/

Rate this article

Rating options from poor, fair, good, very good to excelent.  
 

Comments

   
Write your comment here.
Comment
Verification Code