File Upload and Save Submitted Files to SQL Server 2005, Sample ASP.NET Web Site Application
Saving files in SQL Server is a method that we programmers may apply even it is uncommon. Keeping images like photos, or web desing components like graphics, backgrounds, etc will cost an overhead if the read image file is not cached and has to be fetched and read from the database each time it is requested. So if you decide to keep your web application's images or documents, in short binary data in SQL Server, make sure that you have valid reasons for doing so.
In this document, I'll try to explain the codes of a sample web site application which web users can upload files of certain types and save image files into Microsoft SQL Server 2005 database by using the GUI designed for this purpose. Users may also select uploading the files to a web folder instead of saving the binary files into a database. In an other page of this web application, a list of uploaded and saved in SQL database files will be listed in a web page using a GridView ASP.NET object. In this list page by clicking a hyperlink over the listed file item, a new page will display the image or serve the requested file after reading it from the SQL 2005 database.
You can use MS SQL Server 2008 as the file storage database also just like SQL Server 2005 database.
The same logic described in this ASP.NET tutorial can be implemented in MS Visual Studio 2005, MS VS2008 or MS VS2010 to save image to sql database instances like SQL2005 or SQL Server 2008.
The sql database in which the binary files will be kept has to contain the following table
In order to save file to SQL Server, we will begin by creating sql table Files to store the uploaded file in SQLServer.
One important point about this Files table is it that it uses the [file] column of type varbinary(max) to keep the submitted or uploaded binary files, including images, documents, executables, etc. It is noteworthy that since SQL Server will not support "image" data type as well as the text and ntext data types with the next release SQL Server 2005, you should use the varbinary(max) data type column to manage files up to 2 GB in sizes without a problem in future versions of SQL Server (SQL Server 2008, SQL Server 2008 R2).
FileUpload.aspx to Save File to SQL Server
Let's start examining the sample application which upload file to SQL Server from ASP.NET page FileUpload.aspx.
This page has one important web control, FileUpload control which we will use save file to SQL Server
You can add a button to submit the web form after the file is selected in order to upload file to sql.
When the ASP.NET button web control is clicked the page posts backs and you can read and save the submitted binary file data with the submitted form.
Here is some important parts of the btnUpload_Click event code.
The above if statement controls whether any file is submitted or not with the form to upload file SQL Server.
If a file is selected for upload in the FileUpload control and it is submitted FileUpload1.HasFile property will be True, otherwise HasFile property will equal to False.
If we have any file submitted to save file to SQL Server, we can continue else we can exit event sub procedure.
If you want to check and validate the uploaded file extension, you can use the following lines of codes.
First, in order to get the uploaded files extension, below line of code will guide us.
If we set the file extension of the uploaded file's extension to a variable, we can compare it in the future with valid file extensions.
Here is a function that can be used to compare if the file submitted by the web user is among the list of valid extensions.
Developers can use the same .NET code to compare the uploaded file's extension against a banned list of file extentions.
If you examine the web.config file for the AllowedFileExtensions AppSettings key value pair, you can easily understand that AllowedFileExtensions key is used to store the list of valid file extension.
Look at the below section copied down here from the web.config configuration file of the sample web site application.
If we split the AllowedFileExtensions key value, we can get an array of the confirmed extensions.
Below is a similar way of keeping valid extensions hardcoded as an array in the application instead of using the web configuration file.
If the file extension tests are successfull then we have two choice, one is saving the uploaded file in a file folder that can be reached from the web server, and also that has the write permission.
Or the second one is saving the uploaded file into the Microsoft SQL Server 2005 database.
Let's select the first one, save the file on a web folder.
Saving the file to the web folder that is parameterized using the web.config file UploadFolder AppSettings key-value pair is so easy.
Let's continue now with the saving to database selection.
First create a SqlConnection object getting the connection string from the configuration file connection strings section.
And the PhotosConnectionString is declared in the web.config file as shown below;
Then a SqlDataAdapter object is created from the Files database table using the following select sql statement.
The below VB.NET codes saves the uploaded file to be handled as a IO.Stream object.
And the following codes creates a new row of the Files datatable in the dataset and sets its columns with the filename and the stream object as the binary file.
ListFiles.aspx
This page is used as a displayed list of files uploaded successfully into the sql server database.
Here is the ASP.NET codes in the design page of the Visual Studio 2005 / Visual Studio 2008.
The GridView will list saved images / files after users save image to sql database.
When the HyperLinkField column of the GridView object is clicked the id field value which is unique in the Files database table is passed as a querystring parameter to the file.aspx page.
File.aspx to Display Image After Save File in SQL Database
File.aspx ASP.NET page reads requested image from SQL Server database tables with its id value.
After reading image file, File.aspx web page displays the requested image file which is as uploaded file in SQLServer 2005 (or any other SQL Server version like SQL2008, etc.)
Page.Request.Item("id") enables us to read the querystring parameters for the id parameter value of the uploaded file to SQL Server database.
Then the following lines of codes is used to read image file from sql database.
Now it is time to response the request with the file fetched from SQL Server database table named Files with its id IDENTITY field.
Content type "Image/JPEG" is used for image files. You can better keep the content type or the MIME type of the saved filed as a property of itself. Because if the uploaded file is a .doc file you have to use the content type as "text/html", etc.
I hope ASP.NET developers get the main tips about the solution which can be used to save image to SQL database
You can download the sample web site application source codes from the Files section of the site following File Upload and Save to SQL2005 Database Sample Code for an ASP.NET Web Site link.
The uploaded zip file is somehow corrupted so I had placed the download files for the sample ASP.NET file upload sources files at Download FilesDBSample.zip file for File Upload and Save Submitted Files to SQL Server 2005, Sample ASP.NET Web Site Application