Hi alhamd,
Use below article i have created the example.
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" Visible="false" />
<asp:BoundField HeaderText="Name" DataField="FileName" />
<asp:TemplateField HeaderText="">
<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
Screenshot