Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS - request in order to get an image

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?

like image 910
Julien METZMEYER Avatar asked May 27 '13 14:05

Julien METZMEYER


1 Answers

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.

var url = 'http://'; // enter url here
$http.get(url,{responseType: "blob"}).
    success(function(data, status, headers, config) {
        // encode data to base 64 url
        fr = new FileReader();
        fr.onload = function(){
            // this variable holds your base64 image data URI (string)
            // use readAsBinary() or readAsBinaryString() below to obtain other data types
            console.log( fr.result );
        };
        fr.readAsDataURL(data);
    }).
    error(function(data, status, headers, config) {
        alert("The url could not be loaded...\n (network error? non-valid url? server offline? etc?)");
    });
like image 144
Daan Avatar answered Sep 28 '22 02:09

Daan