How to upload file to s3 in Node.js?

s3Bucket in nodejs

If you are working on a Node.js project that requires file storage, Amazon S3 (Simple Storage Service) is an ideal solution. S3 provides a scalable, secure, and highly available way to store and retrieve files. In this article, we will guide you through the steps to configure an S3 bucket in a Node.js project.

Creating an S3 Bucket

The first step in configuring an S3 bucket is to create one. Follow these steps to create an S3 bucket:

  1. Log in to the AWS Management Console.
  2. Navigate to the S3 service.
  3. Click on the “Create bucket” button.
  4. Enter a unique name for your bucket.
  5. Select a region for your bucket.
  6. Click on the “Create” button.

Creating an AWS IAM User

To access your S3 bucket from a Node.js project, you will need to create an AWS IAM (Identity and Access Management) user with the appropriate permissions. Follow these steps to create an IAM user:

  1. Log in to the AWS Management Console.
  2. Navigate to the IAM service.
  3. Click on the “Users” menu item.
  4. Click on the “Add user” button.
  5. Enter a name for your user.
  6. Select “Programmatic access” as the access type.
  7. Click on the “Next: Permissions” button.
  8. Select “Attach existing policies directly” as the permissions type.
  9. Select the “AmazonS3FullAccess” policy.
  10. Click on the “Next: Tags” button.
  11. Click on the “Next: Review” button.
  12. Click on the “Create user” button.
  13. Save the access key ID and secret access key for your user.

Configuring AWS Credentials

Next, you need to configure your AWS credentials in your Node.js project. Follow these steps to configure your credentials:

  1. Install the AWS CLI (Command Line Interface) on your machine.
  2. Open a command prompt and run the command “aws configure”.
  3. Enter your access key ID and secret access key.
  4. Enter the default region for your bucket.
  5. Enter “json” as the default output format.

Installing the AWS SDK for Node.js

To interact with your S3 bucket from a Node.js project, you will need to install the AWS SDK (Software Development Kit) for Node.js. Follow these steps to install the AWS SDK:

  1. Open a command prompt in your project directory.
  2. Run the command “npm install aws-sdk”.

Uploading a File to S3

To upload a file to your S3 bucket from a Node.js project, you can use the AWS SDK’s “putObject” method. Here’s an example code snippet:

const AWS = require('aws-sdk');
const fs = require('fs');

const s3 = new AWS.S3();

const uploadFile = (fileName) => {
  const fileContent = fs.readFileSync(fileName);

  const params = {
    Bucket: 'your-bucket-name',
    Key: 'example-file.jpg',
    Body: fileContent
  };

  s3.upload(params, (err, data) => {
    if (err) {
      throw err;
    }
    console.log(`File uploaded successfully. ${data.Location}`);
  });
};

uploadFile('example-file.jpg');

This code uses the fs module to read the contents of a file and the s3.upload method to upload it to the S3 bucket. You need to replace the your-bucket-name value in the params object with the name of your S3 bucket.

Retrieving a File from S3

To retrieve a file from your S3 bucket, you can use the AWS SDK’s getObject method. Here’s an example code snippet:

const AWS = require('aws-sdk');

const s3 = new AWS.S3();

const getFile = () => {
  const params = {
    Bucket: 'your-bucket-name',
    Key: 'example-file.jpg'
  };

  s3.getObject(params, (err, data) => {
    if (err) {
      throw err;
    }
    console.log(`File retrieved successfully. ${data.Body.toString()}`);
  });
};

getFile();

This code uses the s3.getObject method to retrieve the contents of a file from the S3 bucket. You need to replace the your-bucket-name value in the params object with the name of your S3 bucket.

Deleting a File from S3

To delete a file from your S3 bucket, you can use the AWS SDK’s deleteObject method. Here’s an example code snippet:

const AWS = require('aws-sdk');

const s3 = new AWS.S3();

const deleteFile = () => {
  const params = {
    Bucket: 'your-bucket-name',
    Key: 'example-file.jpg'
  };

  s3.deleteObject(params, (err, data) => {
    if (err) {
      throw err;
    }
    console.log(`File deleted successfully. ${data}`);
  });
};

deleteFile();

This code uses the s3.deleteObject method to delete a file from the S3 bucket. You need to replace the your-bucket-name value in the params object with the name of your S3 bucket.

Enabling CORS for S3

If you want to allow cross-origin resource sharing (CORS) for your S3 bucket, you need to configure CORS rules. Follow these steps to configure CORS rules for your S3 bucket:

  1. Log in to the AWS Management Console.
  2. Navigate to the S3 service.
  3. Click on the name of your bucket.
  4. Click on the “Permissions” tab.
  5. Click on the “CORS configuration” button.
  6. Add the following XML code to the editor:
<CORSConfiguration>
  <CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
  </CORSRule>
</CORSConfiguration>

Conclusion

Using S3 in your Node.js project can be a great way to store and manage your files. It provides you with a scalable and reliable way to store and retrieve data, and it can help you reduce your infrastructure costs.

Follow Us on
https://www.linkedin.com/company/scribblers-den/
https://www.facebook.com/scribblersden.blogs

Read More
https://scribblersden.com/how-to-configue-s3-bucket/

Thank You

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *