.Net, ADO.NET, ASP.NET, C#, Database, DB Connection Example, Example Connection, Programming, SQL, SQL Server 2000, SQL Server 2005, SQL Server 2008, SQL Server 2012, Web Development, WebForms

Basic Example of using the ASP.NET FileUpload to Save into a Database

Here is a super-simple bare-bones example of an ASP.NET Web form page in C# that uses the .NET FileUpload component to allow a user to upload a file into a SQL Server database table. I’ve put this together as a template to show just how easy it is to do and how few lines of actual code the process actually requires. Surprisingly the examples I found online and at the Microsoft support site were incomplete or had errors, so this is my attempt at making things clear.

Uploading the File from the Client Computer

In order to have the file upload magic happen, we need to make use of the System.IO library to parse the uploaded file’s path, as well as the standard System.Data and System.Data.SqlClient libraries to insert the file into the database.

In the first part of the code, we get the details of the uploaded file by referencing the FileUpload control’s PostedFile properties. This lets us get useful information such as theb, the content length, and the content type.

Converting the File into a Database-Friendly Format

Once we have the file information, we’ll need to put the file into a format that we can actually save to our database. The simplest way to do so is to convert the file into a byte array that we can then save into our database table as an Image type value. This allows for quick and easy file storage and retrieval.

To actually get the file into a byte array, we first need to convert it to a Stream object. Once the file is in a Stream object we can grab the total length of the file to set the byte array to from the Stream object’s length property. Finally, we can populate the byte array using the Stream.Read method. It’s a bit tricky, but makes perfect sense once you get the hang of it.

Saving the File into the Database

The final step is to do the actual insertion of the file into our database table. As you can see, I’ve hard-coded the database connection information and table Insert statement to an imaginary database server and table. If you are going to test this code, then you’ll need to update the database connection string as well as the table Insert statement to suit your particular setup.

Don’t Forget to Increase your Maximum Allowed File Size

Remember that maximum allowed file sizes for uploads are set in your Web application’s Web.config file, and that the default size is a paltry 4 MB.

To increase this you will need to open the Web.config file and update the HTTPRuntime tag’s MaxRequestLength value in the System.Web section of your config file. Note that these settings and their location in your Web.config vary depending on the version of ASP.NET that your application is running under, and what version of IIS is hosting your application. You may also want to increase the ExecutionTimeOut value if you expect your users will be uploading larger files that take longer than the default 90 seconds to upload.

The Example Code:

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

 protected void btnUploadToDb_Click(object sender, EventArgs e)
 if (uplFileUploader.HasFile){
 string strTestFilePath = uplFileUploader.PostedFile.FileName; // This gets the full file path on the client's machine ie: c:\test\myfile.txt
 string strTestFileName = Path.GetFileName(strTestFilePath); // use the System.IO Path.GetFileName method to get specifics about the file without needing to parse the path as a string
 Int32 intFileSize = uplFileUploader.PostedFile.ContentLength;
 string strContentType = uplFileUploader.PostedFile.ContentType;

 // Convert the uploaded file to a byte stream to save to your database. This could be a database table field of type Image in SQL Server
 Stream strmStream = uplFileUploader.PostedFile.InputStream;
 Int32 intFileLength = (Int32)strmStream.Length;
 byte[] bytUpfile = new byte[intFileLength + 1];
 strmStream.Read(bytUpfile, 0, intFileLength);

 saveFileToDb(strTestFileName, intFileSize, strContentType, bytUpfile); // or use uplFileUploader.SaveAs(Server.MapPath(".") + "filename") to save to the server's filesystem.
 lblUploadResult.Text = "Upload Success. File was uploaded and saved to the database.";
 }catch(Exception err){
 lblUploadResult.Text= "The file was not updloaded because the following error happened: " + err.ToString();
 lblUploadResult.Text = "No File Uploaded because none was selected.";
 protected void saveFileToDb(string strTestFileName, Int32 intFileSize, string strContentType, byte[] bytUpfile) {
 string testDbConnection = "Data Source=myServer;Initial Catalog=myDatabase;Persist Security Info=True;User ID=myUserAccount;Password=myPassword";
 // string testDbConnection = "Data Source=VMCorpDev1;Initial Catalog=PropertyManagement;Persist Security Info=True;User ID=ais_devel;Password=devel";
 // string strInsertStmt = string.Format("INSERT INTO [PropMgtFileAttachments] ([AttachedFileName],[CreatedBy],[CreatedDt],[AttachedFile]) VALUES ('{0}','John Doe',GETDATE(),@TestFile)", strTestFileName);
 string strInsertStmt = string.Format("INSERT INTO [TestFileTable] ([AttachedFileName],[CreatedBy],[CreatedDt],[AttachedFile]) VALUES ('{0}','3733',GETDATE(),@TestFile)", strTestFileName);

 using (SqlConnection conn = new SqlConnection(testDbConnection)) {
 SqlCommand cmdCommand = conn.CreateCommand();
 cmdCommand.CommandText = strInsertStmt;
 cmdCommand.CommandType = CommandType.Text;
 cmdCommand.Parameters.AddWithValue("@TestFile", bytUpfile);


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <form id="form1" runat="server">
 <asp:FileUpload ID="uplFileUploader" runat="server" />
 <asp:Button ID="btnUploadToDb" runat="server" Text="Upload to Database" OnClick="btnUploadToDb_Click" />
 <asp:Label ID="lblUploadResult" runat="server" Text=""></asp:Label>



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s