Angular JS - request in order to get an image

2019-01-24 09:05发布

问题:

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?

回答1:

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?)");
    });


回答2:

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:

var dataURL = encodeURIComponent(canvas.toDataURL("image/png"));
var url = "/camera/" + name + "/";

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = response;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("image=" + dataURL);

Here it is converted into an angular.js $http service:

var dataURL = encodeURIComponent(canvas.toDataURL("image/png"));
var url = "/camera/" + name + "/";

var config = {
  method: 'POST',
  url: url,
  data: $.param({ image: dataURL }),
  headers: {'Content-Type': 'application/x-www-form-urlencoded'}
};

$http(config);

express function to save the image on the server:

app.post('/camera/:username', function (req) {
  var username = req.params.username,
    image = decodeURIComponent(req.body.image),
    binaryData;

  var base64Data = image.replace(/^data:image\/png;base64,/, "");
  base64Data += base64Data.replace('+', ' ');
  binaryData = new Buffer(base64Data, 'base64').toString('binary');

  fs.writeFile("public/camera-images/" + username + ".png", binaryData, "binary");
});