how to get image from database in mvc code example
Example: how to store and retrieve image from sql database using c# in mvc
BY LOVE
Note : - name attribute of the image file must match with the action parameter
- Datatype of Image column in sql will be varbinary(max)
1- CSHTML page code
@using (Html.BeginForm("UserProfile", "UserHome", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" id="postedFile" name="postedFile" class="custom-file-input" border="1">
<input type="submit" class="btn btn-primary" value="Save Changes">
}
2- Controller code
[HttpPost]
public ActionResult UserProfile(UserProfileViewModal modal, HttpPostedFileBase postedFile)
{
User objUser = new User();
objUser.First_Name = modal.FirstName;
objUser.Last_Name = modal.LastName;
objUser.Email = modal.Email;
objUser.Company = modal.Company;
objUser.Address = modal.Address;
objUser.TimeZone = modal.TimeZone;
objUser.UserName = modal.UserName;
objUser.Password = modal.Password;
if (postedFile != null)
{
byte[] bytes;
using (BinaryReader br = new BinaryReader(postedFile.InputStream))
{
bytes = br.ReadBytes(postedFile.ContentLength);
modal.UserImage = bytes;
}
}
string Query = "Update Users set Password='" + modal.Password + "', First_Name='" + modal.FirstName + "', Last_Name='" + modal.LastName + "'," +
"Email='" + modal.Email + "', Address='" + modal.Address + "', Company='" + modal.Company + "', TimeZone='" + modal.TimeZone + "' where UserName='" + modal.UserName + "'";
objUsersBLL.UpdateUserData(Query, out Exception ex);
Query = "Update Users set UserImage=@imgByte where UserName='" + modal.UserName + "'";
using (SqlCommand cmd = new SqlCommand(Query))
{
cmd.Parameters.AddWithValue("@imgByte", modal.UserImage);
objUsersBLL.UpdateUserDataImageScalarSQL(cmd, out Exception exs);
}
return RedirectToAction("UserProfile");
}
3- Controller code to get image from database
[HttpGet]
public ActionResult UserProfile()
{
string UserName = "";
if (TempData["Username"] != null)
{
UserName = TempData["Username"].ToString();
TempData.Keep("Username");
}
User user = objUsersBLL.GetUserDettailsEnityList(UserName, out Exception ex);
UserProfileViewModal objUserProfileViewModal = new UserProfileViewModal();
if (user.UserImage != null)
{
ViewBag.Base64String = user.UserImage;
}
return View(objUserProfileViewModal);
}
4- Now showing the image on CSHTML page from the viewbag
if (ViewBag.Base64String != null)
{
<img style="height:100px; width:100px;" alt="" src="data:image/jpg;base64,@Convert.ToBase64String(ViewBag.Base64String)" />
}
else
{
<p>No image</p>
}