Home > front end >  Display images from S3
Display images from S3

Time:12-22

I have Amazon AWS S3 Bucket and images inside. Every object in my bucket has its own link. When I open it a browser ask me to download the image. So, it is a download link, but not directly the link of the image in the Internet. Of course, when I put it to <img src="https://"> it doesn't works.

So my question is how I can display images from S3 on my client so that I will not be forced to download images instead of just watching them on the site.

My Stack: Nest.js & React.js (TypeScript)

How I upload images:

one service:

const svgBuffer = Buffer.from(svgString, 'utf-8');
mainRes = await uploadFile(currency, svgBuffer);

another service I got uploadFile function from:

uploadFile = (currency: string, svg: Buffer) => {
        const uploadParams = {
            Bucket: this.config.S3_BUCKET_NAME,
            Body: svg,
            Key: `${currency}-chart`,
        };

        return this.s3.upload(uploadParams).promise();
    };

How I supposed to get my images:

<img src=`https://${s3bucketPath}/${imagePath}`>

CodePudding user response:

It could be a problem with object metadata. Check the metadata and validate the Content type. For example for an PNG image should be:

Content-Type='image/png'

If object's Content-Type is 'binary/octet-stream' then it will download instead of display.

Add the corresponding parameter when uploading through JavaScript SDK:

const uploadParams = {
        Bucket: this.config.S3_BUCKET_NAME,
        Body: svg,
        Key: `${currency}-chart`,
        ContentType: 'image/png',
    };

CodePudding user response:

After the image is uploaded you have multiple options to get them without downloading them to your application.


The easiest one but not the best is getting them directly from the S3 Bucket.

Let's say We have the bucket: bucket-test, You can get URL directly in the browser:  s3 bucket

But Your object must be public which is unsafe. Moreover, it will be generating additional costs in the form of the transfer.


The next option is to set up CloudFront which will create a CDN for your

Then you are creating the CloudFront which points to S3 objects

Some pros

  • Your bucket objects may be private.
  • This is also faster as images are cached in the AWS Cloudfront edges.
  • You can also set alternative names for your Cloudfront distribution and hide objects.

Your traffic looks like this:

When an image is not cached

USER <-> Cloudfront Edge <-> S3

When the image is cached:

USER <-> Cloudfront Edge

Here is how to setup the CDN: https://aws.amazon.com/cloudfront/getting-started/S3/

  • Related