[英]How to load image from database using jquery ajax in asp.net
我正在通過jQuery AJAX在ASP.Net中創建注釋系統,但是我面臨着從數據庫加載圖像的問題。 我在數據庫中有3個表:
以下是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);
}
這是循環內的item.userPic
問題。 item.username
和item.cmntText
正常工作,但item.userPic
無法正常工作。 但是,當我訪問Profile表的另一個屬性(例如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("~/")
在其中必須指定圖像文件夾的位置。
將以下代碼段添加到函數或網絡方法中,
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 += '<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>';
});
然后創建一個新的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);
}
}
然后在web.config中注冊處理程序
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.