jQuery Ajax 调用 HTTP 处理程序 (.ashx)
我有一个 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;
}
}
}
如何使用此处理程序通过 jQuery ajax 请求将图像发送到客户端?
有几个问题: 1)如何将图像转换为JSON? 2)如果无法将图像转换为JSON,我可以使用哪种格式将图像发送到客户端?
Tnx很多!
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);
}
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?
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只是想将其显示在页面上吗?为什么不直接编写一个 img 标签,其中 src 指向您的处理程序?
像这样的东西:
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:
1) 要将图像作为 JSON 发送,您需要将其转换为 base64 编码的字符串:
2) 但是,并非所有浏览器(IE < 8)都支持该数据-您需要使用它来显示这些 Base64 编码图像的 uri 方案。
最好的方法是编写一个
img
标记,其中src
指向 httpHandler。1) To send the image as JSON, you need to convert it to base64 encoded string:
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 thesrc
pointing to httpHandler.