Upload and Play multiple Audio and Video files from Database using C# and VB.Net in ASP.Net

alhamd
 
on Aug 02, 2021 11:07 PM
Sample_242577.zip
663 Views

I want to upload multiple audio or video student lectures file in the database in the following table like that

tblFiles

FID    File_Name    ContenType      Data       Class    Section

1          Eng Lec        audio             BinaryData               One       A

2          Eng Lec        Vedio             BinaryData               One       A

For upload I wrote the following code

<body>    
     <form id="form1" runat="server">  
        <div class="container py-3">  
            <h2 class="text-center text-uppercase">How to upload video in database and play using asp.net</h2>  
            <div class="row">  
                <div class="form-group">  
                    <label>Choose Video:</label>  
                    <div class="input-group">  
                        <div class="custom-file">  
                            <asp:FileUpload ID="FileUpload1" CssClass="custom-file-input" runat="server" />  
                            <label class="custom-file-label"></label>  
                        </div>  
                        <div class="input-group-append">  
                            <asp:Button ID="btnUpload" CssClass="btn btn-outline-secondary" runat="server" Text="Upload" OnClick="btnUpload_Click" />  
                        </div>  
                    </div>  
                </div>  
            </div>  
            <asp:Label ID="lblMessage" runat="server"></asp:Label>  
            <asp:GridView ID="GridView1" ShowHeaderWhenEmpty="true" HeaderStyle-CssClass="bg-primary text-white" runat="server" AutoGenerateColumns="false" CssClass="table table-bordered">  
                <EmptyDataTemplate>  
                    <div class="text-center">No Data Found <strong>Upload New Video</strong></div>  
                </EmptyDataTemplate>  
                <Columns>  
                    <asp:BoundField HeaderText="ID" DataField="VID" />  
                    <asp:BoundField HeaderText="Name" DataField="Name" />  
                    <asp:TemplateField HeaderText="Audio/Videos">  
                        <ItemTemplate>  
                            <video width="130" height="130" controls>  
                                <source src='<%#Eval("Video_Path")%>' type="video/mp4">  
                            </video>  
                        </ItemTemplate>  
                    </asp:TemplateField>  
                </Columns>  
            </asp:GridView>  
        </div>  
    </form> 
</body>

Now pls guide how to insert multiple audio or video files in the database and play on click in the Gridview in Asp.Net and after that Download it. 

        protected void Page_Load(object sender, EventArgs e)  
        {  
            if (!IsPostBack)  
            {  
                BindGrid();  
            }  
        }  
  
        private void BindGrid()  
        {  
            string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
            using (SqlConnection con = new SqlConnection(CS))  
            {  
                SqlCommand cmd = new SqlCommand("spGetAllVideos", con);  
                cmd.CommandType = CommandType.StoredProcedure;  
                con.Open();  
                GridView1.DataSource = cmd.ExecuteReader();  
                GridView1.DataBind();  
            }  
        }  
  
        protected void btnUpload_Click(object sender, EventArgs e)  
        {  
            if (FileUpload1.PostedFile!=null)  
            {  
                try  
                {  
                    string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);  
                    FileUpload1.PostedFile.SaveAs(Server.MapPath("UploadVideos/" + FileName));  
  
                    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
                    using (SqlConnection con = new SqlConnection(CS))  
                    {  
                        SqlCommand cmd = new SqlCommand("spInsertVideo", con);  
                        cmd.CommandType = CommandType.StoredProcedure;  
                        con.Open();  
                        cmd.Parameters.AddWithValue("@Name",FileName);  
                        cmd.Parameters.AddWithValue("@Video_Path", "UploadVideos/" + FileName);  
                        cmd.ExecuteNonQuery();  
                        BindGrid();  
                        lblMessage.Text = "Your file uploaded successfully";  
                        lblMessage.ForeColor = System.Drawing.Color.Green;  
                    }  
                }  
                catch (Exception)  
                {  
                    lblMessage.Text = "Your file not uploaded";  
                    lblMessage.ForeColor = System.Drawing.Color.Red;  
                }  
            }  
        } 

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Aug 05, 2021 05:12 AM

Hi alhamd,

Use below article i have created the example.

Upload and Play MP3 Audio files from Database using HTML5 Audio Player in ASP.Net

Refer below code.

HTML

