Display.ashx不显示带有字符&的图像名称

时间:2020-10-11 20:55:28

标签: c# html asp.net webforms

我遇到一种情况,Display.ashx成功显示了其中仅包含字母(例如咖啡或绿茶)的Sql服务器中的图像,但是当图像名称另存为(咖啡和泡沫)时,它不会显示。请查看代码下面,我在Display类的Img上设置了一个断点,当图像名称为Coffee时,将传递完整的字符串,但是当图像名称为Coffee&Froth时,它将剪切泡沫并仅吸收Coffee,这意味着它仅吸收字符前的字符串&。有人可以告诉我一种解决方法,以使整个字符串都包含字符。谢谢

 public class Display : IHttpHandler
    {
        public Stream Displays(string Img)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString.ToString()))
            {
                string sql = string.Format("select top 1 img from Images where Name  = '{0}'", Img);

                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.CommandType = CommandType.Text;
                cmd.Connection.Open();

                object imagevalue = cmd.ExecuteScalar();

                if (imagevalue != null && imagevalue != DBNull.Value)
                {
                    return new MemoryStream((byte[])imagevalue);
                }

                using (FileStream fs = File.OpenRead(HttpContext.Current.Server.MapPath(@"~/Content/noimage.png")))
                {
                    MemoryStream memStream = new MemoryStream();
                    memStream.SetLength(fs.Length);
                    fs.Read(memStream.GetBuffer(), 0, (int)fs.Length);
                    return memStream;
                }
            }
        }
    #endregion

这就是我所谓的图片

 protected void Refresh_SelectedIndexChanged(object sender, EventArgs e)
        {
            // string id = CoffeeMenu.SelectedValue;
            Image1.ImageUrl = "~/Display.ashx?id=" + "Coffee & Froth";
            divSuccess.Visible = false;
          divError.Visible = false;
        }

HTML

  <asp:DropDownList ID="CoffeeMenu" runat="server" CssClass="selectpicker" OnSelectedIndexChanged="Refresh_SelectedIndexChanged"/>

2 个答案:

答案 0 :(得分:0)

编码数据部分:

Image1.ImageUrl = "~/Display.ashx?id=" + Server.UrlEncode("Coffee & Froth");

您遇到的问题是&用来分隔url中的值,因此显示的额外参数看起来像:

?name=blah&resize=1920x1080&convert=png&rotate=90

因此,浏览器可能会以“ Coffee +&+ Froth”的形式请求“ Coffee&Froth”,并且您的ashx会将其解释为具有以下参数:

{
  "id": "Coffee ",
  " Froth": null
}

或者,从文件名中删除非数字或字母的任何内容;这些东西存储在磁盘上后,看起来好像您可以控制它们的命名

答案 1 :(得分:0)

(移动评论以回答问题)

尝试Coffee &amp; FrothCoffee%20%26%20Froth

&amp;在HTML中用于表示&

%20space的十六进制,而%26&的十六进制。十六进制通常用于对URL中的特殊字符进行编码。

全ASCII表: https://en.wikipedia.org/wiki/ASCII#Printable_characters