Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

net::ERR_INVALID_URL when setting <img> src from $http.get result

I have a angular directive that works on img tags and loads the image dynamically as a base64 string. I use $http.get to load the image and set it into the img.src like this:

var onSuccess = function(response) {
  var data = response.data;
  element.attr("src", "data:image/png;base64," + data);
};
var onError = function(response) {
  console.log("failed to load image");
};
scope.$watch('authSrc', function(newValue) {
  if (newValue) {
    $http({
      method: "GET",
      url: scope.authSrc,
      data: ""
    }).then(onSuccess, onError)
  }
});

after i set the src attribute, i get the net::ERR_INVALID_URL error. The string that returns from the request looks like this: IHDR����^tiDOT@(@@AMȯz�@IDATx��uw\�ٷ�o����G�B["...

Any ideas?

thanks

like image 430
Lior Paz Avatar asked Dec 05 '25 05:12

Lior Paz


1 Answers

Got it to work will the help of This link.

Trick was to use responseType: "blob", and use URL/webkitURL createObjectURL()

Here's the full directive:

'use strict';

app.directive('authSrc',function ($http) {
    return {
      restrict: 'A',
      scope: {
        authSrc: "="
      },
      link: function (scope, element) {
        var onSuccess = function(response) {
          var data = response.data;
          var url = window.URL || window.webkitURL;
          var src = url.createObjectURL(data);
          element.attr("src", src);
        };

        var onError = function(response) {
          console.log("failed to load image");
        };

        scope.$watch('authSrc', function(newValue) {
          if (newValue) {
            $http({
              method: "GET",
              url: scope.authSrc,
              responseType: "blob"
            }).then(onSuccess, onError)
          }
        });


      }
    }
  });
like image 169
Lior Paz Avatar answered Dec 07 '25 19:12

Lior Paz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!