从目录获取映像并使用c#.net将映像存储在SQL Server数据库中

时间:2017-06-19 10:42:29

标签: c# sql-server

我希望使用c#.net从本地目录中获取图像以存储在SQL Server数据库中,以及从数据库中检索图像以使用WPF显示在列表框上。

1 个答案:

答案 0 :(得分:0)

这是C#代码

protected void btnUpload_Click(object sender, EventArgs e)
    {
        Stream fs = FileUpload1.PostedFile.InputStream;
        BinaryReader br = new BinaryReader(fs);
        Byte[] bytes = br.ReadBytes((Int32)fs.Length);
        string strQuery = "insert into tblFiles(Data) values (@Data)";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
        SqlConnection con = new SqlConnection(consString);
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        con.Open();
        cmd.ExecuteNonQuery();
    }
protected void btnView_Click(object sender, EventArgs e)
    {
        string strQuery = "select * from tblFiles";
        SqlCommand cmd = new SqlCommand(strQuery);
        SqlConnection con = new SqlConnection(consString);
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        con.Open();
        SqlDataAdapter objAdapter = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        objAdapter.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

试试这个

HTML

<div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="btnUpload" runat="server" Text="Upload" 
            onclick="btnUpload_Click" />
        <asp:Button ID="btnView" runat="server" Text="View" onclick="btnView_Click" />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField HeaderText="Image">
                    <ItemTemplate>
                        <asp:Image ID="Image4" ImageUrl= '<%#"data:image/jpg;base64," + Convert.ToBase64String((byte[])(Eval("Data")))%>' Height="250px" Width = "250px" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>