Upload Video File, Audio File and Image File in SQL Server DB

Create a table in a SQL Server.

Create table Videos
(
 ID Int identity,
Video varbinary(MAX),
Video_Name nvarchar(50),
Video_Size bigint
)

Img.jpg

Tools

Drag and Drop FileUpload Control, Button,Lable, Panel and inside the panel drag and drop Repeater Control.

Change the text property of BtnUpload control to Upload.

Code

1. Save Data in DataBase. Here  data may be Video file, Image file or audio file. On click event of upload button write down the following code.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

using System.Data;

 

public partial class _Default : System.Web.UI.Page 

{

    protected void Page_Load(object sender, EventArgs e)

    {

    }

    byte[] buffer;

    SqlConnection connection;

    protected void BtnUpload_Click(object sender, EventArgs e)

    {

        if (FileUpload1.HasFile && FileUpload1.PostedFile != null

            && FileUpload1.PostedFile.FileName != "")

        {

            HttpPostedFile file = FileUpload1.PostedFile;

            //retrieve the HttpPostedFile object

            buffer = new byte[file.ContentLength];

            int bytesReaded = file.InputStream.Read(buffer, 0,

            FileUpload1.PostedFile.ContentLength);         

            if (bytesReaded > 0)

            {

                try

                {

                    connection = new SqlConnection("Data Source=.;Initial Catalog=Sample;User Id=sa;Password=faculty");

                    SqlCommand cmd = new SqlCommand

                    ("INSERT INTO Videos (Video, Video_Name, Video_Size)" +

                     " VALUES (@video, @videoName, @videoSize)", connection);

                    cmd.Parameters.Add("@video",

                        SqlDbType.VarBinary, buffer.Length).Value = buffer;

                    cmd.Parameters.Add("@videoName",

                        SqlDbType.NVarChar).Value = FileUpload1.FileName;

                    cmd.Parameters.Add("@videoSize",

                        SqlDbType.BigInt).Value = file.ContentLength;

                    using (connection)

                    {

                        connection.Open();

                        // int i = cmd.ExecuteNonQuery();

                        cmd.ExecuteReader();

                        Label1.Text = "uploaded";

                    }

                }

                catch (Exception ex)

                {

                    Label1.Text = ex.Message.ToString();

                }

                finally

                {

                    connection.Close();

                }

            }

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

        }

        else

        {

            Label1.Text = "Choose a valid video file";

        }

    }

The above code will help you to save your data in database.Notice one thing, if your data is large in size then you need to increase  maxRequestLength in web.config under System.web node.

<system.web>
<httpRuntime maxRequestLength="2097151" />

2. Select Data and show it on your Page.

Here we are going to use Player Control to display data on your page. But our file exists in a database, so we need a handler to read the bytes in the database. you can call handler like handler.ashx?Id=1. Id=1 is a query string. So Next step is add Handler to your Project and name it as VideoHandler.ashx.

This handler is going to retrieve data from database.

Code
 

using System;

using System.Web;

using System.Data.SqlClient;

using System.Data.SqlTypes;

using System.Data;

public class VideoHandler : IHttpHandler

{

    // SqlConnection connection;

    public void ProcessRequest(HttpContext context)

    {

        SqlConnection connection = new SqlConnection("Data Source=.;Initial Catalog=Sample;User Id=sa;Password=faculty");

        SqlCommand cmd = new SqlCommand("SELECT Video, Video_Name" + " FROM Videos WHERE ID = @id", connection);

        cmd.Parameters.Add("@id", SqlDbType.Int).Value =context.Request.QueryString["id"];

        try

        {

            connection.Open();

            SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default);

            if (reader.HasRows)

            {

                while (reader.Read())

                {

                    context.Response.ContentType = reader["Video_Name"].ToString();

                    context.Response.BinaryWrite((byte[])reader["Video"]);

                }

            }

        }

        finally

        {

            connection.Close();

        }

    }

    public bool IsReusable

    {

        get

        {

            return false;

        }

    }

}

3. Show Video on Page.

You have to read the data from the SQL Server with a SQL adapter and bind the data source to the Repeater control. Well, here you can specify which videos to select in the datasource..

Add one textBox and Button right above the Panel. Change the text property of button to Show Video. This textbox we are going to use to enter Id of video.Finally on click event of ShowVideo button we are going to display video on page.

So here we will create one method, this will retrieve data from sqlserver
 

private DataTable GetSpecificVideo(object i)

//pass the id of the video

{

    connection = new SqlConnection("Data Source=.;Initial Catalog=Sample;User Id=sa;Password=faculty");

    SqlDataAdapter adapter = new SqlDataAdapter("SELECT Video, ID " +

                             "FROM Videos WHERE ID = @id", connection);

    adapter.SelectCommand.Parameters.Add("@id", SqlDbType.Int).Value = (int)i;

    DataTable table = new DataTable();

    adapter.Fill(table);

    return table;

 
On click event Bind this data to repeater Control...

protected void Button1_Click(object sender, EventArgs e)
 {
     int id = Convert.ToInt32(TextBox1.Text);
     Repeater1.DataSource = GetSpecificVideo(id);     
     Repeater1.DataBind();
 }

Now we will add Palyer control.  In source view of Repeater Control add an Itemtemplate
 

<asp:Panel ID="Panel1" runat="server" Height="126px" Width="881px">

        <asp:Repeater ID="Repeater1" runat="server">

    <ItemTemplate>

            <object id="player" 

                       classid="clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6" 

                       height="300" width="300">

                <param name="url" 

                  value='<%# "VideoHandler.ashx?id=" + Eval("ID") %>'/>

                <param name="showcontrols" value="true" />

                <param name="autostart" value="true" />

            </object>

        </ItemTemplate>

    </asp:Repeater>

        </asp:Panel>

 

Run your application . Now you can upload file as well as show your uploaded video file on page.