<div class="container py-3">
    <h2 class="text-center text-uppercase">How to upload video in database and play using asp.net</h2>
    <div class="row">
        <div class="form-group">
            <label>Choose Video:</label>
            <div class="input-group">
                <div class="custom-file">
                    <asp:FileUpload ID="FileUpload1" CssClass="custom-file-input" runat="server" AllowMultiple="true" />
                    <label class="custom-file-label"></label>
                </div>
                <div class="input-group-append">
                    <asp:Button ID="btnUpload" CssClass="btn btn-outline-secondary" runat="server" Text="Upload" OnClick="btnUpload_Click" />
                </div>
            </div>
        </div>
    </div>
    <asp:Label ID="lblMessage" runat="server"></asp:Label>
    <asp:GridView ID="GridView1" ShowHeaderWhenEmpty="true" HeaderStyle-CssClass="bg-primary text-white" runat="server" AutoGenerateColumns="false" CssClass="table table-bordered">
        <EmptyDataTemplate>
            <div class="text-center">No Data Found <strong>Upload New Video</strong></div>
        </EmptyDataTemplate>
        <Columns>
            <asp:BoundField HeaderText="ID" DataField="VID" />
            <asp:BoundField HeaderText="Name" DataField="Name" />
            <asp:TemplateField HeaderText="Audio/Videos">
                <ItemTemplate>
                    <video width="130" height="130" controls runat="server" visible='<%# Eval("ContentType").ToString().ToLower()=="video/mp4" ? true : false %>'>
                        <source src='<%# Eval("Id", "File.ashx?Id={0}") %>' type="video/mp4">
                    </video>
                    <audio controls runat="server" visible='<%# Eval("ContentType").ToString().ToLower()=="audio/mpeg3" ? true : false %>'>
                        <source src='<%# Eval("Id", "File.ashx?Id={0}") %>' type='audio/mpeg3' />
                    </audio>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:HyperLinkField DataNavigateUrlFields="Id" Text="Download" DataNavigateUrlFormatString="~/File.ashx?Id={0}"
                HeaderText="Download" />
        </Columns>
    </asp:GridView>
</div>

Namespaces

C#

using System.IO;
using System.Data.SqlClient;
using System.Configuration;

VB.Net

Imports System.IO
Imports System.Data.SqlClient
Imports System.Configuration

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        this.BindGrid();
    }
}

protected void btnUpload_Click(object sender, EventArgs e)
{
    foreach (HttpPostedFile postedFile in FileUpload1.PostedFiles)
    {
        string filename = Path.GetFileName(postedFile.FileName);
        string contentType = postedFile.ContentType;
        using (Stream fs = postedFile.InputStream)
        {
            using (BinaryReader br = new BinaryReader(fs))
            {
                byte[] bytes = br.ReadBytes((Int32)fs.Length);
                string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    string query = "insert into tblFiles values (@Name, @ContentType, @Data)";
                    using (SqlCommand cmd = new SqlCommand(query))
                    {
                        cmd.Connection = con;
                        cmd.Parameters.AddWithValue("@Name", filename);
                        cmd.Parameters.AddWithValue("@ContentType", contentType);
                        cmd.Parameters.AddWithValue("@Data", bytes);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                }
            }
        }
    }

    Response.Redirect(Request.Url.AbsoluteUri);
}

private void BindGrid()
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "SELECT * FROM tblFiles";
            cmd.Connection = con;
            con.Open();
            GridView1.DataSource = cmd.ExecuteReader();
            GridView1.DataBind();
            con.Close();
        }
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Me.BindGrid()
    End If
End Sub

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
    For Each postedFile As HttpPostedFile In FileUpload1.PostedFiles
        Dim filename As String = Path.GetFileName(postedFile.FileName)
        Dim contentType As String = postedFile.ContentType
        Using fs As Stream = postedFile.InputStream
            Using br As BinaryReader = New BinaryReader(fs)
                Dim bytes As Byte() = br.ReadBytes(CType(fs.Length, Int32))
                Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
                Using con As SqlConnection = New SqlConnection(constr)
                    Dim query As String = "insert into tblFiles values (@Name, @ContentType, @Data)"
                    Using cmd As SqlCommand = New SqlCommand(query)
                        cmd.Connection = con
                        cmd.Parameters.AddWithValue("@Name", filename)
                        cmd.Parameters.AddWithValue("@ContentType", contentType)
                        cmd.Parameters.AddWithValue("@Data", bytes)
                        con.Open()
                        cmd.ExecuteNonQuery()
                        con.Close()
                    End Using
                End Using
            End Using
        End Using
    Next

    Response.Redirect(Request.Url.AbsoluteUri)
End Sub

Private Sub BindGrid()
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand()
            cmd.CommandText = "SELECT * FROM tblFiles"
            cmd.Connection = con
            con.Open()
            GridView1.DataSource = cmd.ExecuteReader()
            GridView1.DataBind()
            con.Close()
        End Using
    End Using
End Sub

Handler

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