1

I want to show image in image control on page load. I'm using the following code. My problem is that the image is saved in the database as binary data, but I can't retrieve the image in the image control

public partial class TeacherProfile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        profilepic();        
    }    

    protected void upload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            HttpPostedFile file = FileUpload1.PostedFile;
            Byte[] imgbyte = new Byte[file.ContentLength];
            file.InputStream.Read(imgbyte, 0, file.ContentLength);
            SqlCommand cmd = new SqlCommand("Update Registration set Photo = '" + imgbyte + "'    where id ='" + idd.Text + "' ", con);
            //cmd.Parameters.AddWithValue("@userid", 222);    //image id
            //cmd.Parameters.AddWithValue("@pic", imgbyte);
            //try
            //{
            con.Close();
                con.Open();
                cmd.ExecuteNonQuery();

            con.Close();
                Label1.Text = "Image Uploaded";

            con.Close();
            //}
            //catch
            //{
            //    Label1.Text = "Try Again";
            //}
        }
    }

    public void profilepic()
    {
        SqlCommand cmd2 = new SqlCommand("select Photo from Registration where Username = '" + username1.Text + "'", con);
        //cmd2.Parameters.AddWithValue("@userid", username1.Text);

        con.Open();
        SqlDataReader dr = cmd2.ExecuteReader();

        if (dr.Read())
        {
            byte[] bytes = (byte[])dr["Photo"];
            string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
            Image1.ImageUrl = "data:image/png;base64," + base64String;
            cmd2.ExecuteNonQuery();
            con.Close();
        }
        else
        {
        }
    }
}

Can anybody help me please?

Thanks in advance...

4
  • What is the type of your Photo column, is it varbinary? Commented May 6, 2018 at 17:35
  • No its datatype is image Commented May 6, 2018 at 17:44
  • Does the bytes are updated in table correctly? I guess they way you are updating this field isn't right. Have a look on this answer stackoverflow.com/a/17856781/1433093. To get that data and pass this in image control seems fine to me. Commented May 6, 2018 at 17:51
  • SQL Injection alert - you should not concatenate together your SQL statements - use parametrized queries instead to avoid SQL injection - check out Little Bobby Tables Commented May 6, 2018 at 18:07

1 Answer 1

1

my code for file upload

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="fileUpload.aspx.cs" Inherits="fetchImage.fileUpload" %>

<!DOCTYPE html>

 <html xmlns="http://www.w3.org/1999/xhtml">
 <head runat="server">
 <title></title>
 <style type="text/css">
    .auto-style1 {
        margin-left: 0px;
    }
    .auto-style2 {
        margin-left: 6px;
        margin-top: 0px;
    }
 </style>
</head>
 <body>
 <form id="form1" runat="server">
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <br />
   <div>

        <asp:TextBox ID="TextBox1" runat="server" CssClass="auto-     style1"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" CssClass="auto-style2" OnClick="Button1_Click" Text="Button" />

</div>
</form>
</body>
</html>

file upload cs:




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace fetchImage
{
public partial class fileUpload : System.Web.UI.Page
{
    string path;
    SqlConnection con = new SqlConnection("Data Source=DESKTOP- U0NOKBP\\SQLEXPRESS;Initial Catalog=Lnmi;Integrated Security=True");
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {

        FileUpload1.SaveAs(Request.PhysicalApplicationPath + "/Images/"+           FileUpload1.FileName.ToString());
        path = "Images/"+FileUpload1.FileName.ToString();
        con.Open();
        SqlCommand cmd = con.CreateCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText  = "insert into Images values('"+path.ToString()+"','"+TextBox1.Text+"')";
        cmd.ExecuteNonQuery();
        con.Close(); 
    }
}

}

 for showing the file 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ShowImage.aspx.cs" Inherits="fetchImage.ShowImage" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
 <head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
    <asp:DataList ID="DataList1" runat="server">
        <ItemTemplate>
        <table>
            <tr>
                <td>
                    <img src="<%#Eval("image_path") %>" height="100"  width="100" />
                    <td><%#Eval("title") %></td>
                </td>
            </tr>
        </table>
            </ItemTemplate>
    </asp:DataList>
</div>
</form>
</body>

file show cs :
 using System;
 using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace fetchImage
  {
public partial class ShowImage : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("Data Source=DESKTOP-       U0NOKBP\\SQLEXPRESS;Initial Catalog=Lnmi;Integrated Security=True");
    protected void Page_Load(object sender, EventArgs e)
    {

            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select * from Images";
            cmd.ExecuteNonQuery();
            DataTable dt = new DataTable();
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            sda.Fill(dt);
            DataList1.DataSource = dt;
            DataList1.DataBind();
            con.Close();


    }
}

}

please create a table before proceeding
 create table Images(image_path varchar(MAX), title varchar(50));


   and lastly add a folder Images in your project by right clicking at your project name
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.