Pages

Subscribe:

Ads 468x60px

Friday, March 16, 2012

how to save and fetch images from sql server in asp.net using c#

in previous article we explained that how to save files in sql server database using asp.net now we will learn that how to fetch images from sql server database in asp.net using c#

below function in page load event will just fetch the image data from sql server.
protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["ImageID"] != null)
    {
        string strQuery = "select Name, ContentType, Data from tblFiles where id=@id";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@id", SqlDbType.Int).Value
        = Convert.ToInt32 (Request.QueryString["ImageID"]);
        DataTable dt = GetData(cmd);
        if (dt != null)
        {
            Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
            Response.Buffer = true;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = dt.Rows[0]["ContentType"].ToString();
            Response.AddHeader("content-disposition", "attachment;filename="
            + dt.Rows[0]["Name"].ToString());
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }
    }
}
and we wll pass the parameters to our image tag as mention below in asp.net



No comments:

Post a Comment