How to display images from the Amazon S3 bucket?

If you are using Amazon S3 for storing images then mostly then you will arrive at a situation of displaying those images on a webpage. You can use javascript, angular, or any other programming language in the frontend but you need to keep some points in mind before proceeding.

In case you are someone new to AWS then take a look at this article to know what AWS is and what solution they offer.

Enable CORS on S3 Bucket

Despite your bucket and image being public or private you need to enable CORS on your S3 bucket. Go to the S3 console and click on your bucket name. Then navigate to “Permissions” as shown below.

Scroll down and go to “Cross-origin resource sharing (CORS)” section and click edit.

Paste the following JSON and click save changes.

[
    {
     "AllowedHeaders": [
       "" 
      ], 
     "AllowedMethods": [
       "GET",
       "HEAD" 
      ], 
     "AllowedOrigins": [
       ""
    ],
    "ExposeHeaders": [],
    "MaxAgeSeconds": 3000
    }
]

NOTE: In the above CORS JSON, after hosting the website change AllowedOrigins object from “*” to your server name so that only your application can access it.

Now CORS is successfully enabled.

Frontend Code

For this demo, I am going to use javascript for reading images. You can use any language but if your S3 image object is not public, then you need to generate a pre-signed URL (SDK will take care of it, provided you are passing “signatureVersion” as a parameter).

<!DOCTYPE html>
<html lang="en">
<head>
  <script src="https://sdk.amazonaws.com/js/aws-sdk-2.179.0.min.js"></script>
</head>
<body>
  <img height="200" width="200">
  <script>

    var mimes = {
        'jpeg': 'data:image/jpeg;base64,'
    };

      AWS.config.update({
          signatureVersion: 'v4', // pre-signing
          region: 'ENTER_REGION_NAME', //us-east-1
          accessKeyId: 'ENTER_YOUR_ACCESS_KEY',
          secretAccessKey: 'ENTER_YOUR_SECRET_KEY'
      });

      var bucket = new AWS.S3({params: {Bucket: 'BUCKET_NAME'}});

      function encode(data)
      {
          var str = data.reduce(function(a,b){ return a+String.fromCharCode(b) },'');
          return btoa(str).replace(/.{76}(?=.)/g,'$&\n');
      }

      function getUrlByFileName(fileName,mimeType) {
          return new Promise(
              function (resolve, reject) {
                  bucket.getObject({Key: fileName}, function (err, file) {
                      var result =  mimeType + encode(file.Body);
                      resolve(result)
                  });
              }
          );
      }

      function openInNewTab(url) {
        console.log(url);
          var redirectWindow = window.open(url, '_blank');
          redirectWindow.location;
      }

      getUrlByFileName('S3_FILE_PATH', mimes.jpeg).then(function(data) {
          document.querySelector('img').src = data;
      });

  </script>
</body>
</html>

Replace the Access key, Secret Key, Region, Bucket Name and Key appropriately.

Happy Coding!!

Leave a Comment