Hi ramitaherwahd...,
Refering this article i have created the example.
Model
public class FileModel
{
public int Id { get; set; }
public string Name { get; set; }
public string ContentType { get; set; }
public byte[] Data { get; set; }
}
Namespaces
using System.IO;
using System.Data.SqlClient;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
Controller
public class HomeController : Controller
{
private IConfiguration Configuration;
public HomeController(IConfiguration _configuration)
{
Configuration = _configuration;
}
public IActionResult Index()
{
return View(this.GetFiles());
}
[HttpPost]
public IActionResult UploadFile(IFormFile postedFile)
{
string fileName = Path.GetFileName(postedFile.FileName);
string contentType = postedFile.ContentType;
using (MemoryStream ms = new MemoryStream())
{
postedFile.CopyTo(ms);
string constr = this.Configuration.GetConnectionString("MyConn");
using (SqlConnection con = new SqlConnection(constr))
{
string query = "INSERT INTO tblFiles VALUES (@Name, @ContentType, @Data)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Name", fileName);
cmd.Parameters.AddWithValue("@ContentType", contentType);
cmd.Parameters.AddWithValue("@Data", ms.ToArray());
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
return RedirectToAction("Index");
}
private List<FileModel> GetFiles()
{
List<FileModel> files = new List<FileModel>();
string constr = this.Configuration.GetConnectionString("MyConn");
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT Id, Name, Data FROM tblFiles"))
{
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
files.Add(new FileModel
{
Id = Convert.ToInt32(sdr["Id"]),
Name = sdr["Name"].ToString(),
Data = (byte[])sdr["Data"]
});
}
}
con.Close();
}
}
return files;
}
}
View
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model IEnumerable<Upload_File_Database_MVC_Core.Models.FileModel>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="UploadFile">
<input type="file" name="postedFile" />
<input type="submit" id="btnUpload" value="Upload" />
</form>
<hr />
<table id="tblFiles" cellpadding="0" cellspacing="0">
<tr>
<th style="width:50px">File ID</th>
<th style="width:120px">File Name</th>
<th style="width:80px">Photo</th>
</tr>
@foreach (var file in Model)
{
<tr>
<td>@file.Id</td>
<td>@file.Name</td>
<td><img src='@string.Format("data:image/png;base64,{0}", Convert.ToBase64String(file.Data))' alt="@file.Name" /></td>
</tr>
}
</table>
</body>
</html>
Screenshot