如何在ASP.NET中保存和检索数据库中的图像

时间:2018-05-06 17:29:36

标签: asp.net sql-server image image-conversion

我想在页面加载时在图像控件中显示图像。我使用以下代码。我的问题是图像作为二进制数据保存在数据库中,但我无法在图像控件中检索图像

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
        {
        }
    }
}

有人可以帮帮我吗?

提前致谢...

1 个答案:

答案 0 :(得分:0)

我的文件上传代码

<%@ 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