Click here to Skip to main content
12,689,349 members (25,528 online)
Click here to Skip to main content
Add your own
alternative version


121 bookmarked

Video Uploader Control for SQL Server

, 28 Nov 2007 CPOL
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.


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.


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).


  • Create a table in a SQL Server database that will store the file data, file name, and file size.
  • IDInt
  • 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, 
            //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)
                    string connectionString = 
                    connection = new SqlConnection(connectionString);
                    SqlCommand cmd = new SqlCommand
                    ("INSERT INTO Videos (Video, Video_Name, Video_Size)" + 
                     " VALUES (@video, @videoName, @videoSize)", connection);
                        SqlDbType.VarBinary, buffer.Length).Value = buffer;
                        SqlDbType.NVarChar).Value = FileUpload1.FileName;
                        SqlDbType.BigInt).Value = file.ContentLength;
                    using (connection)
                        int i = cmd.ExecuteNonQuery();
                        Label1.Text = "uploaded, " + i.ToString() + " rows affected";
                catch (Exception ex)
                    Label1.Text = ex.Message.ToString();

            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 = 

        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 = 
            SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default);
            if (reader.HasRows)
                while (reader.Read())
                    context.Response.ContentType = reader["Video_Name"].ToString();
    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 = 
    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();
    return table;
protected void ButtonShowVideo_Click(object sender, EventArgs e)
    Repeater1.DataSource = GetSpecificVideo(2);
    //the video id (2 is example)


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">
            <object id="player" 
                       height="170" width="300">
                <param name="url" 
                  value='<%# "VideoHandler.ashx?id=" + Eval("ID") %>'/>
                <param name="showcontrols" value="true" />
                <param name="autostart" value="true" />

Hope you found this useful.


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


About the Author

Islam ElDemery
Web Developer Business Development Gate
Egypt Egypt

You may also be interested in...


Comments and Discussions

