Created
June 15, 2022 12:58
-
-
Save toluolatubosun/32b1a7b55346cba2ed3bea32e7b5e320 to your computer and use it in GitHub Desktop.
AWS File Upload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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