3

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

Lior Paz
  • 71
  • 1
  • 7

3 Answers3

3

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


      }
    }
  });
Community
  • 1
  • 1
Lior Paz
  • 71
  • 1
  • 7
0

Specify the responseType in your request, and you may have to disable default transforms that $http attempts on the data.

see here

tanenbring
  • 780
  • 4
  • 14
  • Thanks @tanenbring, doesn't look like a request transform problem, but response type helped me get to the answer, which i'll post in a sec – Lior Paz Jan 30 '16 at 09:34
0

My problem was specifying a zoom level after the base64 string '#zoom=90'

Lord Darth Vader
  • 1,895
  • 1
  • 17
  • 26