Serving an image stored in a database on an aspx page

I am returning an image that is stored in a SQL server database column.

I need to execute this on an aspx page.

How should I do it?

+3
source share
4 answers

I would create an image element in which the src attribute points to an ashx handler with the image id in the query string. In this handler, you can 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();
                    }
                }
            }
        }
+3
source

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

Plus, I recommended storing images in the file system, not in DB.

+2
source

html <img> src, ( ashx). / , , - (, , http).
.

+2

, , System.Drawing.Image, . temp <img> html/ascx/aspx ..

#:

 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">
+1

Source: https://habr.com/ru/post/1761088/


All Articles