Categories
JavaScript Answers

How to upload a file to Amazon S3 with Node.js?

Spread the love

Sometimes, we want to upload a file to Amazon S3 with Node.js.

In this article, we’ll look at how to upload a file to Amazon S3 with Node.js.

How to upload a file to Amazon S3 with Node.js?

To upload a file to Amazon S3 with Node.js, we can use the putObject method.

For instance, we write

const AWS = require('aws-sdk');
AWS.config.update({
  accessKeyId: 'accessKeyId',
  secretAccessKey: 'secretAccessKey',
  region: 'region'
});

const upload = async () => {
  const params = {
    Bucket: "yourBucketName",
    Key: 'someUniqueKey',
    Body: 'someFile'
  };
  try {
    let uploadPromise = await new AWS.S3().putObject(params).promise();
    console.log("Successfully uploaded data to bucket");
  } catch (e) {
    console.log(e);
  }
}

to define the upload function that calls putObject with the params object to upload the file that’s set as the value of Body.

We set the Bucket and Key to set the bucket and key that we use to access the uploaded file.

And then we call promise to return a promise that resolves when the upload is done.

Conclusion

To upload a file to Amazon S3 with Node.js, we can use the putObject method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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