[英]How to load image from database using jquery ajax in asp.net
I am creating comment system in ASP.Net through jQuery AJAX but I am facing a problem of loading images from the database. 我正在通过jQuery AJAX在ASP.Net中创建注释系统,但是我面临着从数据库加载图像的问题。 I have 3 tables in the database:
我在数据库中有3个表:
The following is the jQuery AJAX code: 以下是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 += '<div class="q2" style="background-color: red">' +
'<img src="' + item.userPic + '" class="img-circle" width="32px" height="32px" />'+
'<span>' + item.username + '</span>' +
'<p>' + item.cmntText + '</p>' + '</div>';
});
loadPost.html(trHtml);
}
Here is the problem with item.userPic
which is inside the loop. 这是循环内的
item.userPic
问题。 item.username
and item.cmntText
works well but item.userPic
is not working. item.username
和item.cmntText
正常工作,但item.userPic
无法正常工作。 However when i access another attribute of the Profile table like fulname
then it works. 但是,当我访问Profile表的另一个属性(例如
fulname
它就会起作用。 I just can't access userPic
of the same table. 我只是无法访问同一表的
userPic
。
This is the code behind in C#: 这是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);
}
This is the result that I get: 这是我得到的结果:
If you are retrieving a base64 encoded string, set the 'src' attribute of the image tag with the base64 encoded string. 如果要检索base64编码的字符串,请使用base64编码的字符串设置image标签的'src'属性。 For example:
例如:
$("#img").attr('src','data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==');
In case you are retrieving the path of the image, you have to retrieve the image using ajax call and use the HttpContext.Current.Server.MapPath("~/")
in asmx where you have to specify the location of your image folder. 如果要检索图像的路径,则必须使用ajax调用来检索图像,并使用asmx中的
HttpContext.Current.Server.MapPath("~/")
在其中必须指定图像文件夹的位置。
add the below code snippet to a function or web method, 将以下代码段添加到函数或网络方法中,
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();
}
Note: Replace the 'Uploads' according to your needs which is the folder where your image exists. 注意:根据您的需要替换“上传”,即图像所在的文件夹。 Also note that i'm passing the 'DocumentName' which is actually the file name only.
另请注意,我正在传递“ DocumentName”,它实际上只是文件名。
You have to another page or handler that accepts user id and returns an image, the code should works as below: 您必须转到另一个接受用户ID并返回图像的页面或处理程序,代码应如下所示工作:
In the JavaScript block, you will change the part that draws the image tag 在JavaScript块中,您将更改绘制图像标签的部分
$.each(newData, function (i, item) {
trHtml += '<div class="q2" style="background-color: red">' +
'<img src="/GetUserImage?userId=' + item.username + '" class="img-circle" width="32px" height="32px" />'+
'<span>' + item.username + '</span>' +
'<p>' + item.cmntText + '</p>' + '</div>';
});
Then create a new HTTP Handler as below 然后创建一个新的HTTP处理程序,如下所示
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);
}
}
Then register the handler in web.config 然后在web.config中注册处理程序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.