上方廣告

2010年1月1日 星期五

讀取資料庫欄位型態為Image的資料

using (SqlConnection conn = new SqlConnection(connStrdg1))
{
    conn.Open();
    string strSQL = "";
    using (SqlCommand command = new SqlCommand())
    {
        command.Connection = conn;
        command.CommandType = CommandType.Text;

        strSQL = "SELECT image FROM XXXX WHERE id=@imgid";
        command.CommandText = strSQL;
        command.Parameters.Add("imgid", SqlDbType.UniqueIdentifier).Value = new Guid(Request.QueryString["imgid"].ToString());
        
        //下面這句為主要關鍵所在
        Response.ContentType = "image/jpeg";
        byte[] image = (byte[])command.ExecuteScalar();

        if (image == null)
        {
            Response.Redirect("/NoImage.gif");
        }
        else
        {
            Response.BinaryWrite(image);
        }
    }
}