In this post we will take a look at how to store data in a MS-SQL Server database using ASP.NET. We will start by creating the database table in which we will store the actual file data, and then create a new Web Form with a file upload control and an upload button which will save the uploaded file to the database. After that we need to create a generic HTTP Handler which will be responsible for flushing out the file to the client. The reason to why we will use a HTTP Handler for this is that we don’t need all the functionality that the System.Web.UI.Page provides, so having both performance and simplicity in mind a HTTP Handler is a better choice.
1. Start by creating a table named File in your database, add the following fields to it:

2. Create a new Web Form, give it the name UploadFile.aspx and add the following code:
C#:
<%@ Page Language="C#" AutoEventWireup="false" CodeFile="UploadFile.aspx.cs" Inherits="UploadFile" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Upload file</title>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload runat="server" ID="ctrFile" /> <asp:Button ID="btnUploadFile" runat="server" Text="Upload" />
<asp:HyperLink runat="server" ID="ctrResult" Target="_blank" />
</form>
</body>
</html>
VB.NET:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="FileUpload.aspx.vb" Inherits="FileUpload" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Upload file</title>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload runat="server" ID="ctrFile" /> <asp:Button ID="btnUploadFile" runat="server" Text="Upload" />
<asp:HyperLink runat="server" ID="ctrResult" Target="_blank" />
</form>
</body>
</html>
UploadFile.aspx.cs:
C#:
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
/// <summary>
/// Handles uploading- and storing a file in a database.
/// </summary>
public partial class UploadFile : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
btnUploadFile.Click += new EventHandler(btnUploadFile_Click);
}
void btnUploadFile_Click(object sender, EventArgs e)
{
// exit if file-upload has no file
if (!ctrFile.HasFile) return;
// generate new fileId
Guid fileId = Guid.NewGuid();
// create insert query
using (SqlCommand command = new SqlCommand())
{
command.Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
command.CommandText = @"insert into [File](FileId, FileName, FileType, FileSize, FileContent)
values(@FileId, @FileName, @FileType, @FileSize, @FileContent)";
command.Parameters.Add("@FileId", SqlDbType.UniqueIdentifier).Value = fileId;
command.Parameters.Add("@FileName", SqlDbType.NVarChar, 100).Value = Path.GetFileName(ctrFile.PostedFile.FileName);
command.Parameters.Add("@FileType", SqlDbType.NVarChar, 100).Value = ctrFile.PostedFile.ContentType;
command.Parameters.Add("@FileSize", SqlDbType.Int).Value = ctrFile.PostedFile.ContentLength;
// filecontent, convert from stream to byte array
byte[] fileContent = new byte[ctrFile.PostedFile.ContentLength];
ctrFile.PostedFile.InputStream.Read(fileContent, 0, ctrFile.PostedFile.ContentLength);
command.Parameters.Add("@FileContent", SqlDbType.VarBinary, -1).Value = fileContent;
command.Connection.Open();
command.ExecuteNonQuery();
}
// show result
ctrResult.NavigateUrl = "FileStream.ashx?FileId=" + fileId.ToString();
ctrResult.Text = "Click here to view the uploaded file";
}
}
VB.NET:
Imports System
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
"' <summary>
"' Handles uploading- and storing a file in a database.
"' </summary>
Partial Class UploadFile
Inherits System.Web.UI.Page
Protected Sub btnUploadFile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUploadFile.Click
' exit if file-upload has no file
If Not ctrFile.HasFile Then Exit Sub
' generate new fileId
Dim fileId As Guid = Guid.NewGuid()
' create insert query
Dim command As New SqlCommand()
Try
command.Connection = New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
command.CommandText = "insert into [File](FileId, FileName, FileType, FileSize, FileContent)" _
& "values(@FileId, @FileName, @FileType, @FileSize, @FileContent)"
command.Parameters.Add("@FileId", SqlDbType.UniqueIdentifier).Value = fileId
command.Parameters.Add("@FileName", SqlDbType.NVarChar, 100).Value = Path.GetFileName(ctrFile.PostedFile.FileName)
command.Parameters.Add("@FileType", SqlDbType.NVarChar, 100).Value = ctrFile.PostedFile.ContentType
command.Parameters.Add("@FileSize", SqlDbType.Int).Value = ctrFile.PostedFile.ContentLength
' filecontent, convert from stream to byte array
Dim fileContent(ctrFile.PostedFile.ContentLength) As Byte
ctrFile.PostedFile.InputStream.Read(fileContent, 0, ctrFile.PostedFile.ContentLength)
command.Parameters.Add("@FileContent", SqlDbType.VarBinary, -1).Value = fileContent
command.Connection.Open()
command.ExecuteNonQuery()
Finally
command.Dispose()
End Try
' show result
ctrResult.NavigateUrl = "FileStream.ashx?FileId=" + fileId.ToString()
ctrResult.Text = "Click here to view the uploaded file"
End Sub
End Class
3. Create a new Generic Handler (available under Add New Item > Generic Handler), give it the name FileStream.ashx and add the following code:
C#:
<%@ WebHandler Language="C#" Class="FileStream" %>
using System;
using System.Web;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
/// <summary>
/// Reponsible for flushing out the file from the database to the user.
/// </summary>
public class FileStream : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
// get the file id
Guid fileId = new Guid(context.Request.QueryString["FileId"]);
using (SqlCommand command = new SqlCommand())
{
// get the file from database
command.Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
command.CommandText = "select * from [File] where FileId = @FileId";
command.Parameters.Add("@FileId", SqlDbType.UniqueIdentifier).Value = fileId;
command.Connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
// flush out the binary data to the user
context.Response.Clear();
context.Response.ContentType = (string) reader["FileType"];
context.Response.AddHeader("Content-Disposition", String.Format("inline;filename={0};", reader["FileName"].ToString()));
context.Response.AddHeader("Content-Length", reader["FileSize"].ToString());
context.Response.BinaryWrite((byte[]) reader["FileContent"]);
context.Response.End();
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
VB.NET:
<%@ WebHandler Language="VB" Class="FileStream" %>
Imports System
Imports System.Web
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
"' <summary>
"' Reponsible for flushing out the file from the database to the user.
"' </summary>
Public Class FileStream : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
' get the file id
Dim fileId As New Guid(context.Request.QueryString("FileId"))
Dim command As New SqlCommand()
Try
' get the file from database
command.Connection = New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
command.CommandText = "select * from [File] where FileId = @FileId"
command.Parameters.Add("@FileId", SqlDbType.UniqueIdentifier).Value = fileId
command.Connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader()
If reader.Read() Then
' flush out the binary data to the user
context.Response.Clear()
context.Response.ContentType = reader("FileType").ToString()
context.Response.AddHeader("Content-Disposition", String.Format("inline;filename={0};", reader("FileName").ToString()))
context.Response.AddHeader("Content-Length", reader("FileSize").ToString())
context.Response.BinaryWrite(DirectCast(reader("FileContent"), Byte()))
context.Response.End()
End If
Finally
command.Dispose()
End Try
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
4. Run your code, upload a file using UploadFile.aspx, and then click on the hyperlink “Click here to view the uploaded file” to view the uploaded file.

April 21st, 2008 at 9:24 pm
useful stuff with compact explanation and nice example:D
May 8th, 2008 at 8:14 pm
Thanks alot.. Very useful and direct
June 11th, 2008 at 6:05 pm
do you have this example in VB ?
June 12th, 2008 at 7:52 pm
Here you go, I’ve updated the post with VB.NET code aswell.
June 12th, 2008 at 8:30 pm
Thanks very much.
June 19th, 2008 at 9:24 pm
Excellent‼! This is what I was looking for.
August 7th, 2008 at 3:00 pm
i really appreciate your post. Actually i face some problem like
here i search no. of file and his content and i store this file’s content to database ( SQL 2005 ).
so please help me to solve this query.
Thanks With Warm Regards,
Nevil Gandhi
September 29th, 2008 at 9:18 pm
Great code example, it shows the basics and allows to create something more.
November 15th, 2008 at 6:49 pm
Hello, I build in the code as shown onto this page into my asp.net application. The strange thing is that when a photo (*.jpeg) has been uploaded ore an picture placed for example within a word-document, the Internet Browser cannot handle this item reading it backwards from the SQL-server.
The Field type in my SQL for saving the data = image
I think something is already going wrong during streaming and saving a jpeg-file.
Do you know this problem - What should i do?
Futhermore your solution is fantastic!!
Best regards
Johan
November 30th, 2008 at 5:48 pm
This is really great stuff. One of the few examples which work right away. Thank you very very much.
Regards,
Robin
December 17th, 2008 at 11:28 am
Thank you, indeed one of the few examples that have clean code and work right out of the cut-n-paste.
Thank you.
February 24th, 2009 at 9:03 pm
hey, thnx u..ur code is really helpful..
March 25th, 2009 at 10:33 pm
work…. thanks…..
April 6th, 2009 at 3:29 pm
thows up error at the connection
command.Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
April 6th, 2009 at 3:34 pm
harda: You need to add the database connectionstring to the connectionStrings section in the web.config.
May 12th, 2009 at 10:32 am
Thank You.
How make search in uploads doc and xls documents?
May 23rd, 2009 at 6:31 pm
thanks a lot,explain it step wise thats why it very easy
August 10th, 2009 at 10:27 am
Thanks for your explanation regarding this topic. it was good one
October 7th, 2009 at 10:49 pm
Thank you very much . This is what I’m looking for. I copied and pasted the code to my .ashx file and it works
January 20th, 2010 at 9:01 am
very use full code but if there r n number of file that have been uploaded and if we want to down load the only one file from database den what would be the c# code…
Thank u very much….
January 26th, 2010 at 4:39 pm
Why is it, on every code sample someone puts up, does someone come in and say “Oh, can you post a [VB|C#] version of this?” (If you can’t decipher this sentence, please find another job that doesn’t involve programming).
C’mon people, are you developers or copy-paste programmers? It’s a simple .NET example. You need to be able to read C# and type VB or vice-versa. There’s even converters out on the net to do the job for you.
The code differences between the C# & VB blocks above are 90% the same, most of it is syntax and type conversion differences. This is simple stuff! Can you not figure this out?
From now on, if I put out a piece of code on the net, I’ll be putting it in whatever language I am most comfortable with, and a disclaimer. “If you can’t figure out how to convert this to your language, then you cannot use this code”.
Have a nice day!
February 24th, 2010 at 4:15 am
What do you name the database?
February 28th, 2010 at 10:57 am
Nick: The code reads the name of the database from a connectionString element named “ConnectionString” located below the connectionStrings section in the .config file.
March 16th, 2010 at 12:48 am
Hello, Thanks for the help.
I had another question when the picture opens it only shows that picture and nothing else how can I add something that it just maximizes the picture so I can add a comment field, rating…etc?
March 23rd, 2010 at 8:07 am
Nick: If you want to do this, you need to have an aspx page with an image tag pointing to FileStream.ashx. In this aspx you can also add comments, rating etc.
July 1st, 2010 at 11:02 pm
I am using the FileStream.ashx file exactly as written and it works perfectly when I’m getting a file from SQL and showing it to the user. The problem is I now need to pull a file from SQL and make it an attachment in an email. I have the code that will create an email and add as many attachments as I need but it only want’s to work with real files on a server. I tried to just call FileStream.ashx but that just blew up. is there a way to full the file out of SQL and either save it on the server (may not be possilbe due to security) or just attach it directly to the Email (prefered).
Thanks in advance.
July 2nd, 2010 at 12:32 pm
You should be able to use more or less the same code, but instead of flushing it out on the web, you store it temporarily on the disk instead. Then you use the path to the file when attaching the files to the e-mail.
July 6th, 2010 at 5:28 pm
I thought of that but I can’t figure out how to send it to a file either. I also concidered assigning the result to a variable and then attache the variable. Same problem. Short of bringing up a window that allows open or save I can’t seem to ifentify it as an object that I can do anything with. What I would like to do is be able to say something along these lines:
MailAttachment attach = new MailAttachment(”FileStream.ashx?ID=xxx”);
Where the ID is the unique identifier in the SQL db. It works just fine if I’m using a link but MailAttachement isn’t looking for an HREF it’s looking for a location.
I’ll keep looking. Thanks.
PS There could be more than one file that will need to be attached.
July 6th, 2010 at 10:11 pm
Got it figured out and it seems to work perfectly. Figured I’d let you know so you didn’t knock yourself out trying to figure it out.
Thanks