Uploading images to a Sql Server database is extremely easy using ASP.NET and C#. This article will show you how to upload Images (or any Binary Data) to a SQL Server database using ASP.NET and C#. The next part in this series, Retrieving Images from a Database, will show you how extract images from a database.
Building the Database Table
We start out by building our database table. Our image table is going to have a few columns describing the image data, plus the image itself. Here is the sql required to build our table in SQL Server or MSDE.
CREATE TABLE [dbo].[image] (
[img_pk] [int] IDENTITY (1, 1) NOT NULL ,
[img_name] [varchar] (50) NULL ,
[img_data] [image] NULL ,
[img_contenttype] [varchar] (50) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
ALTER TABLE [dbo].[image] WITH NOCHECK ADD
CONSTRAINT [PK_image] PRIMARY KEY NONCLUSTERED
) ON [PRIMARY] GO
I'm a great fan of having a single column primary key, and making that key
an Identity column, in our example, that column is
img_pk. The next column
img_name, which is used to store a friendly name of our image, for example "Mom
and Apple Pie".
img_data is actually our image data column, and is where
we will be storing our binary image data.
img_contenttype will be used to record
the content-type of the image, for example "
image/gif" or "
we will know what content-type we need to output back to the client, in our
case the browser.