In
this article I will explain how to upload and save MP3 Audio files in
SQL Server Database and then retrieving and displaying in ASP.Net
GridView with download and paly option
Database
For this article I have created a simple table with the following structure
HTML Markup
The
HTML Markup contains a FileUpload and Button to upload and save the MP3
files to database and an ASP.Net GridView control to display the
uploaded files and also allows the user to play and download the MP3
Audio file.
<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" RowStyle-BackColor="#A1DCF2" Font-Names = "Arial" Font-Size = "10pt"
HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White">
<Columns>
<asp:BoundField DataField="Name" HeaderText="FileName" />
<asp:TemplateField>
<ItemTemplate>
<object type="application/x-shockwave-flash" data='dewplayer-vol.swf?mp3=File.ashx?Id=<%# Eval("Id") %>'
width="240" height="20" id="dewplayer">
<param name="wmode" value="transparent" />
<param name="movie" value='dewplayer-vol.swf?mp3=File.ashx?Id=<%# Eval("Id") %>'/>
</object>
</ItemTemplate>
</asp:TemplateField>
<asp:HyperLinkField DataNavigateUrlFields="Id" Text = "Download" DataNavigateUrlFormatString = "~/File.ashx?Id={0}" HeaderText="Download" />
</Columns>
</asp:GridView>
Uploading the MP3 Audio files and saving in SQL Server Database
The
below event handler gets executed when the Upload Button is clicked, it
simply saves the file as Binary data in the SQL Server Database
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
Displaying the uploaded MP3 Audio files in ASP.Net GridView
Below is the code which populates the ASP.Net GridView from data from the table which contains the uploaded MP3 files.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
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 from tblFiles";
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 IsPostBack Then
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 from tblFiles"
cmd.Connection = con
con.Open()
GridView1.DataSource = cmd.ExecuteReader()
GridView1.DataBind()
con.Close()
End Using
End Using
End Sub
Playing and Download the MP3 Audio files from ASP.Net GridView
I
have made use of a Generic Handler which will fetch the uploaded MP3
audio file based on Id when user wants to play in the Music or download
it using the Download link.
C#
<%@ WebHandler Language="C#" Class="FileCS" %>
using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
public class FileCS : 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="FileVB" %>
Imports System
Imports System.Web
Imports System.Data.SqlClient
Imports System.Configuration
Public Class FileVB : 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
No comments:
Post a Comment