Introduction

This tutorial will show you not only how to save an image to a SQL database, but how to retrieve the image and display it on your web page. C#. Storing images to a database is relatively easy, but retrieving them to display in pages is probably a bit more difficult than it should be. In this tutorial, you will learn not only how to save images to a SQL database, but also how to retrieve them and display it on the page with the other controls, inline.

In this example, we are going to use a SQL database with one table, and three columns – id, title and image. Once we have our database set up, we can start on our ASPX page.

We are going to use a simple form consisting of a textbox, a file upload control, and a button. We will also include a label for status messages, and an image control as a placeholder for our uploaded image. Which will look something like this:

This is all we will be adding on our ASPX page, the rest of the web application will be the code-behind and a generic handler. We will start on the code-behind, first. Notice above that we have already set our onclick handler to a method. In the code-behind, we will code the button click event to open a connection with the SQL Database.

This is the only method in the code-behind. What it does in essence, is capture the bytes of the uploaded file, and then saves this to the database along with the text input into the title field. Notice at the end of the try statement we have set the ImageUrl of our image placeholder. This points to the http handler we are going to create. Right-click your project in Solution Explorer and choose Add New Item.. > Generic Handler. Name it DisplayImg.ashx and then add the following code:

In this handler, we are receiving the id of the database record in a query string, then locating it in the database to retrieve the image bytes. We then use a MemoryStream object to display the image.

Conclusion

In this tutorial we learned how to save and retrieve an image from an SQL database. This can be very useful for large scale sites that need to store images on a server rather than locally.

Download Source Files