Skip to content

Instantly share code, notes, and snippets.

@toluolatubosun
Created June 15, 2022 12:58
Show Gist options
  • Save toluolatubosun/32b1a7b55346cba2ed3bea32e7b5e320 to your computer and use it in GitHub Desktop.
Save toluolatubosun/32b1a7b55346cba2ed3bea32e7b5e320 to your computer and use it in GitHub Desktop.
AWS File Upload
const AWS = require("aws-sdk");
const { nanoid } = require("nanoid");
const { AWS_S3_BUCKET, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY } = require("./config");
class AWSUtil {
constructor() {
this.s3 = new AWS.S3({
accessKeyId: AWS_ACCESS_KEY_ID,
secretAccessKey: AWS_SECRET_ACCESS_KEY
});
}
async uploadFile(file, folder, ACL = "public-read") {
const params = {
Bucket: AWS_S3_BUCKET,
Key: `${folder}/${nanoid()}.${file.originalname.split(".").pop()}`,
Body: file.buffer,
ContentType: file.mimetype,
ACL
};
const data = await this.s3.upload(params).promise();
return data.Location;
}
async deleteFile(Location) {
const params = {
Bucket: AWS_S3_BUCKET,
Key: Location.split("s3.amazonaws.com/").pop()
};
const data = await this.s3.deleteObject(params).promise();
return data;
}
}
module.exports = new AWSUtil();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment