Asp.Net Code to Store and Retrieve Image from SQL Database

by top54u.com 06 Feb, 2008

To use SQL database for storing images you must have at least 1 database table having fields to store binary stream of image and content type of image.
You can create the table using following script:

create table [tbl_image] (
 [img_id] [int] identity (1, 1) not null,
 [img_title] [varchar] (100) collate sql_latin1_general_cp1_ci_as null,
 [img_stream] [image] null,
 [img_type] [varchar] (50) collate sql_latin1_general_cp1_ci_as null,
)

You have to set data type image for storing the image in database.

Further for storing the image VB.Net code can be used.
First of all you need a web form and all the fields that need to be inserted along with image. Following is a code snippet for creating a web form:

<div>
            <div>
                Image Title:<asp:TextBox ID="txtImgTitle" runat="server"></asp:TextBox>
            </div>
            <div>
                Browse Image:<asp:FileUpload ID="fileImgUpload" runat="server" />
            </div>
            <div>
                <asp:Button ID="btnUpload" runat="server" Text="Save" /></div>
        </div>
        <div>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="5"
                GridLines="None" ShowHeader="False">
                <Columns>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:Image ID="imgSaved" runat="server" ImageUrl='<%# imageURL(DataBinder.Eval(Container.DataItem, "img_id")) %>'
                                AlternateText='<%#DataBinder.Eval(Container.DataItem,"img_title") %>' />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
        </div>

Download the source code to learn how to store and retrieve image from the SQL server database. You will also learn about image streaming into bytes then insert it into SQL Table.

In the next function you will learn how to display the image retrieved from the database.

You can download the source code from the following link:

displayImages.zip (4.18 kb)

displayImages.rar (3.92 kb)

Spotlight.....

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

10/11/2008 3:19:29 AM




related videos.....
recent posts.....
top54u ezines.....