In this article, Im going to discuss about how to upload an image to AWS S3, the cloud file hosting solution provided by Amazon Web Services.
First install the aws-sdk library.
npm install aws-sdk
Then ,import it to the code, at the top of the file that going to add this file upload to s3 functionality:
import AWS from ’aws-idk’
Now, use the sdk to create an instance of the s3 object. Let’s assign it to a s3 variable.
const s3 = new AWS.S3({
accessKeyId : process.env.AWS_S3_ACCESS_KEY_ID,
secretAccessKet: process.env.AWS_S3_SECRET_ACESS_KEY,
})
Here used two environment variables here:
- AWS_S3_ACCESS_KEY_ID
- AWS_S3_SECRET_ACESS_KEY
Now comes some “administrative works” to do. For that you need to create an IAM profile on AWS (the credentials) with programmatic access with the permissions for AWSCloudFormationFullAccess and AmazonS3FullAccess and an S3 bucket that this user has access to.
Now you need an image blog to upload.
Here you can use the below URL:
const imageURL = ’https://url-to-image.jpg'
const res = await fetch(imageURL)
const blob = await res.buffer()
Or you can get an image sent from a form image field in a multipart form:
const imagePath = req.files[0].path
const blob = fs.readFileSync(imagePath)
Finally, make a call to s3.upload() and call its .promise() method so you can use await to wait until it finishes to get the uploaded files object:
const uploadedImage = await s3.upload({
Bucket: process.env.AWS_S3_Bucket_NAME,
Key: req.files[0].originalFilename,
Body: blod,
}).promise()
AWS_S3_BUCKET_NAME is the name of the S3 bucket , another environment variable.
Finally , you can get the URL of the uploaded image on S3 by referencing the Location property:
uploadedImage.Location
You have to make sure that you set the S3 bucket as public so you can access that image URL.
Top comments (0)