如何将ajax响应图像流分配给图像控件?

我在aspx上创建了一个图像控件,代码如下

 

然后对于正常按钮单击我使用处理程序动态获取图像如下所示

 public void ProcessRequest(HttpContext context) { context.Response.Clear(); if (!String.IsNullOrEmpty(context.Request.QueryString["id"])) { int id = Int32.Parse(context.Request.QueryString["id"]); // Now you have the id, do what you want with it, to get the right image // More than likely, just pass it to the method, that builds the image Image image = GetImage(id); // Of course set this to whatever your format is of the image context.Response.ContentType = "image/jpeg"; // Save the image to the OutputStream image.Save(context.Response.OutputStream, ImageFormat.Jpeg); } else { context.Response.ContentType = "text/html"; context.Response.Write("

Need a valid id

"); } } public bool IsReusable { get { return false; } } private Image GetImage(int id) { string path = string.Empty; SqlConnection con = new System.Data.SqlClient.SqlConnection(); con.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename='C:\Users\1483\Documents\Visual Studio 2010\Projects\WebApplication2\WebApplication2\App_Data\Database1.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True"; con.Open(); SqlCommand cmd = new SqlCommand(@"SELECT Path FROM Temp WHERE Id=@idparam", con); SqlParameter idparam = cmd.Parameters.Add("@idparam", SqlDbType.NVarChar,10); idparam.Value = id.ToString(); SqlDataReader rd = cmd.ExecuteReader(); if (rd.Read()) { path = rd.GetString(0); } byte[] data= File.ReadAllBytes(path); MemoryStream stream = new MemoryStream(data); return Image.FromStream(stream); }

和按钮点击c#代码是

 image2.ImageUrl = "Handler1.ashx?id=" + txtid.Text; 

这一切都完美地工作现在我想通过ajax调用获取图像并使用相同的处理程序将其分配给图像控件,所以我写了一个ajax调用如下

 $('.ajaxcall').click(function () { var id = $('#txtid').val(); var data = 'id=' + id; $.ajax({ type: "GET", cache: false, url: "Handler1.ashx", data: data, // multiple data sent using ajax success: function (html) { $('#image2').val(html); //This where i need to assign the image stream to the image control i don't know how to do it. } }); return false; }); 

它正在发送所需的数据并从数据库中取出图像并发回,但我无法将其分配给图像控件。我按上面的方式分配了它,它显示了所有符号,我猜这是数据,但如何以图像格式表示它帮助或解决是很好的

提前致谢。

我知道一个解决方案可以为你工作,你不必使用ajax调用它只是这样做,

  $('.ajaxcall').click(function () { var id = $('#txtid').val(); var data = 'id=' + id; var imageurl = 'Handler1.ashx?' + data; $('#image2').attr('src', imageurl); }); 

这会得到你的形象