In this article I will explain with an example, how to upload and insert MP3 Audio files in SQL Server Database and then play the MP3 Audio files using HTML5 Audio Player in ASP.Net using C# and VB.Net.
The MP3 Audio files are displayed in GridView and there’s also a Download button to download the MP3 Audio files.
Database
This article makes use of a table named tblFiles whose schema is defined as follows.
Note: You can download the database table SQL by clicking the download link below.
HTML Markup
The HTML Markup contains a FileUpload and Button to upload and save the MP3 Audio files to database and an ASP.Net GridView control to display the uploaded MP3 Audio files and also allows the user to play the MP3 Audio file.
Note: The File.ashx is a Generic Handler (explained later) which is used to fetch the uploaded MP3 Audio files from the SQL Server database and serve as source to the HTML5 Audio Player.
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
<hr />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="FileName" />
<asp:TemplateField>
<ItemTemplate>
<audio controls>
<source src='<%# Eval("Id", "File.ashx?Id={0}") %>' type = '<%# Eval("ContentType") %>' />
</audio>
</ItemTemplate>
</asp:TemplateField>
<asp:HyperLinkField DataNavigateUrlFields="Id" Text="Download" DataNavigateUrlFormatString="~/File.ashx?Id={0}"
HeaderText="Download" />
</Columns>
</asp:GridView>
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.IO
Imports System.Data.SqlClient
Imports System.Configuration
Uploading the MP3 Audio files and saving in SQL Server Database
When the Upload Button is clicked, the MP3 Audio files are uploaded to the Server. The uploaded MP3 Audio files are converted into a Byte Array which is then inserted into the SQL Server Database Table.
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
using (BinaryReader br = new BinaryReader(FileUpload1.PostedFile.InputStream))
{
byte[] bytes = br.ReadBytes((int)FileUpload1.PostedFile.InputStream.Length);
string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "INSERT INTO tblFiles(Name, ContentType, Data) VALUES (@Name, @ContentType, @Data)";
cmd.Parameters.AddWithValue("@Name", Path.GetFileName(FileUpload1.PostedFile.FileName));
cmd.Parameters.AddWithValue("@ContentType", "audio/mpeg3");
cmd.Parameters.AddWithValue("@Data", bytes);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
VB.Net
Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
Using br As New BinaryReader(FileUpload1.PostedFile.InputStream)
Dim bytes As Byte() = br.ReadBytes(CInt(FileUpload1.PostedFile.InputStream.Length))
Dim strConnString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(strConnString)
Using cmd As New SqlCommand()
cmd.CommandText = "INSERT INTO tblFiles(Name, ContentType, Data) VALUES (@Name, @ContentType, @Data)"
cmd.Parameters.AddWithValue("@Name", Path.GetFileName(FileUpload1.PostedFile.FileName))
cmd.Parameters.AddWithValue("@ContentType", "audio/mpeg3")
cmd.Parameters.AddWithValue("@Data", bytes)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Using
Response.Redirect(Request.Url.AbsoluteUri)
End Sub
Populating the GridView
Inside the Page Load event, the GridView is populated with uploaded MP3 Audio from Database Table.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = " SELECT Id, Name, ContentType FROM tblFiles WHERE ContentType = 'audio/mpeg3'";
cmd.Connection = con;
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim strConnString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(strConnString)
Using cmd As New SqlCommand()
cmd.CommandText = " SELECT Id, Name, ContentType FROM tblFiles WHERE ContentType = 'audio/mpeg3'"
cmd.Connection = con
con.Open()
GridView1.DataSource = cmd.ExecuteReader()
GridView1.DataBind()
con.Close()
End Using
End Using
End Sub
Play MP3 Audio files from Database using HTML5 Audio Player in ASP.Net
The following Generic Handler will be used to serve the Audios to the HTML5 Audio Player. The HTML5 Audio Player will call the Generic Handler and pass the ID of the MP3 Audio File to be played.
Based on the ID, the MP3 Audio File will be fetched from the database and will be returned through the Response in Byte Array format.
C#
<%@ WebHandler Language="C#" Class="File" %>
using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
public class File : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
int id = int.Parse(context.Request.QueryString["id"]);
byte[] bytes;
string contentType;
string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string name;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Name, Data, ContentType FROM tblFiles WHERE Id=@Id";
cmd.Parameters.AddWithValue("@Id", id);
cmd.Connection = con;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
bytes = (byte[])sdr["Data"];
contentType = sdr["ContentType"].ToString();
name = sdr["Name"].ToString();
con.Close();
}
}
context.Response.Clear();
context.Response.Buffer = true;
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name);
context.Response.ContentType = contentType;
context.Response.BinaryWrite(bytes);
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
VB.Net
<%@ WebHandler Language="VB" Class="File" %>
Imports System
Imports System.Web
Imports System.Data.SqlClient
Imports System.Configuration
Public Class File : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim id As Integer = Integer.Parse(context.Request.QueryString("id"))
Dim bytes As Byte()
Dim contentType As String
Dim strConnString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim name As String
Using con As New SqlConnection(strConnString)
Using cmd As New SqlCommand()
cmd.CommandText = "SELECT Name, Data, ContentType FROM tblFiles WHERE Id=@Id"
cmd.Parameters.AddWithValue("@Id", id)
cmd.Connection = con
con.Open()
Dim sdr As SqlDataReader = cmd.ExecuteReader()
sdr.Read()
bytes = DirectCast(sdr("Data"), Byte())
contentType = sdr("ContentType").ToString()
name = sdr("Name").ToString()
con.Close()
End Using
End Using
context.Response.Clear()
context.Response.Buffer = True
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name)
context.Response.ContentType = contentType
context.Response.BinaryWrite(bytes)
context.Response.[End]()
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Screenshot
Demo
Downloads