Display Image using ashx Handler

痞子三分冷 提交于 2019-11-26 17:51:32

问题


I have the following image in my aspx page

<td>
 <asp:Image ID="LargeImage" runat="server" Height="100" Width="100" />" 

</td>

In my aspx.cs, assigned a imageurl to this image

protected void uploadimage_Click(object sender, System.EventArgs e)
        {

            ImageUtils.uploadImage(Titletxt.Text, FileUpload.FileContent);
            LargeImage.ImageUrl = "~/AvatarImageFetch.ashx?memberid=" + memberid.ToString();
}

For some reason, the image doesn't show up. Here's my ashx

    public void ProcessRequest(HttpContext context)
        {
            SqlConnection myConnection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["FMMImages"].ConnectionString);

            myConnection.Open();
            string sql = "select largeimage from images_temp where id=@memberid";
            SqlCommand cmd = new SqlCommand(sql, myConnection);
            int param;
            int.TryParse(context.Request.QueryString["memberid"], out param);
            cmd.Parameters.Add("@memberid", SqlDbType.Int).Value = param;
            //cmd.Parameters.Add("@GuID", SqlDbType.UniqueIdentifier).Value = context.Request.QueryString["UID"].ToString();

            cmd.CommandType = System.Data.CommandType.Text;

            SqlDataReader dReader = cmd.ExecuteReader();
            dReader.Read();
            context.Response.BinaryWrite((byte[])dReader["largeimage"]);
            dReader.Close();
            myConnection.Close();


        }

Also, I have a breakpoint in the ashx handler. Looks like the handler isn't firing.


回答1:


Try setting the ContentType:

context.Response.ContentType = "image/png";

http://www.dotnetperls.com/ashx




回答2:


Try the following in your ProcessRequest method:

context.Response.ContentType = "image";

using (System.IO.MemoryStream str = new System.IO.MemoryStream(objData.ToArray(), true))
{
       str.Write(objData.ToArray(), 0, objData.ToArray().Length);
       Byte[] bytes = str.ToArray();
       context.Response.BinaryWrite(bytes);
}

where objData is the value you are reading from the database




回答3:


The ImageUrl only replaces the tilde (~) in the control markup.

Try this instead:

string imageUrl = "~/AvatarImageFetch.ashx?memberid=" + memberid.ToString();
LargeImage.ImageUrl = Page.ResolveUrl(imageUrl);


来源:https://stackoverflow.com/questions/8733875/display-image-using-ashx-handler

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!