Introduction:

In this article, we will explain how to upload file or images in ASP.NET MVC with example.

Description:
Let us implement these in a sample Application to upload file in ASP.Net MVC application. Open Visual Studio and click on New Project link.

how to Upload Files In ASP.NET MVC

In the following figure select “Templates”, Visual C#, then ASP.NET Web Application, and here I give the name of project “Uploadfile”.
You can give the project name as you wish.
And then click on “OK” button

how to Upload Files In ASP.NET MVC

Select MVC Empty Template. Click OK.

how to Upload Files In ASP.NET MVC

Adding Folder

We will add a folder to store the files in the application. Here, I have added a folder in the application.

how to Upload Files In ASP.NET MVC

Adding Controller

Let us add a controller. Right click on the Controller. Add->Controller.

how to Upload Files In ASP.NET MVC


Give a suitable name to the controller.

how to Upload Files In ASP.NET MVC

Write the following code in the controller.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace Uploadfile.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(HttpPostedFileBase file)
        {
            try
            {
                if (file.ContentLength > 0)
                {
                    string _FileName = Path.GetFileName(file.FileName);
             string _path = Path.Combine(Server.MapPath("~/UploadFile"),_FileName);
                    file.SaveAs(_path);
                }
                ViewBag.Message = "File Uploaded Successfully!!";
                return View();
            }
            catch
            {
                ViewBag.Message = "File upload failed!!";
                return View();
            }
        }
 
    }
}
 

Adding View

Right click on index ActionResult. Go to Add View.

how to Upload Files In ASP.NET MVC

Select the empty template. Click add.

how to Upload Files In ASP.NET MVC

Write the following code in the View.

@{
    ViewBag.Title = "Index";
}
 
<h2>UploadFile</h2>
 
@using (Html.BeginForm("index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
 
    <div>
        @Html.TextBox("file", "", new { type = "file" }) <br />
 
        <input type="submit" value="Upload" />
 
        @ViewBag.Message
 
    </div>
 
 
}

Browse the Application

Let us now run the Application and check if it is working fine or not. Browse the Application.

how to Upload Files In ASP.NET MVC

Choose file and Click upload button verify that the file gets uploaded successfully.

how to Upload Files In ASP.NET MVC

I hope this post is useful to developers.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

you may also like