Monday, December 22, 2014

How to upload a file in MVC 4.0 Razor

In this tutorial I will show you how to upload a files in ASP.NET MVC 4.0. 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

Now run your project and enjoying your uploading.

Download the full source code here.


0 comments:

Post a Comment

Popular Posts

Pageviews