【问题标题】:AngularJS/Ionic displaying image from APIAngularJS/Ionic 从 API 显示图像
【发布时间】:2016-08-16 20:35:29
【问题描述】:

我正在尝试通过 Web API 从第三方来源将 PNG 图像加载到我的 Ionic 应用程序中,但它无法显示。我收到的响应包含 PNG 的数据,我认为它是一个字节数组数据,并且开始如下:

�PNG IHDR��R�l pHY....

首先进行以​​下 API 调用:

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

然后将数据应用到我的控制器内的“图像”变量

$scope.image = response.data;

然后我使用我在此处找到的 Base64 编码/解码将数据转换为 base64 字符串:https://stackoverflow.com/questions/246801/how-can-you-encode-a-string-to-base64-in-javascript

最后,在我的 HTML 中,我有这个:

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

结果是一个空框,其中将显示图像,而不是损坏的图像链接。我尝试了在 Stackoverflow 上找到的各种解决方案,但我似乎无法坚持。还应该注意的是,我的配置中确实有以下内容:

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

...在我的 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: *">

我再次尝试通过 API 调用将 PNG 图像加载到我的应用程序中。我相信我收到了图像的字节数组表示,但是当我尝试将其转换为 base64 时,图像不会加载。此外,我在控制台中没有收到任何错误。

如果有人能给我一些见解,那将有很大帮助,谢谢。

【问题讨论】:

  • 我还尝试将数据转换为“Blob”对象,然后从 window.FileReader() 读取它,以获得与预期完全相同的输出。但是图像仍然无法正确显示。

标签: javascript angularjs image encoding bytearray


【解决方案1】:

你的答案有一个线索。您必须从您的对象创建一个 fileurl 并使角度信任它。至于 pdf,您应该能够使用 {{fileURL}} 使用示例中的 img 标签将图像添加到您的 html 中。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    相关资源
    最近更新 更多