I am trying to dynamically populate my image tag src, by fetching binary data from a REST webservice. My link is something like myhost:port/docId/imageId/file which returns content type of "application/octet-stream" and datatType is binary. My approach is getting this binary data, base64 encode it(using jquery.base64.js) and then put the base64 encoded data in the src. Some code portions are as follows.
$.ajax({
url: " myhost:port/docId/imageId/file ",
datatype: "binary",
beforeSend: function (xhr) {
xhr.overrideMimeType("text/plain; charset=x-user-defined");
},
success: function(image){
var imgBase64 = $.base64.encode(image);
return imgBase64 ;
},
error: function(xhr, text_status){
console.log("An error again " + text_status);
}
});
Another plain AJAX approach I have taken is:
req.open('GET', " myhost:port/docId/imageId/file" , false);
req.overrideMimeType('text\/plain; charset=x-user-defined');
if (req.status != 200){
console.log("Status code not 200");
return '';
}
return req.responseText;
I am overriding the MIME type because if I dont, although GET is showing Status 200 OK, the fetch is throwing some error. Now I am base64 encoding "req.responseText" [var imgBase64 = $.base64.encode( req.responseText );]and putting it in the src of my image.
This is how I put the base64 data in img:
var imageSource = "data:image/png;base64," + imgBase64 ;
$('#imageId').attr('src', imageSource);
However while encoding in both the cases
jquery base64 is throwing me an exception "INVALID_CHARACTER_ERR: DOM Exception 5". Even if I encode it forcefully by suppressing this exception when I put the base64 data in src it shows corrupt data in Firebug. My feeling is as I am overriding the MIME type the encoding of binary data as it is coming is somehow getting tampered , so during base64 encoding it is giving some issues.
Can anyone suggest where I am going wrong or may be demonstrate how to fetch an image(jpeg/png/gif/sometimes tif) file from a REST api?
$('#imageId').attr('src', 'myhost:port/docId/imageId/file');