Pages

Free Hosting

Monday, November 7, 2011

How to save vedeo files in SQL Database


In order to save a vedeo file into your database you need to convert your vedeo data into binary form by uploading the file into your web browser by file upload control. also you need to create a database of following columns
ID(int),Vedeo(binary(max)), Video_Name(nvarchar(50), Video_Size(bigint)
Then come into your web page where you inserted a file uploader. Add a button control of name=ButtonUpload and in the ButtonUpload_Click event handler write down the following code.
byte
[] buffer;

//this is the array of bytes which will hold the data (file)

SqlConnection connection=new SqlConnection("Server=.;Database=MyDatabase;User ID=sa;Password=password");

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

{



SqlCommand cmd = new SqlCommand

("INSERT INTO Vedeos (Vedeo, 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();

}

finally

{ connection.Close(); }

}

}

else

{

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

}

}