我在aspx上创建了一个图像控件,代码如下
<div>
<div class="ajaxdata">
<asp:Image ID="image2" runat="server"></asp:Image>
</div>
<a class="ajaxcall">click to see image </a>
</div>
然后对于普通按钮单击,我正在使用处理程序动态获取图像,如下所示
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("<p>Need a valid id</p>");
}
}
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;
});
它正在发送所需的数据并从数据库中获取图像并发送回,但我无法将其分配给图像控件。我按上述方式分配了它,它显示了我猜是数据的所有符号,但如何以图像格式表示它帮助或解决方法很棒
提前致谢。