在aspx页面上提供存储在数据库中的图像

时间:2010-08-23 11:18:30

标签: .net asp.net sql-server

我正在撤回存储在SQL Server数据库中的列中的图像。

我需要在aspx页面上提供这个服务。

我该怎么做?

4 个答案:

答案 0 :(得分:3)

我会创建一个图像元素,其中src属性指向查询字符串中带有图像ID的ashx处理程序。在此处理程序中,您可以使用以下代码:

        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();
                    }
                }
            }
        }

答案 1 :(得分:2)

首先获得Page.Response,然后致电BinaryWrite或使用流directly

另外,我建议在文件系统上存储图像,而不是DB。

答案 2 :(得分:2)

在html页面中,您需要使用指向另一个页面(或ashx处理程序)的src属性呈现<img>标记。在其他页面/处理程序中,您生成的输出是图像的二进制数据(可能还有一些http标题)。
使用参数指定图像。

答案 3 :(得分:1)

从数据库中检索它,使用System.Drawing.Image类从二进制转换为图像,然后将图像保存在临时文件夹中。在html / ascx / aspx等的<img>标记中给出临时文件夹的路径。

C#:

 MemoryStream ms = new MemoryStream(binaryImage);
 Bitmap BMP = new Bitmap(ms);
 String path = Server.MapPath("..\\Temp");

 if (!Directory.Exists(path))
 {
     Directory.CreateDirectory(path);
 }

 FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, path);

 if (SecurityManager.IsGranted(writePermission))
 {
     System.Drawing.Image img = new System.Drawing.Bitmap(ms);
     img.Save(path + "\\xyz.jpg", ImageFormat.Jpeg);
 }

HTML / ASPX:

<img src="Temp/xyz.jpg">
相关问题