Storing Images and BLOB files in SQL Server Part 3
Introduction
In the first two articles of this series, BLOBs were defined along with scenarios of when to store them inside SQL Server rather than on the file system. Several different types of VARBINARIES were introduced, including the VARBINARY(MAX) data type which will be the focus of this article. The first code example loaded an image into the database then retrieved it using an ASPX page with a Binary Write. In this article, a web-based application will be created for inserting images into SQL Server. In addition, the examples from the first two articles will be expanded and improved.
SQL Test Database
To begin, create a test database and table for storing images using the following TSQL script:
USE master;
GO
CREATE DATABASE BLOBTest3;
GO
USE BLOBTest3;
GO
CREATE TABLE BLOBFromWeb
(
BLOBData varbinary(max)
);
GOThe script created a single database, containing a single table, containing a single column. The test column “BLOBData” uses the MAX keyword allowing it to store binaries of any size.
Next create a stored procedure that will be used by a web page for uploading images:
CREATE PROCEDURE WebUp
(
@FileData varbinary(max)
)
AS
INSERT INTO BLOBFromWeb
(BLOBData)
VALUES
(@FileData);The stored procedure will pass one variable, the image “@FileData”, into SQL Server.
The rest of the examples in this series will use stored procedures rather than SQL statements. There are many benefits to using stored procedures, such as increased security, preventing SQL Injection attacks, portability, and performance.
Inserting into SQL from the Web
This example uses Microsoft Visual Studio 2008 to create a web form, which will ask the end user to browse to a file, and then upload the file into SQL Server. The application will also work in Visual Studio 2005. To begin, create a new web site and an aspx page using code behind. Drag a FileUpload and a Button control onto the form as shown below.

Switch to the source view of the page and change the default