How to upload a file to Amazon S3
To upload a file to Amazon S3 in Node.js, you can use the aws-sdk
library, which provides a simple API for interacting with the Amazon S3 service.
Here's an example of how you can use aws-sdk
to upload a file to an S3 bucket:
Copy codeconst AWS = require('aws-sdk');
// Configure the AWS SDK with your AWS access key ID and secret access key
AWS.config.update({
accessKeyId: "YOUR_ACCESS_KEY_ID",
secretAccessKey: "YOUR_SECRET_ACCESS_KEY"
});
// Create an S3 client
const s3 = new AWS.S3();
// Set the name of the bucket and the file to be uploaded
const bucketName = "my-bucket";
const fileName = "file.txt";
// Read the contents of the file into a buffer
const fileBuffer = fs.readFileSync(fileName);
// Use the s3.upload function to upload the file to the bucket
s3.upload({
Bucket: bucketName,
Key: fileName,
Body: fileBuffer,
}, (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(`File uploaded to ${data.Location}`);
});
This code configures the AWS SDK with your AWS access key ID and secret access key, creates an S3 client, reads the contents of the file into a buffer, and uses the s3.upload
function to upload the file to the bucket specified by the bucketName
variable. The err
and data
arguments of the callback function are used to check for errors and log the location of the uploaded file.
You can also use the s3.putObject
function to upload a file to an S3 bucket. This function allows you to set additional options, such as the content type and metadata of the object.
I hope this helps! Let me know if you have any questions.