Neil Hodges
Neil Hodges

Reputation: 127

Retrieve Binary Image from DB via JSON and ashx then convert to image in html?

Ive been tasked to use this method, quite frankly id could do this server side in 2 sec's but need it all doing in javascript.

So here goes, i need to retrieve a binary image from the DB thats returned in a object called S_TeamMember. One of the properties is MainImg byte[]

im using JSON to call a ashx Handler to call the DB and retrieve the data.

    $(function () {
    var queryparam = getUrlVars()["CatLink"];

    $.ajax({
        url: "TeamGroups.ashx",
        data: { CatLink:  queryparam },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnTeamGroupsCompleted,
        error: OnPageFailM
    });
});

the JSON call above

     function OnTeamGroupsCompleted(result) {
    for (var i = 0; i < result.length; i++) {

        var name = result[i].Name;
        var recno = result[i].Recno;
        var mainimg = result[1].MainImg;
        var memholder = "<div class='PersonImageHolder'>" +
            "<div class='PersonImage'>" +
                "<img src='"+ mainimg +"'/>" + <------ PROBLEM IS HERE
            "</div>" +
            "<div class='PersonNameHolder inline-block'>" +
        "<div class='ImgHolderL inline-block'>" +
            "<img src='images/web/WhiteRibbonL.png' />" +
            "</div>" +
            "<div class='NameHolder inline-block'>" +
            "<p><a href='MemberDetail.aspx?TeammMemberLink="+ recno +"'>"+ name +"</a></p>" +
            "</div>" +
            "<div class='ImgHolderR inline-block'>" +
            "<img src='images/web/WhiteRibbonR.png' />" +
            "</div>" +
            "</div>" +
            "</div>";

        $('.Content').append(memholder);

    }
}

then above how im iterating through the JSON result to draw a div on the page with images. The trouble im having is or course parsing the 'MainImg' binary data into a html image tag.

Any ideas how i go about doing this?

Any help would be greatly appreciated

Upvotes: 0

Views: 882

Answers (2)

secondflying
secondflying

Reputation: 871

What's value of result[i].MainImg in OnTeamGroupsCompleted? JSON format natively doesn't support binary data. You can:

  1. write a new ashx
  2. pass name or id in url
  3. set ashx to img src
  4. in ashx output image binary data

in javascript:

"<img src='image.ashx?name"+ result[i].Name +"'/>" + <------ PROBLEM IS HERE

in image.ashx:

public void ProcessRequest(HttpContext context)
{
    string name = context.Request.QueryString["name"];
    //query database by name to get image binary data
    Byte[] bytes = ...;
    context.Response.ContentType = "image/png";
    context.Response.BinaryWrite(bytes);
}

Upvotes: 1

Selvaraj M A
Selvaraj M A

Reputation: 3136

I don't think it is doable using javascript! But instead you can store the url of the image in DB and return it to the browser.

Upvotes: 0

Related Questions