Web
Analytics
File Upload in Database Using Entity Framework Code First MVC | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

Hi, In this blog I am writing sample code to store file name and path into database table using Entity framework code first approach.

Download Source Code

Step: 1 First Create Controller named Home Controller .

Step 2: Create Index.cshtml view into Index Action of Home controller.

public ActionResult Index()
{
return View();
}




Step 3: Write following code into Index.cshtml

@model FileUpload.Models.FileUploadModel
@{
Layout = null;
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{



}

Step 4 : CReate two classes into Models folder (DataContext.cs and FileUploadModel.cs)

Note : Install Entity Framework in your project using package manager console.

install-package entityframework

DataContext.cs

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace FileUpload.Models
{
public class DataContext :DbContext
{
public DataContext() : base("conn") { }
public DbSet fileuploadmodels { get; set; }
}
}

FileUploadModel.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace FileUpload.Models
{
[Table("filesupload")]
public class FileUploadModel
{
[Key]
public int id { get; set; }
public string FileName { get; set; }
public string FilePath { get; set; }
}
}

Step 5: Write Index Action with HttpPost Attribute in Home Controller.

[HttpPost]
public ActionResult Index([Bind(Include="FileName, FilePath")] FileUploadModel fm1, HttpPostedFileBase fileupload1)
{
string filename = string.Empty;
string filepath = string.Empty;

filename = fileupload1.FileName;
string ext = Path.GetExtension(filename);
if (ext == ".jpg" || ext == ".png")
{
DataContext db = new DataContext();
filepath = Server.MapPath("~//Files//");
fileupload1.SaveAs(filepath + filename);

fm1.FileName = filename;
fm1.FilePath = "~//Files//";

db.fileuploadmodels.Add(fm1);

// db.Entry(model).State = EntityState.Modified;

db.SaveChanges();

return Content("file is uploaded successfully");

}
else
{
return Content("You can upload only jpg or png file");
}
return View();
}
}




Step 6: Write Connection string into web.config

Step 7: Create Database Table (filesupload)

Database

Step 8: Run and see output.

Output:

Animation

ASP.NET Core 2.0 Online Training

ASP.NET Core 2.0 Online Traininghttps://yogeshdotnet.comonline-training/