Resolved How to display an image from SQL Server?

Anonymous

Well-known member
Joined
Sep 29, 2020
Messages
94
Programming Experience
Beginner
I have added a column for photo in my table

C#:
alter table DailyMsg add Photo varbinary(max);

This is my stored procedue

C#:
create proc sp_viewImage
as
begin
select Photo from DailyMsg
end

Function to connect to database and return value

C#:
 public byte[] getPhoto()
        {
            SqlCommand com = new SqlCommand("sp_viewImage", con);
            com.CommandType = CommandType.StoredProcedure;
            con.Open();
            byte[] photo = (byte[])com.ExecuteScalar();
            //string Base64String = Convert.ToBase64String(photo, 0, photo.Length);
            con.Close();
            return photo;
        }


Controller
C#:
 public ActionResult Index()
        {
            DailyMsg dailyMsg = new DailyMsg();
            dailyMsg.msg = dailyMsgs.ViewDailyMessage();
            dailyMsg.Photo = dailyMsgs.getPhoto();
            return View(dailyMsg);
        }

What I have now is the byte array and I am confused as how to get this to display the actual image.

My view

C#:
@model @WebPortal.Models.DailyMsg

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<div>
    @Model.msg
</div>

<img src = 'URL'><\img>
 
Here's an example that does what you want:

 

Latest posts

Back
Top Bottom