articles

Home / DeveloperSection / Articles / Upload File in Asp.Net Mvc 4

Upload File in Asp.Net Mvc 4

Sumit Kesarwani14534 26-Aug-2014

In this article, I’m explaining how to upload image in an asp.net mvc 4 application.

Step 1

First create a table in database named “UploadFile” like this:

Upload File in Asp.Net Mvc 4

Step 2

Now create a basic asp.net mvc 4 application and add a class named “UploadFile”

like this:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
 
namespace UploadFileMvcApp.Models
{
    [Table("UploadFile")]
    public class UploadFile
    {
        [Key]
        public int FileId { get; set; }
        public string Title { get; set; }
    }
}

Step 3

Now add another class named “FileContext” like this:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
 
namespace UploadFileMvcApp.Models
{
    public class FileContext : DbContext
    {
        public DbSet<UploadFile> Files { get; set; }
    }
}

Step 4

Now add a controller to the project named “HomeController” and write the below

code in it:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UploadFileMvcApp.Models;
 
namespace UploadFileMvcApp.Controllers
{
    public class HomeController : Controller
    {
        FileContext db = new FileContext();
 
        public ActionResult Index()
        {
            return View();
        }
 
        [HttpPost]
        public ActionResult Index(string Title, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                UploadFile files = new UploadFile();
                files.Title = Title;
                db.Files.Add(files);
                db.SaveChanges();
 
                int Id = (from a in db.Files select a.FileId).Max();
 
                if (Id > 0)
                {
                    if (Request.Files["file"].ContentLength > 0)
                    {
                        string extension = Path.GetExtension(Request.Files["file"].FileName);
                        string path = string.Format("{0}/{1}{2}", Server.MapPath("/Files"), Id, extension);
 
                        Request.Files["file"].SaveAs(path);
 
                        ViewData["Message"] = "File Uploaded Successfully";
 
                    }
                    else
                    {
                        ViewData["Message"] = "File Uploaded Failed";
                    }
                }
            }
            return View();
        }
    }
}

 

Step 5

Now add a view named “Index” to the project and write the below code in it:

@{
    ViewBag.Title = "Index";
}
 
<h2>Upload File Samle</h2>
<div style="width: 400px;">
    @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <div style="width: 100%; float: left;">
            <div style="width: 100px; float: left;">
                <label>Title </label>
            </div>
            <div style="width: 200px; float: left;">
                <input type="text" id="Title" name="Title" />
            </div>
        </div>
        <div style="width: 100%; float: left;">
            <div style="width: 100px; float: left;">
                <label>Upload File </label>
            </div>
            <div style="width: 200px; float: left;">
                <input type="file" name="file" id="file" />
            </div>
        </div>
        <div style="width: 100%; float: left;">
            <div style="width: 300px; float: right;">
                <input type="submit" id="btnSubmit" name="Upload" />
            </div>
        </div>
    }
</div>
<div>
    @if (ViewData["Message"] != "")
    {
        @ViewData["Message"]
    }
</div>

 

Step 6

Now add the connection string in the web.config file like this:

<connectionStrings>
    <add name="FileContext" connectionString="Data Source=Uttam-PC4; Initial Catalog=SumitTesting;user id=userid;password=password;" providerName="System.Data.SqlClient"/>
  </connectionStrings>
 

Step 7

Now add a folder to the project like this:

Upload File in Asp.Net Mvc 4

Output

Now run the application:

Upload File in Asp.Net Mvc 4

Upload File in Asp.Net Mvc 4

Click on submit button:

Upload File in Asp.Net Mvc 4

Now open the Files folder from the Visual Studio like this:

Upload File in Asp.Net Mvc 4

 

Upload File in Asp.Net Mvc 4

As you see that your image file has been uploaded.

 


Updated 30-Jun-2020

Leave Comment

Comments

Liked By