Monday, 16 February 2015

Save and Retrieve BLOB Images from MySql Database in ASP.Net, C#

Save and Retrieve BLOB Images from MySql Database in ASP.Net, C#:


ASPX:

<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button Text="Upload" runat="server" OnClick="UploadFile" />
<hr />
<asp:GridView ID="gvImages" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound">
    <Columns>
        <asp:BoundField HeaderText="File Id" DataField="FileId" />
        <asp:BoundField HeaderText="File Name" DataField="FileName" />
        <asp:TemplateField HeaderText = "Image">
            <ItemTemplate>
                <asp:Image ID="Image1" runat="server" Height="80" Width="80" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

C#:

protected void UploadFile(object sender, EventArgs e)
{
    string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
    string contentType = FileUpload1.PostedFile.ContentType;
    using (Stream fs = FileUpload1.PostedFile.InputStream)
    {
        using (BinaryReader br = new BinaryReader(fs))
        {
            byte[] bytes = br.ReadBytes((Int32)fs.Length);
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (MySqlConnection con = new MySqlConnection(constr))
            {
                string query = "INSERT INTO Files(FileName, ContentType, Content) VALUES (@FileName, @ContentType, @Content)";
                using (MySqlCommand cmd = new MySqlCommand(query))
                {
                    cmd.Connection = con;
                    cmd.Parameters.AddWithValue("@FileName", filename);
                    cmd.Parameters.AddWithValue("@ContentType", contentType);
                    cmd.Parameters.AddWithValue("@Content", bytes);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }
    }
    Response.Redirect(Request.Url.AbsoluteUri);
}

Displaying the inserted Image files from MySql database table in ASP.Net GridView:
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        this.BindGrid();
    }
}

private void BindGrid()
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (MySqlConnection con = new MySqlConnection(constr))
    {
        using (MySqlCommand cmd = new MySqlCommand())
        {
            cmd.CommandText = "SELECT FileId, FileName, ContentType, Content FROM Files";
            cmd.Connection = con;
            using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd))
            {
                DataTable dt = new DataTable();
                sda.Fill(dt);
                gvImages.DataSource = dt;
                gvImages.DataBind();
            }
        }
    }
}

Displaying the Binary (BLOB) Images in Image control in GridView:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        byte[] bytes = (byte[])(e.Row.DataItem as DataRowView)["Content"];
        string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
        (e.Row.FindControl("Image1") as Image).ImageUrl = "data:image/png;base64," + base64String;
    }
}