Click here to Skip to main content
Click here to Skip to main content
Go to top

Video Uploader Control for SQL Server

, 28 Nov 2007
Rate this:
Please Sign up or sign in to vote.
Upload and insert video, audio, or image to SQL Server, and show it in an ASPX page.

Introduction

This article will explain how to upload and insert files into SQL Server (specially audio, video, and image files) using C# and ADO.NET, and then how to show the video file in an ASP.NET page with a player control.

Background

Before we start, I don't know what is better, uploading files to a database or uploading files to a server system and storing only their paths in the database. Well, I think, if those files are small in size (like images), I'd prefer to store them in the database, but if they are large (I don't have a number), then I think this will take time with the stream while reading and writing binary data (I'd like to know about your experience).

Tools

  • Create a table in a SQL Server database that will store the file data, file name, and file size.
  • ID Int
    Video varbinary(MAX)
    Video_Name nvarchar(50)
    Video_Size bigint
  • In the control, add a FileUpload control, a Button, a Label.
  • Add the control to your page.

Using the code

The idea when uploading a file to a database is to convert it to bytes. Converting a file to bytes is easy by getting the HTTPPostedFile and read it with a stream to bytes, then inserting them in a varbinary column in SQL Server (in the case of video or audio files) or an image column (in the case of images).

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

public partial class UploadVideo : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    byte[] buffer;
    //this is the array of bytes which will hold the data (file)

    SqlConnection connection;
    protected void ButtonUpload_Click(object sender, EventArgs e)
    {
        //check the file

        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);
            //the HttpPostedFile has InputStream porperty (using System.IO;)
            //which can read the stream to the buffer object,
            //the first parameter is the array of bytes to store in,
            //the second parameter is the zero index (of specific byte)
            //where to start storing in the buffer,
            //the third parameter is the number of bytes 
            //you want to read (do u care about this?)

            if (bytesReaded > 0)
            {
                try
                {
                    string connectionString = 
                      ConfigurationManager.ConnectionStrings[
                      "uploadConnectionString"].ConnectionString;
                    connection = new SqlConnection(connectionString);
                    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();
                        Label1.Text = "uploaded, " + i.ToString() + " rows affected";
                    }
                }
                catch (Exception ex)
                {
                    Label1.Text = ex.Message.ToString();
                }
            }

        }
        else
        {
            Label1.Text = "Choose a valid video file";
        }
    }
}
//create a sqlcommand object passing the query and the sqlconnection object
//when declaring the parameters you have to be sure 
//you have set the type of video column to varbinary(MAX)

How to select the data and show it on your page

The problem here is that we have to set the src property of the player control, but our file exists in a database, so we need a handler to read the bytes in the database.. The handler idea is awesome! You can call it like: "Handler.ashx?ID=1", and in the handler code, read the video column where the ID column = QueryString["id"].

using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public class VideoHandler : IHttpHandler 
{
    
    public void ProcessRequest (HttpContext context) 
    {
        string connectionString = 
          ConfigurationManager.ConnectionStrings[
          "uploadConnectionString"].ConnectionString;

        SqlConnection connection = new SqlConnection(connectionString);
        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;
        }
    }
}

OK.. how do we show the video?! You can show the video in an ASP.NET Data control. Well, I did an example on the Repeater control. 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..

private DataTable GetSpecificVideo(object i)
//pass the id of the video
{
    string connectionString = 
      ConfigurationManager.ConnectionStrings[
      "uploadConnectionString"].ConnectionString;
    SqlDataAdapter adapter = new SqlDataAdapter("SELECT Video, ID " + 
                             "FROM Videos WHERE ID = @id", connectionString);
    adapter.SelectCommand.Parameters.Add("@id", SqlDbType.Int).Value = (int)i;
    DataTable table = new DataTable();
    adapter.Fill(table);
    return table;
}
protected void ButtonShowVideo_Click(object sender, EventArgs e)
{
    Repeater1.DataSource = GetSpecificVideo(2);
    //the video id (2 is example)

    Repeater1.DataBind();
}

Now, its time for the player control.. In the Repeater (source view), add an ItemTemplate, and set the URL value parameter of the player control to <'%# "VideoHandler.ashx?id=" + Eval("ID") %'>. The ID is the name of the ID column of the data source that the Repeater binds to.

<asp:Button ID="ButtonShowVideo" runat="server" 
   onclick="ButtonShowVideo_Click" Text="Show Video" />

    <asp:Repeater ID="Repeater1" runat="server">
        <ItemTemplate>
            <object id="player" 
                       classid="clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6" 
                       height="170" 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>

Hope you found this useful.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Islam ElDemery
Web Developer Business Development Gate
Egypt Egypt
Blog
Follow on   Twitter

