jQuery Ajax call to HTTP Handler (.ashx)
I have an HTTP Handler that sends an image to the client (during a postback):
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);
}
e开发者_如何转开发lse
{
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?
A few questions: 1) How to convert the image to 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?
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?
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:
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.
The best approach would be to write an img
tag with the src
pointing to httpHandler.
精彩评论