0

I am creating comment system in ASP.Net through jQuery AJAX but I am facing a problem of loading images from the database. I have 3 tables in the database:

  1. UserRegistration(uid(PK),username....)
  2. Profile(profileID(PK),uid(FK),fulname,userPic...)
  3. Comment(cmntID(PK),cmntText,uid(FK)....)

The following is the jQuery AJAX code:

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.username and item.cmntText works well but item.userPic is not working. However when i access another attribute of the Profile table like fulname then it works. I just can't access userPic of the same table.

This is the code behind in 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:

enter image description here

4
  • We need some more detail here. Is the userpic stored as a string path or a base64 encoded string? What is the value you get? What is the value you expect? Commented Oct 13, 2016 at 7:44
  • I think he become an json as response. So can you please check your console.logs and check the image path (open URL in new tab) to check availbilty. Commented Oct 13, 2016 at 7:47
  • @Rory he userPic is stored as a string path so i just want to display that stored images from database using jquery ajax Commented Oct 13, 2016 at 13:21
  • What does console.log(item.userPic) log at console? Commented Oct 15, 2016 at 5:43

2 Answers 2

1

If you are retrieving a base64 encoded string, set the 'src' attribute of the image tag with the base64 encoded string. 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.

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.

Sign up to request clarification or add additional context in comments.

2 Comments

i'm using string path not base64..... kindly explain it with an example if you don't mind plz i really need it .... and i'm storing image like this: fileupload.PostedFile.SaveAs(Server.MapPath("~/images/") + fileupload.FileName);
This will make the whole request too slow and its size will be huge, specially if there were many comments
0

You have to another page or handler that accepts user id and returns an image, the code should works as below:

In the JavaScript block, you will change the part that draws the image tag

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.