Comments and Discussions

 
QuestionVideo is not loading plz help me Pinmemberrajeshmuthiah14-Jul-14 1:22 
QuestionNo good! Pinmemberemoutlou8-Oct-13 5:05 
QuestionVideo file can't be stored with this code PinmemberAvaniSoni15-Sep-13 1:19 
Questionshitttttttt PinmemberMember 1013175131-Aug-13 9:37 
Questionshitttttttt PinmemberMember 1013175131-Aug-13 9:36 
Questionnot show video Pinmemberjaimin8512-Aug-13 0:07 
Questionnot show the video Pinmemberpalawan19-Jun-13 2:14 
GeneralMy vote of 3 PinmemberMember 1003872818-Jun-13 2:07 
GeneralMy vote of 2 PinmemberFarzad F Wadia30-Mar-13 18:00 
QuestionIts Not Working Pinmembershalinibharani28-Nov-12 23:40 
QuestionIts Working but.., Pinmembersrikanth4u25-Oct-12 5:04 
QuestionError PinmemberMustafaIqbal29-Aug-12 5:22 
AnswerRe: Error PinmemberMember 979473617-Feb-13 5:44 
QuestionVideo uploader control - error in vs2005 PinmemberVCSSyed23-Jul-12 12:51 
AnswerRe: Video uploader control - error in vs2005 Pinmember_Amy23-Jul-12 23:52 
GeneralRe: Video uploader control - error in vs2005 PinmemberVCSSyed24-Jul-12 0:05 
GeneralRe: Video uploader control - error in vs2005 PinmemberVCSSyed24-Jul-12 0:10 
GeneralRe: Video uploader control - error in vs2005 PinmemberVCSSyed24-Jul-12 0:17 
QuestionVideo uploader control - not showing video PinmemberVCSSyed23-Jul-12 12:45 
QuestionVideo not playing Pinmembermeena218-Apr-12 0:24 
Questionhow to save the video file path into database PinmemberMember 872361711-Apr-12 20:47 
Questiondidn't work PinmemberSara_Mardini7-Apr-12 8:33 
Hi,
 
when i run the code an exeption happend and this messag appear !
 
Object reference not set to an instance of an object.
 
what should i do ?!
AnswerRe: didn't work Pinmember_Amy23-Jul-12 23:51 
Generalhow to play all videos Pinmemberharikrishnan.vg90221-Feb-12 0:14 
QuestionNot Working PinmemberMember 854266616-Feb-12 1:08 
Questiongreat.... PinmemberRajesh Biswas7-Dec-11 19:28 
AnswerRe: great.... Pinmembersaracena8-Mar-12 0:17 
GeneralRe: great.... PinmemberRajesh Biswas3-Jul-12 19:21 
AnswerRe: great.... PinmemberAVINCODE13-Mar-13 22:12 
Questionnot working on mozila firefox PinmemberMember 822941316-Oct-11 20:25 
QuestionNOT WORKING Pinmemberarchana jain13-Oct-11 23:56 
AnswerRe: NOT WORKING PinmemberMember 822941316-Oct-11 20:30 
QuestionVery Worst PinmemberAmericanGopi7-Aug-11 21:58 
GeneralThis article not working . . . Pinmemberprabhakarparihar5-Mar-11 0:57 
GeneralMy vote of 3 PinmemberAtul Dhiman from Chandigarh, India7-Dec-10 20:05 
GeneralRe: My vote of 3 PinmemberJohn Simmons / outlaw programmer7-Dec-10 23:25 
GeneralRe: My vote of 3 PinmemberAtul Dhiman from Chandigarh, India8-Dec-10 18:59 
GeneralMy vote of 5 PinmemberKanasz Robert12-Nov-10 0:34 
Generalvideo uploadin is not wrkin Pinmemberre.shivangi25-Oct-10 1:29 
Generalits not working Pinmembersatish deverkonda28-Jul-10 23:03 
Generalmp3 files PinmemberMember 47211685-May-10 5:49 
GeneralSupports only .wmv cideo formats PinmemberSandeep N. Pamnani5-Apr-10 23:00 
GeneralRe: Supports only .wmv cideo formats PinmemberSandeep N. Pamnani5-Apr-10 23:07 
GeneralUnable to show videos when hit the button and videos unable to play PinmemberNeo Yong Sheng7-Feb-10 20:32 
Generalvery nice PinmemberOmarGamil26-Jan-10 4:02 
GeneralVideo works in IE and not in firefox PinmemberMember 209778131-May-09 1:09 
GeneralMy videos r nt playing! Pinmemberfun2code4-Feb-09 10:10 
GeneralRe: My videos r nt playing! Pinmembermeena218-Apr-12 0:27 
GeneralNeed help quickly Pinmemberravikumarnegala15-Oct-08 0:12 
GeneralRe: Need help quickly PinmemberIslam ElDemery16-Oct-08 21:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140921.1 | Last Updated 28 Nov 2007
Article Copyright 2007 by Islam ElDemery
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid