Reputation: 187
I have a POST request that is returning an image as a gif. As far as I can tell the response is not base64 encoded text. So how can I assign the image to the src tag of an img ?
The reason I say its not base64 encoded as I have tried to display it using data:image/gif;base64,"+ data
and this give me no result.
So then I tried encoding the repsonse using the jquery.base64 plugin (but that complained about invalid characters);
the response text looks like the following "GIF87a��" in fiddler, looking at the response textview. image view displays the image fine.
I have no access to the server to tell it to return in base64 either.
Any ideas or help would be greatly appreciated, maybe its something so simple I've missed it.
Thanks in advance.
Upvotes: 2
Views: 4401
Reputation: 21
Thanks to the answer from @xchg.ca, I was able to do this by jquery ajax call:
$.ajax({
type: "GET",
url: "imageURL",
beforeSend: function (xhr) {
xhr.overrideMimeType('text/plain; charset=x-user-defined');
},
success: function (result, textStatus, jqXHR) {
if(result.length < 1){
alert("The thumbnail doesn't exist");
$("#thumbnail").attr("src", "data:image/png;base64,");
return
}
var binary = "";
var responseText = jqXHR.responseText;
var responseTextLen = responseText.length;
for ( i = 0; i < responseTextLen; i++ ) {
binary += String.fromCharCode(responseText.charCodeAt(i) & 255)
}
$("#thumbnail").attr("src", "data:image/png;base64,"+btoa(binary));
},
error: function(xhr, textStatus, errorThrown){
alert("Error in getting document "+textStatus);
}
});
Upvotes: 1
Reputation: 1164
It is totally possible:
here is example:
var req = new XMLHttpRequest;
req.overrideMimeType('text/plain; charset=x-user-defined');
req.open('GET', "http://jonathanleighton.com/images/me.jpg", !1);
req.send(null);
for (var responseText = req.responseText, responseTextLen = responseText.length, binary = "", i = 0; i < responseTextLen; ++i) {
binary += String.fromCharCode(responseText.charCodeAt(i) & 255)
}
image.src = 'data:image/jpeg;base64,'+window.btoa(binary);
This is example from Internet, but confirmed that it works. 'POST' shoul work exactly the same way.
Upvotes: 5