简体   繁体   中英

AngularJS/Ionic displaying image from API

I'm attempting to load a PNG image into my Ionic app via a web API from a third-party source, but it's failing to display. The response I receive contains data for the PNG which I believe to be a byte array data and begins like this:

PNG IHDR R l pHY....

This starts by making the following API call:

function getImage(authToken) {
  var settings = {
    "async": true,
    "crossDomain": true,
    "url": imgLocation,
    "method": "GET",
    "headers": {
      "auth-token": authToken,
      "cache-control": "no-cache"
    }
  }
  return $http(settings)
    .then(function(response) {
      return response;
    })
    .catch(function(e) {
      return e.data;
    }); 
}

The data is then applied to the 'image' variable inside of my controller

$scope.image = response.data;

I then convert the data into a base64 string, using the the Base64 encode/decode I found here: https://stackoverflow.com/questions/246801/how-can-you-encode-a-string-to-base64-in-javascript

And then finally, into my HTML I have this:

<img ng-src="data:image/PNG;base64,{{image}}">

The result is an empty box in place where an image would be shown, and not a broken image link. I've attempted various solutions found on Stackoverflow but I can't seem to get anything to stick. It should also be noted that I do have the following in my config:

$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|file|ftp|blob):|data:image\//);

... and in my index.html:

<meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src 'self' 'unsafe-inline' *; img-src 'self' data: *">

So again, I'm attempting to load PNG images via API calls into my app. I believe I'm receiving a byte array representation of the image, but when I attempt to convert it to base64, the image doesn't load. Additionally, I'm not receiving any errors in the console.

If anyone could offer me some insight, it would be of great help, thanks.

there is a thread with your answer. You have to create a fileurl from your object and make angular trust it. As for the pdf you should be able to add the image to your html with {{fileURL}} using the img tag like in the example.

AngularJS: Display blob (.pdf) in an angular app

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM