简体   繁体   English

将Byte数组转换为Angularjs中的Base64字符串

[英]Convert Byte array to Base64 string in Angularjs

I am getting byte array in service response and that image would be shown in an image field of my html page. 我在服务响应中获取字节数组,该图像将显示在我的html页面的图像字段中。 Any idea how can i implement this. 任何想法我怎么能实现这一点。 I tried to find out solution for this over stack overflow but not able to get valid solution. 我试图找出这个堆栈溢出的解决方案,但无法获得有效的解决方案。 Please help. 请帮忙。 My code is: 我的代码是:

this.getPrescription = function(pres_id) {
     var deff = $q.defer();
     $http({
           method: "GET",
           url: "www.abc.com/api/&prescriptionOnly=false&page=1",
           headers: {
           'Authorization': 'Bearer ' + localStorage.getItem("chemist_access_token"),
           'Content-Type': 'application/json'
           },
           responseType: 'arraybuffer'
           }).then(function(objS) {
                   console.log("getPrescription:\n" + JSON.stringify(objS))
                   deff.resolve(objS);
                   }, function(objE) {
                   errorHandler.serverErrorhandler(objE);
                   deff.reject(objE);
                   });
     return deff.promise;
     };

and in my controller I am calling like: 在我的控制器中,我打电话给:

$scope.getPrescription = function(id) {
    $ionicLoading.show({
        template: '<ion-spinner icon="spiral"></ion-spinner>',
        noBackdrop: false
    });
    serverRepo.prescriptionGet(id).then(function(objS) {
        console.log("orderByCustomer:\n" + JSON.stringify(objS));
        $scope.picdata=$window.URL.createObjectURL(new Blob([objS.data], {type: 'image/png'}));

        $ionicLoading.hide();
        console.log("getOrderByNew_success_loadMore:\n" +$scope.picdata);
    }, function(objE) {
        $ionicLoading.hide();
    });
}

and when I check my console it showing: getOrderByNew_success_loadMore: blob:file:///0aa86d9f-61a1-4049-b18c-7bf81e05909f 当我检查我的控制台时,它显示:getOrderByNew_success_loadMore:blob:file:/// 0aa86d9f-61a1-4049-b18c-7bf81e05909f

Use this filter to convert byte array to base64 使用此过滤器将字节数组转换为base64

app.filter('bytetobase', function () {
    return function (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);
    };
});

to bind it as image use 将其绑定为图像使用

<img ng-src="data:image/JPEG;base64,{{picture | bytetobase}}" alt="..." width="100" height="100">

Or if you need to assign it a variable use 或者,如果您需要为其分配变量使用

var image = $filter('bytetobase')($scope.picture );

If you need to display and image from byte array you can create an object using Blob and get it's URL to pass into the image tag source. 如果需要从字节数组中显示和映像,可以使用Blob创建一个对象,并获取它的URL以传递到图像标记源。 The last parameter in Blob constructor contains information about blob type, so you should set correct type during blob creation. Blob构造函数中的最后一个参数包含有关blob类型的信息,因此应在blob创建期间设置正确的类型。

$http.get(url, {responseType: 'arraybuffer'})
  .then(function(response) {
    return $window.URL.createObjectURL(new Blob([response.data], {type: 'image/png'}));
  });

And when you don't plan to work with your object any longer (eg after image has been loaded in appropriate img tag) 当你不打算再使用你的对象时(例如在图像加载到适当的img标签之后)

Update 更新

Alternative solution with base64 使用base64的替代解决方案

$scope.getPrescription = function(id) {
  $ionicLoading.show({
    template: '<ion-spinner icon="spiral"></ion-spinner>',
    noBackdrop: false
  });
  serverRepo.prescriptionGet(id).then(function(objS) {
    console.log("orderByCustomer:\n" + JSON.stringify(objS));
    // Creating file reader
    var reader = new window.FileReader();
    // Creating blob from server's data
    var data = new Blob([objS.data], {type: 'image/jpeg'});
    // Starting reading data
    reader.readAsDataURL(data); 
    // When all data was read
    reader.onloadend = function() {
      // Setting source of the image
      $scope.picdata = reader.result;
      // Forcing digest loop
      $scope.$apply();
    }

    $ionicLoading.hide();
    console.log("getOrderByNew_success_loadMore:\n" +$scope.picdata);
    }, function(objE) {
    $ionicLoading.hide();
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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