0
votes

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.

1
Can you show(print) the first 4 bytes in your uint8 array? Like alert("bytes : " + myArray[0] + "," + myArray[1] + "," + myArray[2] + "," + myArray[3]); then paste here. You have an Answer about base64 but your data may not be in such format. We need correct information.VC.One
Alerting First 4 Bytes : - bytes : 137,80,78,71simple user

1 Answers

1
votes

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