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?
Advertisement
Answer
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:
JavaScriptx21<img id="ItemPreview" src="" />
2
AJAX:
JavaScript118181$.ajax({
2type: 'POST',
3contentType: 'application/json; charset=utf-8',
4dataType: 'json',
5timeout: 10000,
6url: 'Common.asmx/GetItemPreview',
7data: '{"id":"' + document.getElementById("AwardDropDown").value + '"}',
8success: function (data) {
9if (data.d != null) {
10var results = jQuery.parseJSON(data.d);
11for (var key in results) {
12//the results is a base64 string. convert it to an image and assign as 'src'
13document.getElementById("ItemPreview").src = "data:image/png;base64," + results[key];
14}
15}
16}
17});
18
My ‘GetItemPreview’ code queries a SQL server where I have an image stored as a base64 string and returns that field as the ‘results’:
JavaScript
1
4
1
string itemPreview = DB.ExecuteScalar(String.Format("SELECT [avatarImage] FROM [avatar_item_template] WHERE [id] = {0}", DB.Sanitize(id)));
2
results.Add("Success", itemPreview);
3
return json.Serialize(results);
4
The magic is in the AJAX call at this line:
JavaScript
1
2
1
document.getElementById("ItemPreview").src = "data:image/png;base64," + results[key];
2
Enjoy!