In this article I will explain how to save and retrieve BLOB (Binary) Images from MySql Database in ASP.Net, C# and VB.Net.
The Image files will be saved as BYTE array in the BLOB field of MySql database.
Using MySQL with ASP.Net
Database
I have made use of the following table Files with the schema as follows.
Note: You can download the database table SQL by clicking the download link below.
HTML Markup
The HTML Markup consists of an ASP.Net FileUpload control, a Button and a GridView. The inserted images will be displayed in the GridView control.
The GridView has a OnRowDataBound event handler assigned which will be used for displaying the Image inserted in MySql database.
<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>
Namespaces
You will need to import the following namespaces
C#
using System.IO;
using System.Data;
using System.Configuration;
using MySql.Data.MySqlClient;
VB.Net
Imports System.IO
Imports System.Data
Imports System.Configuration
Imports MySql.Data.MySqlClient
Uploading Image files and then saving in MySql database table
The below event handler gets executed when the Upload Button is clicked, it first converts the uploaded image file to BYTE array using BinaryReader class and then saves the Image file as Binary data (BLOB) in the MySql Database.
The name of the file, the content type (MIME type) and the actual file as array of bytes are inserted into the MySql database table.
Note: The Content type (MIME type) is very important while downloading the files as it notifies the browser about type of the File.
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);
}
VB.Net
Protected Sub UploadFile(sender As Object, e As EventArgs)
Dim filename As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
Dim contentType As String = FileUpload1.PostedFile.ContentType
Using fs As Stream = FileUpload1.PostedFile.InputStream
Using br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(DirectCast(fs.Length, Long))
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New MySqlConnection(constr)
Dim query As String = "INSERT INTO Files(FileName, ContentType, Content) VALUES (@FileName, @ContentType, @Content)"
Using cmd As 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()
End Using
End Using
End Using
End Using
Response.Redirect(Request.Url.AbsoluteUri)
End Sub
The following screenshot displays the records inserted in the MySql database table.
Displaying the inserted Image files from MySql database table in ASP.Net GridView
Inside the Page Load event, the GridView is populated with the records from the MySql database table.
C#
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();
}
}
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Me.BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand()
cmd.CommandText = "SELECT FileId, FileName, ContentType, Content FROM Files"
cmd.Connection = con
Using sda As New MySqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
gvImages.DataSource = dt
gvImages.DataBind()
End Using
End Using
End Using
End Sub
Displaying the Binary (BLOB) Images in Image control in GridView
The following OnRowDataBound event handler does the job of displaying the Binary (BLOB) Image data in Image control.
First the BLOB data is fetched from the GridView DataItem property and is converted back to the BYTE array, which is then converted to a BASE64 string and assigned to the ImageUrl property of the Image control.
C#
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;
}
}
VB.Net
Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim bytes As Byte() = TryCast(TryCast(e.Row.DataItem, DataRowView)("Content"), Byte())
Dim base64String As String = Convert.ToBase64String(bytes, 0, bytes.Length)
TryCast(e.Row.FindControl("Image1"), Image).ImageUrl = Convert.ToString("data:image/png;base64,") & base64String
End If
End Sub
Screenshot
Downloads