65.9K
CodeProject is changing. Read more.
Home

storing and retriving images from database using ASP.NET

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.67/5 (3 votes)

Dec 1, 2011

CPOL
viewsIcon

16597

Code for storing and retrieving images from database using ASP.NET.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        int id = Convert.ToInt32(Request.QueryString["imagId"]);

        if (id > 0)
        {

            //connect to the db
            SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=F:\Examples\ImageExamples\Images1\ImageStoringAndRetrivingUsingImageConrtol\App_Data\Database1.mdf;Integrated Security=True;User Instance=True");

            //sql command to select the image with id of 1
            SqlCommand cmd = new SqlCommand("SELECT * FROM Images WHERE ImgId=@ImgId", conn);
            cmd.CommandType = CommandType.Text;

            //select the image with ImgId of 1
            cmd.Parameters.AddWithValue("@ImgId", id);

            using (conn)
            {
                //open the connection
                conn.Open();
                //send the sql query to select the image and store the results in a sqldatareader
                SqlDataReader rdr = cmd.ExecuteReader();
                //read the data
                if (rdr.Read())
                {
                    //store the image binary data in a byte array
                    Byte[] imgData = (byte[])rdr["ImgBin"];
                    //setup the image type to be displayed
                    Response.ContentType = (rdr["ImgType"].ToString());
                    //output the image to the page
                    Response.OutputStream.Write(imgData, 0, imgData.Length);
                }
            }

        }

    }
    }