简体   繁体   English

jQuery Ajax 调用 HTTP 处理程序 (.ashx)

[英]jQuery Ajax call to HTTP Handler (.ashx)

I have an HTTP Handler that sends an image to the client (during a postback):我有一个 HTTP 处理程序将图像发送到客户端(在回发期间):

    public class ImageHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        Byte[] pic = GetPhoto(Convert.ToInt32(context.Request.QueryString["userID"]));

        if (pic != null)
        {
            context.Response.ContentType = "image/jpeg";
            context.Response.OutputStream.Write(pic, 0, pic.Length);
        }
        else
        {
            context.Response.ContentType = "image/png";
            context.Response.WriteFile("/AllImages/DefaultPicture_large.png");
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

How can I use this handler to send the image to the client with a jQuery ajax request?如何使用此处理程序通过 jQuery ajax 请求将图像发送到客户端?

A few questions: 1) How to convert the image to JSON?几个问题:1)如何将图像转换为JSON? 2) If it's not possible to convert the image to JSON, which format can I use to send the image to the client? 2) 如果无法将图像转换为 JSON,我可以使用哪种格式将图像发送到客户端?

Tnx a lot!很多!

Are you just looking to display it on the page?您只是想在页面上显示它吗? Why not just write an img tag with the src pointing to your handler?为什么不直接写一个 img 标签,让 src 指向你的处理程序呢?

Something like:就像是:

var img_url = '/myImageHandler.ashx?userDI=' + some_user_id;
$("#displayArea").append($("<img src='" + img_url + "' alt='user image' />"));

1) To send the image as JSON, you need to convert it to base64 encoded string: 1)要将图像作为 JSON 发送,您需要将其转换为 base64 编码字符串:

 string imageString = Convert.ToBase64String(pic);
 return imageString;

2) However, not all browsers (IE < 8) support the data-uri scheme which you need to use to display those base64 encoded images. 2)但是,并非所有浏览器(IE < 8)都支持您需要用来显示那些 base64 编码图像的 data-uri 方案。

The best approach would be to write an img tag with the src pointing to httpHandler.最好的方法是编写一个img标签,其中src指向 httpHandler。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM