This tutorial will show you how to both save an image, and also retrieve the image from a SQL database. C# version.

There are many tutorials out there that show you how to store images in a database, but not many show you how to retrieve images and display them inline. It is pretty tricky to do, unfortunately, but it can be done. This tutorial will show you how to use the FileUpload control to save an image to the database and then also display it inline, in the same page, with all the other controls.

Our first step is to create the database. We will have one table with three columns- id, title and image. The image column will be of type image, also.
Once we have our database set up, we can start work on the ASPX page. We will add a textbox for the title, a FileUpload Control for the image, and a button to initiate the upload. Finally, we will include an Image placeholder, which will display the image when it has been uploaded. Our ASPX page will look something like this:

Nothing too special right now, just a regular ASPX page with a few controls. Next, we are going to want to add the logic to the button click event – notice that we have already specified the method in the OnClick attribute of the button. In the code-behind, the butSubmit_Click will look something like this:

In this method, we get the file from the FileUpload control and also the text entered by the user, then we transfer this data over to the database. We also set the ImageUrl of the Image placeholder to point at a HttpHandler we are about to create. Right-click your project and choose to Add New Item > Generic Handler. In this file, we will add the following:

In this handler, we are receiving the id of the database record in a querystring, then locating it in the database to retrieve the image bytes. We then use a MemoryStream object to display the image. The entire code for this handler is as follows:

Download Source Files