如何在Angular JS中显示接收到的字节数组图像

9

我有一个服务器端应用程序,将返回一张图片。以下是响应头:

Content-Disposition: attachment; filename=8822a009-944e-43f4-999b-d297198d302a;1.0_low-res
Content-Length: 502343
Content-Type: image/png
Date: Mon, 03 Aug 2015 19:13:39 GMT
Server: Apache-Coyote/1.1

在Angular中,我需要显示图像。获取图像时,我使用AngularJS的$http调用服务器,并将结果放入作用域(scope),但我从未达到$http的success函数。使用Postman执行此调用会正常返回图像。我想知道如何让Angular显示图像。
这是我显示图片的方法:
<img ng-src={{image}} />

以下是从服务器获取图片的调用方法:

$http.get(url, {responseType: "arraybuffer"})
    .success(function(data) {
        $scope.image= data;
    }
)

你能发布向服务器的 $http 调用吗? - Bellu
是的,这就是它:$http.get(url, {responseType: "arraybuffer"}). success(function(data) { $scope.image= data; }) - Loshmeey
3个回答

11

我同意Bellu的回答,你应该使用.then函数而不是$http.get返回的promise上的.success函数。但是,我想你仍然会遇到一个问题,因为你没有提供URL,而是提供了对字节数组的引用。

要将ng-src引用绑定到客户端内存中保存的字节数组,你的绑定应采用以下形式:

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

编辑

由于我从未明确提到过,上面的ng-src绑定假定您的图像数据以base64格式存在。如果数组不是以base64格式存在,HarrisonA在下面提供了一种将其转换的方法。


谢谢大家的回应,使用Bellu发布的代码,我已经取得了进展,但是我现在还在为图像的显示而苦恼。在调试代码时,我可以看到响应中有图片,而且大小正确,但是图像仍然没有在用户界面(UI)中显示。我是否漏掉了些什么? - Loshmeey
搞定了。我们必须将arrayBuffer编码为base64字符串。现在一切都好了 :) 谢谢大家的回答! - Loshmeey
1
刚好昨天回来看到这个。很高兴你把它弄好了!值得一提的是,base64 可能不是唯一可用的格式,只是最常见的例子。你可以在这里进一步了解数据 URI 方案的格式:https://en.wikipedia.org/wiki/Data_URI_scheme#Format - jdmcnair
好的!感谢你的帮助! - Loshmeey
@jdmcnair 如果我有一张 .png 类型的图片,这个能用吗? - Vinit Divekar
显示剩余6条评论

8

我想要补充jdmcnair的回答和Loshmeey的评论:

以下是我用来将数组缓冲区转换为base64字符串的函数链接。

ArrayBuffer to base64 encoded string

该函数:

function _arrayBufferToBase64( buffer ) {
  var binary = '';
  var bytes = new Uint8Array( buffer );
  var len = bytes.byteLength;
  for (var i = 0; i < len; i++) {
    binary += String.fromCharCode( bytes[ i ] );
  }
  return window.btoa( binary );
}

我在我的Angular控制器中使用了这个函数,然后将结果(使用$scope变量)传递给我的HTML文件中的img元素。


1
+1 因为原始问题涉及字节数组,而不是Base64编码的字符串。你提供的片段正好缺失了将它们完美结合的部分。 - mks-d

2
  • 我认为你应该使用then回调,在angular文档中,他们说success回调已经被弃用。
  • 你的img在data响应属性中。

考虑到这些因素,你可以尝试像这样做。

$http.get(url, {responseType: "arraybuffer"} ).then(function(response) { 
$scope.image= response.data; });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接