Uploading Files In ASP.NET MVC Using HttpPostedFileBase

In earlier ASP.NET file upload control we needed to write lots of code to upload files, validate file extension and get files from upload control. Also lots of server resources were involved due to server control. Now in this article we will learn how to upload files with minimum code in ASP.NET MVC using HttpPostedFileBase.
Step 1: Create an MVC Application.
Now let us start with a step by step approach from the creation of a simple MVC application as in the following:
  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
  2. Click "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear:
 Step 2: Create Model Class
Now let us create the model class named FileUploadModel.cs by right clicking on Models folder as in the following screenshot:
 Note: 

It is not mandatory that Model class should be in Model folder, it is just for better readability. You can create this class anywhere in the solution explorer. This can be done by creating different folder name or without folder name or in a separate class library.

FileUploadModel.cs class code snippet:
    public class FileUploadModel   
      {    
          [DataType(DataType.Upload)]    
          [Display(Name = "Upload File")]    
          [Required(ErrorMessage = "Please choose file to upload.")]    
          public string file { get; set; }    
        
      }   
Step 3 : Add Controller Class.
Now let us add the MVC 5 controller as in the following screenshot:

 After clicking on Add button it will show the window. Specify the Controller name as FileUpload with suffix Controller.

Note:
The controller name must be having suffix as 'Controller' after specifying the name of controller. Now lets modify the default code in FileUploadController.cs to read uploaded files now FileUploadController.cs file then the code will look like as follows,
FileUploadController.cs

using System;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace UploadingFilesUsingMVC.Controllers
{
    public class FileUploadController : Controller
    {
        // GET: FileUpload
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult UploadFiles(HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                try
                {

                    if (file != null)
                    {
                        string path = Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(file.FileName));
                        file.SaveAs(path);

                    }
                    ViewBag.FileStatus = "File uploaded successfully.";
                }
                catch (Exception)
                {

                    ViewBag.FileStatus = "Error while file uploading.";
                }

            }
            return View("Index");
        }
    }
}
Step 4 : Creating strongly typed view named Index using FileUploadModel class .
Right click on View folder of created application and choose add view, select FileUploadModel class and create scaffolding template to create view to upload files as,

 Click on Add button, then it will create the view named index. Now open the Index.cshtml view, then the following default code you will see which is generated by MVC scaffolding template as,
Index.cshtml

@model UploadingFilesUsingMVC.Models.FileUploadModel

@{
    ViewBag.Title = "www.compilemode.com";
}

@using (Html.BeginForm("UploadFiles", "FileUpload", FormMethod.Post,new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.file, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.file, new { htmlAttributes = new { @class = "form-control", @type="file"} })
                @Html.ValidationMessageFor(model => model.file, "", new { @class = "text-danger" })
            </div>
        </div>
        
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Upload" class="btn btn-primary" />
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10 text-success">
                @ViewBag.FileStatus
            </div>
        </div>
    </div>
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

Step 4 : Create a folder named UploadedFiles or as you wish to save uploaded files,
Right click on created ASP.NET MVC application, solution explorer and choose add new item, then Add New Folder. After adding the model, view, controller and UploadedFiles folder to save the file. Solution explorer will look like as follows,


Now we have done all coding to upload files.
Step 5: Now run the application. After running the application initial screen will look as follows,

 Now click on Upload button without selecting file then the following error message is visible which we have defined in model class as,

 Now browse the file and click on upload button, It will show the following message after successfully uploading the file as,


Now lets see the UploadedFiles folder where our uploaded files are saved, Browse the folder or move the mouse cursor or image then uploaded image will look like as follows,

 I hope from all the preceding examples we have learned how to upload files using strongly typed file uploader in ASP.NET MVC .
Note:

  • HttpPostedFileBase instance name must be a file.
  • Model class property name must be file so it can generate the input type file .
  • Its important to define enctype = "multipart/form-data" in form action otherwise file value will be null in controller .
  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
Summary
I hope this article is useful for all readers. If you have any suggestions please contact me.
Read more articles on ASP.NET MVC:

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode