Angular JS - request in order to get an image

三世轮回 提交于 2019-11-29 04:09:22

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

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");
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!