简体   繁体   中英

How to display image from Uint8Array in angularjs

I am trying to display image from Amazon S3 Bucket using Angular JS.

My Amazon S3 CORS Configuration are as follows:-

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

HTML Tag

<img ng-src="{{imgSrc}}">

Angular JS code to retrieve the image is as follows:-

$scope.retrieveImage = function()
    {
       AWS.config.update({
                accessKeyId: "MyAccessKey", secretAccessKey: "MySecretKey"
            });

       var bucket = new AWS.S3({ params: { Bucket: "MyBucket" } });

       bucket.getObject({ Key: 'Datetime.png' }, function (err, file) {
         $scope.imgSrc= "";
       });
    }

The file.Body parameter inside getObject() method is coming as Uint8Array.

Please help me on this:-

  1. Is this the standard coding to retrieve image from Amazon S3 when using Angular JS? Should file.Body always comes as Uint8Array
  2. How to convert Uint8Array object to image and show inside the webpage? Please note that uploaded image can be of any format like JPEG/PNG/GIF etc.

It will be of really help if anyone can provide working example.

Try like this :

$scope.retrieveImage = function() {
    var mypath = "https://mybucket.s3.amazonaws.com/Datetime.png";
    mypath = mypath.substr(1);
    AWS.config.update({
        accessKeyId: "MyAccessKey",
        secretAccessKey: "MySecretKey"
    });
    var bucketInstance = new AWS.S3();
    var params = {
        Bucket: "MyBucket",
        Key: mypath
    }
    bucketInstance.getObject(params, function(err, data) {
        if (data) {
            $scope.imgSrc= "data:image/jpeg;base64," + encode(data.Body);
        } else {
            console.log('error::', err);
        }
    });
}

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