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;

            //Image CODE
            if (postedFile != null)
            {
                byte[] bytes;
                using (BinaryReader br = new BinaryReader(postedFile.InputStream))
                {
                    bytes = br.ReadBytes(postedFile.ContentLength);
                    modal.UserImage = bytes;
                }
            }
           

            // Call the method here to update the USER record.
            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();

            //Image Code
            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>
       }

Are there any code examples left?
Create a Free Account
Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
Sign up
Develop soft skills on BrainApps
Complete the IQ Test
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source