一个aspx页面上服务图像存储在数据库中数据库中、图像、页面、aspx

2023-09-04 02:53:50 作者:埋葬关于你的记忆

我拉回存储在一列在SQL服务器数据库的图像。

I'm pulling back an image that is stored in a column in a SQL server database.

我要为这件事一个aspx页面上。

I need to serve this up on an aspx page.

我将如何做呢?

推荐答案

我想创建一个图像元素,其中src属性指向一个ashx的处理程序,在查询字符串的图片ID。在此处理程序,你可以有以下code:

I would create an image element where the src attribute points to an ashx handler with the image id in the query string. In this handler, you could have the following code:

        string ImageId = Request.QueryString["img"];
        string sqlText = "SELECT img_data, img_contenttype FROM Images WHERE img_pk = " + ImageId;

        using (var connection = new SqlConnection("your connection string"))
        {
            using (var command = new SqlCommand(sqlText, connection))
            {
                connection.Open();
                using (SqlDataReader dr = command.ExecuteReader())
                {
                    if (dr.Read())
                    {
                        Response.Clear();
                        Response.ContentType = dr["img_contenttype"].ToString();
                        Response.BinaryWrite((byte[]) dr["img_data"]);
                        Response.End();
                    }
                }
            }
        }