Home > DeveloperSection > Beginner > Upload File in Asp.Net Mvc 4

Upload File in Asp.Net Mvc 4


ASP.NET MVC ASP.NET MVC 
Ratings:
4 Comment(s)
 5562  View(s)
Rate this:

Upload File in Asp.Net Mvc 4

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 { getset; }

        public string Title { getset; }

    }

}

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 { getset; }

    }

}

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="width400px;">

    @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))

    {

        <div style="width100%floatleft;">

            <div style="width100pxfloatleft;">

                <label>Title </label>

            </div>

            <div style="width200pxfloatleft;">

                <input type="text" id="Title" name="Title" />

            </div>

        </div>

        <div style="width100%floatleft;">

            <div style="width100pxfloatleft;">

                <label>Upload File </label>

            </div>

            <div style="width200pxfloatleft;">

                <input type="file" name="file" id="file" />

            </div>

        </div>

        <div style="width100%floatleft;">

            <div style="width300pxfloatright;">

                <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.

 


Nice article

By Chintoo Semi on   2 years ago
Nice article

UploadFile Multiple files

By Arslan Mehboob on   2 years ago
plz help me i want uploadfile multiple files at a time  in asp.net mvc 4

Upload Error

By A Mc on   7 months ago
Hi, nice article, thanks.
I am using MVC 5 in visual Studio 2015.
When uploading a file, 'File Uploaded Successfully ' message appears, but jpg file is not being saved to database.
Any suggestions?
Thanks.

Upload Error

By A Mc on   7 months ago
Hi, nice article, thanks.
I am using MVC 5 in visual Studio 2015.
When uploading a file, 'File Uploaded Successfully ' message appears, but jpg file is not being saved to database.
Any suggestions?
Thanks.

Don't want to miss updates? Please click the below button!

Follow MindStick