63 lines
1.4 KiB
JavaScript
63 lines
1.4 KiB
JavaScript
|
|
const aws = require('aws-sdk');
|
||
|
|
|
||
|
|
aws.config.update({
|
||
|
|
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
|
||
|
|
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
|
||
|
|
region: process.env.AWS_REGION
|
||
|
|
});
|
||
|
|
|
||
|
|
// Create an S3 instance
|
||
|
|
const s3 = new aws.S3();
|
||
|
|
|
||
|
|
async function uploadFileToS3(fileData, directoryPath, mimetype) {
|
||
|
|
return new Promise((resolve, reject) => {
|
||
|
|
const params = {
|
||
|
|
Bucket: process.env.AWS_BUCKET_NAME,
|
||
|
|
Key: `${directoryPath}`,
|
||
|
|
Body: fileData,
|
||
|
|
ACL: 'public-read',
|
||
|
|
ContentType: mimetype
|
||
|
|
};
|
||
|
|
|
||
|
|
s3.upload(params, (err, data) => {
|
||
|
|
if (err) {
|
||
|
|
console.error("Error uploading to S3:", err);
|
||
|
|
reject(err);
|
||
|
|
} else {
|
||
|
|
console.log("Upload successful:", data.Location);
|
||
|
|
resolve(data.Location);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
async function deleteFileToS3(imageUrl) {
|
||
|
|
try {
|
||
|
|
return new Promise(async (resolve, reject) => {
|
||
|
|
// Extract the key from the imageUrl
|
||
|
|
const key = imageUrl.split('/').slice(3).join('/');
|
||
|
|
|
||
|
|
// Construct parameters for deleteObject operation
|
||
|
|
const deleteParams = {
|
||
|
|
Bucket: process.env.AWS_BUCKET_NAME,
|
||
|
|
Key: key,
|
||
|
|
};
|
||
|
|
|
||
|
|
// Delete the object from S3 bucket
|
||
|
|
await s3.deleteObject(deleteParams).promise();
|
||
|
|
|
||
|
|
resolve();
|
||
|
|
});
|
||
|
|
} catch (error) {
|
||
|
|
console.error("Error occurred while deleting file from S3:", error);
|
||
|
|
resolve();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
module.exports = {
|
||
|
|
uploadFileToS3,
|
||
|
|
deleteFileToS3,
|
||
|
|
s3
|
||
|
|
}
|