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.


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


Select MVC Empty Template. Click OK.


Adding Folder

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


Adding Controller

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



Give a suitable name to the controller.


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.


Select the empty template. Click add.


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.


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


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.

Welcome to SQL Tutorials Point

Don't have an account? Click here to Create a new account, it takes less than a minute.