Hi, In this blog I am writing sample code to store file name and path into database table using Entity framework code first approach.
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)
Step 8: Run and see output.
Output:
Can you also show the download?
How can I display the list of files in the folder?
Nice article