Monday, October 19, 2009

Uploading files to sql server database in asp.net

Guys if u requires storing files in sql server database, then here is the code.
create a datatable as shown in fig.

Drag a FileUpload control and Button control on Aspx markup .
And on button click event write the following code.

protected void Button2_Click(object sender, EventArgs e)
{
string cnstng = "Data Source=test;Initial Catalog=testdb;Integrated Security=True";
SqlConnection con = new SqlConnection(cnstng);
string sqlText = "insert into dbo.Attachments (FileName, FileContent,FileSizeInMB,ContentType) values(@FileName ,@FileContent,,FileSizeInMB,ContentType)";
if (FileUpload1.HasFile)
{
HttpPostedFile p_filePosted = FileUpload1.PostedFile;
int length = p_filePosted.ContentLength;
string filePath = p_filePosted.FileName;
string fileName = Path.GetFileName(filePath);
string contentType = p_filePosted.ContentType;
string sizeMB = (length / 1048576).ToString();
int sizeMBIndex = sizeMB.IndexOf(".");
if (sizeMBIndex > 0)
{
sizeMBIndex = sizeMBIndex + 4;
sizeMB = sizeMB.Substring(0, sizeMBIndex);
}

byte[] bytes = new byte[length];
p_filePosted.InputStream.Read(bytes, 0, length);
try
{
con.Open();
SqlCommand cmd = new SqlCommand(sqlText, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@FileName", fileName);
cmd.Parameters.AddWithValue("@FileContent", bytes);
cmd.Parameters.AddWithValue("@FileSizeInMB", sizeMB);
cmd.Parameters.AddWithValue("@ContentType", contentType);
cmd.ExecuteNonQuery();
}
Catch
{
}
}
}

2 comments:

  1. Good Work.
    Keep uploading more technical stuff.
    I will be visiting your blog regularly.

    i m also a .net developer.
    i do write technical blog. i don't update much.
    http://urshiva.wordpress.com/

    ReplyDelete
  2. thnks a lot.. shivu. sure i ll upload more n more stuffs
    even i ll visit ur blog.
    i have read ur blogs in kannada.. good at expressing urself.good luk..

    ReplyDelete