Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
116
rated 0 times [  123] [ 7]  / answers: 1 / hits: 79048  / 14 Years ago, thu, december 30, 2010, 12:00:00

Using Javascript, I'm making an AJAX call to a WCF service, and it is returning a byte array. How can I convert that to an image and display it on the web page?


More From » ajax

 Answers
3

I realize this is an old thread, but I managed to do this through an AJAX call on a web service and thought I'd share...




  • I have an image in my page already:



     <img id=ItemPreview src= />

  • AJAX:



    $.ajax({
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    timeout: 10000,
    url: 'Common.asmx/GetItemPreview',
    data: '{id:' + document.getElementById(AwardDropDown).value + '}',
    success: function (data) {
    if (data.d != null) {
    var results = jQuery.parseJSON(data.d);
    for (var key in results) {
    //the results is a base64 string. convert it to an image and assign as 'src'
    document.getElementById(ItemPreview).src = data:image/png;base64, + results[key];
    }
    }
    }
    });



My 'GetItemPreview' code queries a SQL server where I have an image stored as a base64 string and returns that field as the 'results':



     string itemPreview = DB.ExecuteScalar(String.Format(SELECT [avatarImage] FROM [avatar_item_template] WHERE [id] = {0}, DB.Sanitize(id)));
results.Add(Success, itemPreview);
return json.Serialize(results);


The magic is in the AJAX call at this line:



     document.getElementById(ItemPreview).src = data:image/png;base64, + results[key];


Enjoy!


[#94442] Tuesday, December 28, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
amari

Total Points: 736
Total Questions: 111
Total Answers: 90

Location: Saint Pierre and Miquelon
Member since Fri, Jan 28, 2022
2 Years ago
;