开发者

Serving an Image stored in a database on an aspx page

I'm p开发者_运维问答ulling back an image that is stored in a column in a SQL server database.

I need to serve this up on an aspx page.

How would I do that?


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


You first get Page.Response, then call BinaryWrite or use Stream directly

Plus i recommned storing images on filesystem, not DB.


In the html page, you need to render a <img> tag with a src attribute pointing to another page (or ashx handler). In that other page/handler the only output you generate is the binary data of the image (and possibly some http headers).
Use parameters to specify the image.


Retrieve it from the database, convert from binary to image using The System.Drawing.Image class, and then save the image in a temporary folder. Give the path of temp folder in <img> tag in html/ascx/aspx, etc.

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">
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