Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

How to upload files in ASP.NET MVC 4.0

Dec 19, 2014
Introduction:

In this post I will show you how to upload files(image, doc, mp3 etc..) in MVC 4.0 using Razor as a view engine.

Description:

In previous articles you have shown Asp.net MVC 4 Razor Tutorial with Example for Beginners, Create Image (Photo) Gallery in Asp.net MVC in jQuery using C#, How to make a form and insert data into database using MVC4.0 razor, Show data from a database table content in MVC 4.0 razor. Now in this post you will learn about file uploading in MVC 4.0. As like normal ASP we would not use any server side file up loader tool, we will use simple HTML file up loader tool to upload the file into our destination folder.


So how to do this?? Lets get start. Create a new MVC 4.0 application and add a new controller, name it as HomeController. We will use Index ActionMethod to write the code to upload the file.

We need two ActionMethod named Index, one is for HttpGet and another for HttpPost. Within the HttpGet ActionMethod we don't need to write anything.

Lets create the View first. To create the View right click on the ActionMethod Index and click on the Add View  option.

In the View write down the code.

@{
    ViewBag.Title = "Upload file";
}

<h2>Upload File</h2>
<h3 style="color: green">@ViewBag.Message</h3>
@using (Html.BeginForm("Index", "Home", FormMethod.Post
            , new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary();

    <input type="file" id="fileToUpload" name="file" />
    <span class="field-validation-error" id="spanfile"></span>

    <input type="submit" id="btnSubmit" value="Upload" />
}


Here we have taken a simple HTML file up loader and a submit button. Within the form we are calling the ActionMethod Index, which is present in HomeController. A ValidationSummary to show all validation message.

Now get back to the ActionMethod. Within the Index ActionMethod (HttpPost) write down the code.

[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
      if (ModelState.IsValid)
      {
           if (file == null)
           {
              ModelState.AddModelError("File", "Please Upload Your file");
           }
           else if (file.ContentLength > 0)
           {
              int MaxContentLength = 1024 * 1024 * 4; //Size = 4 MB
              string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
           if (!AllowedFileExtensions.Contains
(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
           {
                 ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
           }
           else if (file.ContentLength > MaxContentLength)
           {
                 ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
            }
            else
            {
                 var fileName = Path.GetFileName(file.FileName);
                 var path = Path.Combine(Server.MapPath("~/Upload"), fileName);
                 file.SaveAs(path);
                 ModelState.Clear();
                 ViewBag.Message = "File uploaded successfully. File path :   ~/Upload/"+fileName;
             }
         }
     }
     return View();
}


Before run this project don't forget to create a Upload folder within root directory, otherwise you will get an error.

HttpPostedFileBase file getting the file which you are uploading.

file.ContentLength : Size of the file
file.FileName : file name with extension




If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

4 comments :

Anonymous said...

Nice and Simple.

Anonymous said...

Its nice..Thank You

Unknown said...

simple and nice

Unknown said...

i asked code but the linke u returend is not the code why?

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.