QuestionNot Working Pin
Member 854266616-Feb-12 2:08
memberMember 854266616-Feb-12 2:08 
Questiongreat.... Pin
Rajesh Biswas7-Dec-11 20:28
memberRajesh Biswas7-Dec-11 20:28 
AnswerRe: great.... Pin
saracena8-Mar-12 1:17
membersaracena8-Mar-12 1:17 
GeneralRe: great.... Pin
Rajesh Biswas3-Jul-12 20:21
memberRajesh Biswas3-Jul-12 20:21 
AnswerRe: great.... Pin
AVINCODE13-Mar-13 23:12
memberAVINCODE13-Mar-13 23:12 
Questionnot working on mozila firefox Pin
Member 822941316-Oct-11 21:25
memberMember 822941316-Oct-11 21:25 
archana jain14-Oct-11 0:56
memberarchana jain14-Oct-11 0:56 
Member 822941316-Oct-11 21:30
memberMember 822941316-Oct-11 21:30 
QuestionVery Worst Pin
AmericanGopi7-Aug-11 22:58
memberAmericanGopi7-Aug-11 22:58 
GeneralThis article not working . . . Pin
prabhakarparihar5-Mar-11 1:57
memberprabhakarparihar5-Mar-11 1:57 
GeneralMy vote of 3 Pin
Atul Dhiman from Chandigarh, India7-Dec-10 21:05
memberAtul Dhiman from Chandigarh, India7-Dec-10 21:05 
GeneralRe: My vote of 3 Pin
John Simmons / outlaw programmer8-Dec-10 0:25
memberJohn Simmons / outlaw programmer8-Dec-10 0:25 
GeneralRe: My vote of 3 Pin
Atul Dhiman from Chandigarh, India8-Dec-10 19:59
memberAtul Dhiman from Chandigarh, India8-Dec-10 19:59 
GeneralMy vote of 5 Pin
Kanasz Robert12-Nov-10 1:34
memberKanasz Robert12-Nov-10 1:34 
Generalvideo uploadin is not wrkin Pin
re.shivangi25-Oct-10 2:29
memberre.shivangi25-Oct-10 2:29 
Generalits not working Pin
satish deverkonda29-Jul-10 0:03
membersatish deverkonda29-Jul-10 0:03 
Generalmp3 files Pin
Member 47211685-May-10 6:49
memberMember 47211685-May-10 6:49 
GeneralSupports only .wmv cideo formats Pin
Sandeep N. Pamnani6-Apr-10 0:00
memberSandeep N. Pamnani6-Apr-10 0:00 
GeneralRe: Supports only .wmv cideo formats Pin
Sandeep N. Pamnani6-Apr-10 0:07
memberSandeep N. Pamnani6-Apr-10 0:07 
GeneralUnable to show videos when hit the button and videos unable to play Pin
Neo Yong Sheng7-Feb-10 21:32
memberNeo Yong Sheng7-Feb-10 21:32 
Generalvery nice Pin
OmarGamil26-Jan-10 5:02
memberOmarGamil26-Jan-10 5:02 
GeneralVideo works in IE and not in firefox Pin
Member 209778131-May-09 2:09
memberMember 209778131-May-09 2:09 
GeneralMy videos r nt playing! Pin
fun2code4-Feb-09 11:10
memberfun2code4-Feb-09 11:10 
GeneralRe: My videos r nt playing! Pin
meena218-Apr-12 1:27
membermeena218-Apr-12 1:27 
GeneralNeed help quickly Pin
ravikumarnegala15-Oct-08 1:12
memberravikumarnegala15-Oct-08 1:12 
GeneralRe: Need help quickly Pin
Islam ElDemery16-Oct-08 22:07
memberIslam ElDemery16-Oct-08 22:07 
GeneralThis is not working on Firefox Pin
G.S.Reddy31-Jul-08 6:50
memberG.S.Reddy31-Jul-08 6:50 
GeneralGood Job bro Pin
shahid shaikh22-Jul-08 4:34
membershahid shaikh22-Jul-08 4:34 
GeneralGood job but a little help would be nice please. Pin
Kazi Nayeem11-May-08 19:57
memberKazi Nayeem11-May-08 19:57 
GeneralRe: Good job but a little help would be nice please. Pin
Islam ElDemery12-May-08 0:52
memberIslam ElDemery12-May-08 0:52 
GeneralSome problems, I really need some help Pin
Ladamantis220921-Jan-08 11:15
memberLadamantis220921-Jan-08 11:15 
QuestionLarge files Pin
Cubex9-Jan-08 15:41
memberCubex9-Jan-08 15:41 
General[Message Deleted] Pin
Islam ElDemery10-Jan-08 0:48
memberIslam ElDemery10-Jan-08 0:48 
GeneralRe: Large files Pin
Islam ElDemery10-Jan-08 2:57
memberIslam ElDemery10-Jan-08 2:57 
GeneralNice, but it's better to read the uploaded file in chunks Pin
hspc9-Dec-07 8:34
memberhspc9-Dec-07 8:34 
GeneralRe: Nice, but it's better to read the uploaded file in chunks Pin
Islam ElDemery12-Dec-07 4:54
memberIslam ElDemery12-Dec-07 4:54 
GeneralWhy varbinary Pin
jamief5-Dec-07 5:55
memberjamief5-Dec-07 5:55 
GeneralRe: Why varbinary Pin
Islam ElDemery12-Dec-07 4:46
memberIslam ElDemery12-Dec-07 4:46 
QuestionASP.Net project topic request! Pin
Pech4-Dec-07 22:36
memberPech4-Dec-07 22:36 
GeneralRe: ASP.Net project topic request! Pin
Islam ElDemery12-Dec-07 4:38
memberIslam ElDemery12-Dec-07 4:38 
Generaladd me on gmail Pin
Farrru30-Nov-07 19:21
memberFarrru30-Nov-07 19:21 
GeneralOk Islam Brother Pin
Farrru29-Nov-07 3:12
memberFarrru29-Nov-07 3:12 
GeneralRe: Ok Islam Brother Pin
Islam ElDemery29-Nov-07 3:15
memberIslam ElDemery29-Nov-07 3:15 
Generali m trying Pin
Farrru29-Nov-07 3:07
memberFarrru29-Nov-07 3:07 
GeneralRe: i m trying [modified] Pin
Islam ElDemery29-Nov-07 3:08
memberIslam ElDemery29-Nov-07 3:08 
GeneralSQL 2000 Pin
Farrru29-Nov-07 3:03
memberFarrru29-Nov-07 3:03 
GeneralRe: SQL 2000 [modified] Pin
Islam ElDemery29-Nov-07 3:05
memberIslam ElDemery29-Nov-07 3:05 
QuestionHow can i change the 8000 to MAX Pin
Farrru29-Nov-07 3:02
memberFarrru29-Nov-07 3:02 
GeneralI have taken Video field varbinary(8000) not (MAX) Pin
Farrru29-Nov-07 2:55
memberFarrru29-Nov-07 2:55 
GeneralRe: I have taken Video field varbinary(8000) not (MAX) Pin
Islam ElDemery29-Nov-07 2:57
memberIslam ElDemery29-Nov-07 2:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    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 | Terms of Use | Mobile
Web02 | 2.8.170113.4 | Last Updated 28 Nov 2007
Article Copyright 2007 by Islam ElDemery
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid