简体   繁体   中英

How can i display an image to ImageButton asp.net c#

This Updates the database by inserting the image file to avatar column. The uploading to database works but it wont display in image button.

protected void imgProfile_Click(object sender, ImageClickEventArgs e)
{
    SqlConnection connection = null;
    try
    {
        FileUpload img = (FileUpload)ofd;
        Byte[] imgByte = null;
        if (img.HasFile && img.PostedFile != null)
        {
            //To create a PostedFile
            HttpPostedFile File = ofd.PostedFile;
            //Create byte Array with file len
            imgByte = new Byte[File.ContentLength];
            //force the control to load data in array
            File.InputStream.Read(imgByte, 0, File.ContentLength);
        }
        // Insert the employee name and image into db
        string conn = ConfigurationManager.ConnectionStrings["SE255_AFloresConnectionString2"].ConnectionString;
        connection = new SqlConnection(conn);

        connection.Open();
        string sql = "UPDATE Users SET Avatar = ('" + imgByte + "') OUTPUT INSERTED.User_ID WHERE Username = ('" + Session["UserName"].ToString() + "')";
        SqlCommand cmd = new SqlCommand(sql, connection);

        int id = Convert.ToInt32(cmd.ExecuteScalar());
        userid.Text = "<script>alert('" + String.Format("Employee ID is" +" "+ id) + "')</script>";
        userid.Visible = false;

        //display
        imgProfile.ImageUrl = "~/Handler1.ashx?id=" + id;
    }
    catch
    {
        //lblResult.Text = "There was an error";
    }
    finally
    {
        connection.Close();
    }

This Part is where i am stuck on it wont display it on image button please help

public void ProcessRequest(HttpContext context)
{
    Int32 empno;
    if (context.Request.QueryString["User_ID"] != null)
        empno = Convert.ToInt32(context.Request.QueryString["User_ID"]);
    else
        throw new ArgumentException("No parameter specified");

    context.Response.ContentType = "image/jpeg";
    Stream strm = ShowEmpImage(empno);
    byte[] buffer = new byte[4096];
    int byteSeq = strm.Read(buffer, 0, 4096);

    while (byteSeq > 0)
    {
        context.Response.OutputStream.Write(buffer, 0, byteSeq);
        byteSeq = strm.Read(buffer, 0, 4096);
    }       
}
public Stream ShowEmpImage(int empno)
{

    string conn = ConfigurationManager.ConnectionStrings["SE255_AFloresConnctionString2"].ConnectionString;
    SqlConnection connection = new SqlConnection(conn);
    string sql = "SELECT Avatar FROM Users WHERE User_ID = @ID";
    SqlCommand cmd = new SqlCommand(sql, connection);
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@ID", empno);
    connection.Open();
    object img = cmd.ExecuteScalar();
    try
    {
        return new MemoryStream((byte[])img);
    }
    catch
    {
        return null;
    }
    finally
    {
        connection.Close();
    }
}

This is the .aspx file

    <script type="text/javascript" >
    function clk() {
        var ofd = document.getElementById('<%=ofd.ClientID%>');
        ofd.click();
    }

<asp:Label ID="lblUser" runat="server"></asp:Label>
<asp:Label ID="userid" runat="server"></asp:Label>


<div style="width:100%;">
    <asp:ImageButton ID="imgProfile" CssClass="img-circle img img-rounded" runat="server" Height="100px" Width="100px" OnClientClick="clk();" OnClick="imgProfile_Click"></asp:ImageButton>
    <div style="display:none">
    <asp:FileUpload ID="ofd" runat="server" />
</div>
</div>
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
imgProfile.ImageUrl = "data:image/png;base64," + base64String;

Try the above lines in a method that fetches the image bytes from the database. To do this you don't even need ashx handler. Hope it will help you out.

To make it better way, add this method in your class and call it to take the bytes from the database after we save it to database.

public string GetImageAsByte64String(int empno)
{

string conn = ConfigurationManager.ConnectionStrings["SE255_AFloresConnctionString2"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
string sql = "SELECT Avatar FROM Users WHERE User_ID = @ID";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", empno);
connection.Open();
object img = cmd.ExecuteScalar();
try
{
    byte[] imgByte = (byte[])img;
    string base64String = Convert.ToBase64String(imgByte , 0, imgByte.Length);
    return  ("data:image/png;base64," + base64String);

}
catch
{
    return null;
}
finally
{
    connection.Close();
}
}

Later call this method as below to assign to your ImageUrl property of the imageButton.

//display
imgProfile.ImageUrl = GetImageAsByte64String(id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM