我试图通过httphandler显示二进制图像。这是我的代码:
ajax电话
$.ajax({
type: "GET",
url: "AnswerPostHandler.ashx",
data: "imgid=1380",
success: function (msg) {
$(parent).append(msg);
},
error: function (msg){
alert(msg);
}
});
处理程序代码
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/JPEG";
try
{
krystaladbDataContext db = new krystaladbDataContext();
var binimg = (from i in db.image_tables
where i.IMG_ID.Equals(1380)
select i.IMG_THUMB).Single();
byte[] b = binimg.ToArray();
MemoryStream ms = new MemoryStream(b);
Image img = Image.FromStream(ms);
img.Save(context.Response.OutputStream,
System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception ex)
{
context.Response.Write(ex);
}
}
这里看起来仍然不正确,它正在转储二进制数据。 Base64编码也是一个选择,但我测试了它,它不能在IE 7上工作(字面意思是切换图像的一部分)。
你可以告诉我我在这里做错了什么以及如何做对吗?感谢答案 0 :(得分:3)
处理程序代码,
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/JPEG";
try
{
krystaladbDataContext db = new krystaladbDataContext();
var binimg = (from i in db.image_tables
where i.IMG_ID.Equals(1380)
select i.IMG_THUMB).Single();
byte[] b = binimg.ToArray();
context.Response.BinaryWrite(b);
context.Response.Flush();
}
catch (Exception ex)
{
context.Response.Write(ex);
}
}
和html <img>
标记,
<img src="AnswerPostHandler.ashx?imgid=1380" alt="None" id="img1" />
或者您可以通过jQuery代码请求:
$("#showImageButton").click(function () {
$("#img1").attr("src", "AnswerPostHandler.ashx?imgid=1380");
});
答案 1 :(得分:-1)
做类似的事情会更容易 $(父)的.html( '')
二进制流很难在浏览器中作为img源实现。