Skip to main content

File Upload in ASP.NET MVC3

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.

So, first thing we need to create a view that will contain the file upload control. I am going to use an existing asp.net mvc template for this demo. So I have just modified the default Index view like following.


@{
    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.

How to upload file in asp.net mvc3

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

File Upload in ASP.NET MVC 3

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

kick it on DotNetKicks.com

Comments

  1. Great Article :)

    We can also submit our .net related links on http://www.dotnettechy.com to improve traffic.

    The dotnettechy.com is a community of .Net developers joined together to learn, to teach, to find solutions, to find interview questions and answers, to find .net website / blog collection and to have fun programming. 

    ReplyDelete
  2. @Carpet Store Little Rock   Cibolo - Thanks for compliments!!

    ReplyDelete
  3. thank you so much for this brilliant post ^^

    ReplyDelete
  4. @b08899aec24ae4662cf3ec615c53f089:disqus - thanks buddy

    ReplyDelete
  5. Hey, I wanna do this also, but this time the file i'm trying to save is an attribute of another class, so in the Create method in the Controller, i have the following:
    [HttpPost]public ActionResult Create(HttpPostedFileBase file, Newsletter newsletter)
    { /*.... code to be executed */ }

    The problem is the "file" parameter is always null, and the other object, "newsletter" has a string attribute called "templateUrl", the route of the file I'm trying to save on the server.

    I know I must be wrong somewhere, but I don't know where. Thank you for this!

    ReplyDelete
  6. Hello,


    What you need to do a create another partial class of model and create a property of HttpPostedFile UploadFile.


    like below.


    public partial class newsletter
    {
    //Your original class
    }


    public partial class newsletter{ HttpPostedFile UploadFile{get;set;}}


    [Authorize]
    [HttpPost]
    public ActionResult Create(Newsletter newsletter)

    {
    //Here you will get UploadFile and process as you want

    }



    I will write a blog post about this.

    ReplyDelete
  7. Really, awesome post.modal view controller is most part of .net to develop more attractive website.

    ReplyDelete





  8. The ASP.NET MVC 4 framework Mobile web development Cloud architecture and development Best practices for using HTML5, CSS, Javascript, and jQuery


    ReplyDelete
  9. You ought to search into the brand upgrades accessible for BE blogs. I consider yours may really benefit from it.

    ReplyDelete
  10. @adammoon:disqus - Thanks for your comments and for the visit of my blog. I am unable to understand what you want to say. Can you please let me know your views in detail.

    ReplyDelete
  11. Consequently it simplifies the application development in a extremely distributed surroundings.

    ReplyDelete
  12. Nice one but the path saved in the database should only be for the image folder on my project but not including C:/.../ how can i solve this. thanks

    ReplyDelete
  13. This is awesome!! really helpful for me. Thanks for sharing with us. Following links also helped me to complete my task.

    http://www.mindstick.com/Articles/1d931eb6-5fa8-4509-a8f8-ce76c23f814f/?HTTP%20File%20Upload%20with%20ASP%20NET%20MVC%203

    http://www.dotnetpools.com/Article/ArticleDetiail/?articleId=44

    ReplyDelete
  14. I don't understand what you want to say. Please describe it briefly

    ReplyDelete
  15. This has been resolved. Thanks Jalpesh

    ReplyDelete
  16. Glad to know that you are able to resolve it. Thanks for reading my blog

    ReplyDelete
  17. Can we upload a file to the web server without browsing it from the system.I mean knowing the path of the file,can we directly upload a file from a known path in one click.

    ReplyDelete
  18. OK, it seems its really very easy in MVC 4, compared to how much effort it was earlier on (until so far i used a third party component, but since its so easy i can now use the built-in stuff, great)

    ReplyDelete

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Popular posts from this blog

How to create Rest API(Web API) with ASP.NET Core 1.0

Recently Microsoft has released ASP.NET Core 1.0 RC2, I am getting lots of request from readers that about creating Web API. So I thought it will be a good idea to write a blog post about how to create Rest API(Web API) with ASP.NET Core 1.0.

So let’s get started via creating an ASP.NET Core 1.0 Web Application like following.



Once you click on ASP.NET Web Application, It will ask whether you need to create Web Application or Web API application. We are going to Web API so I am going to select Web API Application like following. Please note that in ASP.NET Core 1.0 there is no separate libraries or DLLs required for creating web APIs. This is just a project template.



Now once you click on OK It will create a Web API application with default values controller and program.cs.  As you know Program.cs is now starting point for the ASP.NET Core 1.0 application so It contains all the required configuration and startup items. Following is a code for that.
using System.IO; using Microsoft.Asp…

How to use migration with Entity Framework Core

Entity framework core is  the lightweight, extensible and cross-platform version of Entity Framework. Before some time, Microsoft has Released a new version of Entity Framework RC2. I have written a couple of blog post about Entity framework code first migration earlier for Entity framework 6.0. So there was a couple of request coming for writing a blog post about Entity Framework Core RC2 migration. So I thought it will be a good idea to give an overview how database migration works in Entity Framework Core RC2. This post will cover a basic scenario where we are going to create the database with existing ASP.NET Identity migration and then we are going to create a new model and have that migration applied in the database.

How to use Entity Framework Migrations: Let’s get started, To demonstrate entity framework core migrations, I am going to create a sample asp.net core web application like following.



Once we select asp.net core application it will appear the following dialog.



Now w…

Solution: gulp is not recognized as internal or external command- Visual Studio

Recently, After Upgrading to the newer version of Gulp, I was getting this error.  After doing lots of  finding online and in my system I was able to figure out that Modules like Gulp does not installed to the path. So when you try to run it from the command line it was showing below error.
gulp is not recognized as internal or external command How to solve : gulp is not recognized as internal or external command To solve this error we just need to create a new environment variable and set the NPM modules path there.

To create an environment variable,  Right click My Computer/ This Pc and click on properties.  It will open following windows.



Go to Advance System Settings and it will open system properties windows like below.



Click on Environment Variables it will open an environment and system variables windows like below.



Click on new System variable and put NODE_PATH in system variable name and %AppData%\npm\node_modules into the variable value like below.



Click on Ok. That’s it. N…