如何在asp.net中使用jquery ajax从数据库加载图像

我正在通过jQuery AJAX在ASP.Net中创建评论系统,但我面临着从数据库加载图像的问题。 我在数据库中有3个表:

  1. 放在userRegistration(UID(PK),用户名….)
  2. 配置文件(配置文件ID(PK),UID(FK),fulname,userPic …)
  3. 评论(cmntID(PK),cmntText,UID(FK)….)

以下是jQuery AJAX代码:

function getcomment() { var postPlace = $('div.q1'); $.ajax({ url: '/WebForm1.aspx/GetComment', contentType: "application/json; charset=utf-8", data: "{}", dataType: 'json', type: 'POST', success: function (data) { var newData = jQuery.parseJSON(data.d); var trHtml = ''; var loadPost = postPlace; $.each(newData, function (i, item) { trHtml += '
' + ''+ '' + item.username + '' + '

' + item.cmntText + '

' + '
'; }); loadPost.html(trHtml); }

这是item.userPic的问题,它位于循环内部。 item.usernameitem.cmntText工作正常,但item.userPic不起作用。 但是,当我访问配置文件表的另一个属性,如fulname然后它的工作原理。 我只是无法访问同一个表的userPic

这是C#背后的代码:

 [WebMethod] public static string GetComment() { string connection = ConfigurationManager.ConnectionStrings["connection"].ConnectionString; SqlConnection con = new SqlConnection(connection); SqlDataAdapter da = new SqlDataAdapter("select * from userregistration inner join comment on userregistration.uid=comment.uid inner join profile on comment.uid=profile.uid order by cmntID DESC ", con); DataTable dt = new DataTable(); da.Fill(dt); return JsonConvert.SerializeObject(dt); } 

这是我得到的结果:

在此处输入图像描述

如果要检索base64编码的字符串,请使用base64编码的字符串设置image标记的’src’属性。 例如:

 $("#img").attr('src','data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='); 

如果要检索图像的路径,则必须使用ajax调用检索图像,并使用asmx中的HttpContext.Current.Server.MapPath("~/") ,您必须指定图像文件夹的位置。

将以下代码段添加到函数或Web方法中,

 string strdocPath; try { strdocPath = (Server.MapPath("~\\Uploads\\" + DocumentName)); FileStream objfilestream = new FileStream(strdocPath, FileMode.Open, FileAccess.Read); int len = (int)objfilestream.Length; Byte[] documentcontents = new Byte[len]; objfilestream.Read(documentcontents, 0, len); objfilestream.Close(); string result = Convert.ToBase64String(documentcontents); return result; } catch (Exception ex) { return ex.ToString(); } 

注意:根据您的需要替换“上传”,这是您的图片所在的文件夹。 另请注意,我传递的是’DocumentName’,它实际上只是文件名。

您必须使用另一个接受用户ID并返回图像的页面或处理程序,代码应如下所示:

在JavaScript块中,您将更改绘制图像标记的部分

 $.each(newData, function (i, item) { trHtml += '
' + ''+ '' + item.username + '' + '

' + item.cmntText + '

' + '
'; });

然后创建一个新的HTTP Handler,如下所示

 public class UserImagesHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { //Get username from from query string //Get binary data context.Response.ContentType = "image/jpeg"; context.Response.BinaryWrite(bytes); } } 

然后在web.config中注册处理程序