如何在angularjs

时间:2018-03-09 09:08:00

标签: angularjs

目前,我从服务器获取响应中的用户详细信息。从那个响应,我想编码图像,并希望它显示在我的前端。目前,我正在做的事情:

HTML:<img ng-src=data:image/png;base64,{{user_image}}>

Angularjs:

  $http({
  method: 'GET',
  url: 'userimage',
  }).then(function(response) {
     $scope.user_image = response.data;
     var str = _arrayBufferToBase64(response.data.user_image);
  }, function(response) {
    console.error('error.');
});


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

}

作为回应,我收到了用户详细信息,但我不知道如何对图像进行编码。请让我知道我哪里出错了。

1 个答案:

答案 0 :(得分:3)

你不应该将base64编码的字符串分配给范围变量而不是response.data吗? 我想,你真正想要的是:

$scope.user_image = _arrayBufferToBase64(response.data.user_image);

但是有一个问题。 您尚未将响应类型指定为“arraybuffer”。 请将其添加到您的请求配置对象:

responseType: 'arraybuffer'