简体   繁体   English

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

[英]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个表:

  1. UserRegistration(uid(PK),username....) UserRegistration(uid(PK),用户名...)
  2. Profile(profileID(PK),uid(FK),fulname,userPic...) 个人资料(profileID(PK),uid(FK),全名,userPic ...)
  3. Comment(cmntID(PK),cmntText,uid(FK)....) 注释(cmntID(PK),cmntText,uid(FK)....)

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.usernameitem.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.

相关问题 如何从数据库中的ASP.NET图像控件中加载图像? - How to load image in image control of ASP.NET from database? 如何在Visual Studio 2012的(数据库)表中手动存储图像并在ASP.NET MVC中使用jquery ajax进行检索 - How to manually store image in (database) table in visual studio 2012 and retrieve using jquery ajax in asp.net mvc 在asp.net中使用jQuery Ajax将值插入数据库 - To insert values into database using jquery ajax in asp.net 具有Ajax历史记录(jquery地址)的Asp.net MVC,如何从URL加载? - Asp.net MVC with Ajax history (jquery address), how to load from the URL? 使用ASP.Net中的AJAX PageMethods从数据库中获取JQuery AutoComplete TextBox在Internet Explorer中不起作用 - JQuery AutoComplete TextBox from database using AJAX PageMethods in ASP.Net is not Working in Internet Explorer 使用ASP.Net中的AJAX PageMethods从数据库实现jQuery AutoComplete TextBox - Implement jQuery AutoComplete TextBox from database using AJAX PageMethods in ASP.Net 如何使用JQuery ajax而不使用asp.net webform将图像上传到服务器端? - how to upload image to server side using JQuery ajax and without library using asp.net webform? 如何在ASP.NET MVC中使用jQuery / Ajax将数据插入数据库? - How to insert data into a database using jQuery / Ajax in ASP.NET MVC? 如何在Web浏览器中从数据库中将ASP.NET中的图像作为文件加载? - How to load an image in ASP.NET from a database as a file in a web browser? 如何从ASP.NET MVC中的数据库加载图像? - How do I load an image from a database in ASP.NET MVC?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM