I would like to display a jpeg image on UI. For this, I request my service (GET method) and then I converted to base 64:
$http({
url: "...",
method: "GET",
headers: {'Content-Type': 'image/jpeg'}
}).then(function(dataImage){
var binary = '';
var responseText = dataImage.data;
var responseTextLen = dataImage.data.length;
for (var j = 0; j < responseTextLen; j+=1) {
binary += String.fromCharCode(responseText.charCodeAt(j) & 0xff)
}
base64Image = 'data:image/jpeg;base64,' + window.btoa(binary);
});
In the end, my browser tells me that the image is corrupt or truncated. So I tried creating a XMLHttpRequest using a overrideMimeType('text / plain; charset = x-user-defined') and it works:
var xhr_object = new XMLHttpRequest();
xhr_object.overrideMimeType('text/plain; charset=x-user-defined');
xhr_object.open('GET', '...', false);
xhr_object.send(null);
if(xhr_object.status == 200){
var responseText = xhr_object.responseText;
var responseTextLen = responseText.length;
var binary = ''
for (var j = 0; j < responseTextLen; j+=1) {
binary += String.fromCharCode(responseText.charCodeAt(j) & 0xff)
}
base64Image = 'data:image/jpeg;base64,' + window.btoa(binary);
}
what is the difference?
I know this isn't an answer so I'm not sure if it's even worth posting. It's similar to what you're doing but in the opposite direction! But here goes:
I'm posting an image data string from a canvas element (canvas.toDataURL("image/png")) to the server (node + express), saving it as a png on the server, then serving that image as a URL to a third party API.
Here's the original XMLHttpRequest I had in an angular.js controller:
Here it is converted into an angular.js $http service:
express function to save the image on the server:
Now AngularJS respects the XHR (XMLHttpRequest) standard and you can use plain angular JS
$http
combined with the HTML FileReader.The trick is to get the data as a blob which you pass to the reader.