Last updated on July 18, 2023
To upload files to an AWS S3 bucket using Node.js in an Express.js application, you can utilize the AWS SDK for JavaScript.
Here’s a step-by-step guide on how to achieve this
Install the aws-sdk
package:
npm install aws-sdk
Require the aws-sdk
module and configure it with your AWS credentials
const AWS = require('aws-sdk');
AWS.config.update({
accessKeyId: 'YOUR_ACCESS_KEY',
secretAccessKey: 'YOUR_SECRET_ACCESS_KEY'
});
Make sure to replace 'YOUR_ACCESS_KEY'
and 'YOUR_SECRET_ACCESS_KEY'
with your actual AWS access key and secret access key. You can obtain these credentials from your AWS account.
Create an instance of the S3 service:
const s3 = new AWS.S3();
Define a route in your Express.js application to handle file uploads
const express = require('express');
const multer = require('multer'); // Middleware for handling file uploads
const upload = multer({ dest: 'uploads/' }); // Destination folder for uploaded files
const app = express();
app.post('/upload', upload.single('file'), (req, res) => {
const file = req.file;
// Set up the S3 upload parameters
const uploadParams = {
Bucket: 'YOUR_BUCKET_NAME',
Key: file.originalname,
Body: file.buffer
};
// Upload the file to the S3 bucket
s3.upload(uploadParams, (err, data) => {
if (err) {
console.error('Error uploading file:', err);
res.status(500).send('Error uploading file');
} else {
console.log('File uploaded successfully:', data.Location);
res.send('File uploaded successfully');
}
});
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, the route /upload
handles the file upload. It expects a single file with the field name 'file'
. The uploaded file is stored in the uploads/
folder temporarily using the multer
middleware.
Inside the route handler, an S3 upload parameters object is created with the bucket name, file key (name), and the file’s buffer (contents). The s3.upload
method is used to upload the file to the specified S3 bucket. If the upload is successful, the file’s location is logged, and a success response is sent. Otherwise, an error message is logged, and an error response is sent.
Make sure to replace 'YOUR_BUCKET_NAME'
with the name of your target S3 bucket.
Remember to properly secure your AWS credentials and consider implementing additional security measures, such as using IAM roles or setting up fine-grained access control on your S3 bucket, to ensure the security of your application and AWS resources.