This document provides a script to upload images from a local folder to an Amazon S3 bucket. The script uses NodeJs with the AWS SDK, fs
, path
, and sharp
libraries. It configures AWS S3 credentials, reads images from a specified directory, compresses them using sharp
, and uploads them to a specified S3 bucket with public-read-write permissions. The script processes only .jpg
, .jpeg
, and .png
files (configurable).
const fs = require('fs')
const path = require('path')
const AWS = require('aws-sdk')
const sharp = require('sharp')
// Configure AWS SDK
// AWS.config.update({ region: 'YOUR_REGION' }) (OPTIONAL)
const s3 = new AWS.S3({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_ACCESS_KEY_SECRET,
})
// Directory containing images
const imageDir = path.join(__dirname, 'YOUR_FOLDER_PATH')
// S3 bucket name
const BUCKET_NAME = 'YOUR_BUCKET_NAME'
// Function to get the file size
const getFileSize = (filePath) => {
return new Promise((resolve, reject) => {
fs.stat(filePath, (err, stats) => {
if (err) {
reject(err)
} else {
resolve(stats.size)
}
})
})
}
// Function to compress and upload an image
const compressAndUpload = async (fileName) => {
try {
const file = path.join(imageDir, fileName)
const fileExtension = path.extname(file).slice(1)
const originalSize = await getFileSize(file)
let compressedFile = await sharp(file)
.toFormat(fileExtension, { quality: 50% })
.toBuffer()
const uploadParams = {
Bucket: BUCKET_NAME,
Key: `FOLDER/${fileName}`,
Body: compressedFile, // Should be a file buffer
ContentType: 'image/jpeg',
ACL: 'public-read-write', // defining the permissions to get the public link
}
const result = await s3.upload(uploadParams).promise()
console.log(`Uploaded ${fileName} to ${result.Location}`)
} catch (error) {
console.error(`Error compressing or uploading ${fileName}:`, error)
}
}
// Function to process all images in the folder
const processImages = async () => {
fs.readdir(imageDir, async (err, files) => {
if (err) {
console.error('Error reading directory:', err)
return
}
for (const file of files) {
const ext = path.extname(file).toLowerCase()
if (['.jpg', '.jpeg', '.png'].includes(ext)) {
await compressAndUpload(file)
}
}
})
}
// Start processing images
processImages()