我在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;
});
它正在发送所需的数据并从数据库中取出图像并发送回来,但我无法将其分配给图像控件。我如上所述分配它,它显示所有符号,我猜这是数据,但如何表示它图像格式任何帮助或解决方法都很棒
先谢谢。
答案 0 :(得分:1)
我知道一个解决方案可以为你工作,你不必使用ajax调用就可以了,只需这样做,
$('.ajaxcall').click(function () {
var id = $('#txtid').val();
var data = 'id=' + id;
var imageurl = 'Handler1.ashx?' + data;
$('#image2').attr('src', imageurl);
});
这将为您提供图像