【Nestjs】Uploading images to Amazon S3

Upload images passed to the Nestjs API to Amazon S3.

For information on how to receive images in Nestjs, see here.

目次

Prerequisite.

There are pre-tasks for performing uploads to Amazon S3 in this article.

  • Creating buckets in the Amazon S3 console
  • Permissions for the bucket
  • Create IAM roles

For more information, see the official

Install AWS SDK for JavaScript

Install the JavaScript package provided by AWS.

$ npm install aws-sdk

Upload to Amazon S3

Create logic to upload to Amazon S3.

Create credential function

The development environment uses the information defined in the environment variables.
The production environment is taken from the metadata of the EC2 instance.

In this way, only authorised developers can access the environment during development, while the production environment can only be accessed from the deployed EC2 instance.

import { fromInstanceMetadata } from '@aws-sdk/credential-providers';

export const createAwsCredentials = () => {
  if (<NODE_ENV> === 'development') {
    return {
      accessKeyId: <AWS_ACCESS_KEY_ID>,
      secretAccessKey: <AWS_SECRET_ACCESS_KEY>,
    };
  } else {
    return fromInstanceMetadata();
  }
};

Amazon S3 upload methods.

Import from aws-sdk.

import {
  GetObjectCommand,
  PutObjectCommand,
  S3Client,
} from '@aws-sdk/client-s3';

Create a method to pass a File and upload it to S3.

The implementation is simple: new S3Client, PutObjectCommand to generate the command and S3Client.send to complete the upload.

The return value is an array of file names.

  async s3Upload(files: Express.Multer.File[]) {
    const s3Client = new S3Client({
      region: <AWS_S3_REAGION>,
      credentials: createAwsCredentials(),
    });

    const imagesInfo = [];
    for (const file of files) {
      const extend = file.originalname.match(/[^.]+$/);
      const fileName = `${crypto.randomUUID()}.${extend}`;
      const bucketParams = {
        Bucket: <AWS_S3_BUCKET_NAME>,
        Key: fileName,
        Body: file.buffer,
      };

      const command = new PutObjectCommand(bucketParams);
      await s3Client.send(command);

      imagesInfo.push({
        image_name: fileName,
      });
    }

    return imagesInfo;
  }

Summary

The AWS SDK is well documented and can be implemented without any particular difficulties.
Please visit the official website.

よかったらシェアしてね!
目次