This utility provides functions for uploading and deleting images to and from an Amazon S3 bucket using the AWS SDK for JavaScript.
-
Install dependencies:
npm install @aws-sdk/client-s3
BUCKET=your-bucket-name
AWS_ACCESS_KEY_ID=your-access-key-id
AWS_SECRET_ACCESS_KEY=your-secret-access-key
imageUpload.ts
is a utility file that provides functions for uploading and deleting images to and from an Amazon S3 bucket using the AWS SDK for JavaScript.
import { S3Client, PutObjectCommand, DeleteObjectCommand } from "@aws-sdk/client-s3";
const Bucket = process.env.BUCKET;
const s3 = new S3Client({
region: 'us-east-2',
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID as string,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY as string,
},
});
const uploadImgToAWS = async (file: any, folder: string) => {
try {
if (!file || file.size === 0) {
throw new Error('Invalid file');
}
const Body = (await file.arrayBuffer()) as Buffer;
const ACL = 'public-read';
const key = `${folder}${Date.now()}${file.name}`;
const ContentType = file.type || 'application/octet-stream';
await s3.send(new PutObjectCommand({ Bucket, Key: key, Body, ACL, ContentType }));
const url = `https://${Bucket}.s3.amazonaws.com/${key}`;
return { url, key };
} catch (error) {
console.log(error);
throw error;
}
};
const deleteImgFromAWS = async (key: string) => {
try {
await s3.send(new DeleteObjectCommand({ Bucket, Key: key }));
console.log(`Successfully deleted object with key: ${key}`);
} catch (error) {
console.error(`Error deleting object with key ${key}:`, error);
throw error;
}
};
export {
uploadImgToAWS,
deleteImgFromAWS,
};
// Example usage for uploading an image
const res = await uploadImgToAWS(img, 'e3global/blog/');
console.log(`Image uploaded successfully. Key: ${res.key}`);
console.log(`Image URL: ${res.url}`);
await deleteImgFromAWS('Your Key');
console.log(`Image deleted successfully.`);
Feel free to contribute to this project by creating issues or submitting pull requests.
This project is licensed under the MIT License.