53 lines
1.5 KiB
JavaScript
53 lines
1.5 KiB
JavaScript
import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
|
|
import { Buffer } from 'node:buffer';
|
|
import { v4 as uuidv4 } from 'uuid';
|
|
|
|
class AWSUtil {
|
|
constructor() {
|
|
this.s3 = new S3Client({ region: "us-east-2" });
|
|
}
|
|
|
|
async uploadFile(base64, ACL = "public-read") {
|
|
const base64Data = Buffer.from(base64.replace(/^data:image\/\w+;base64,/, ""), 'base64');
|
|
const type = base64.split(';')[0].split('/')[1];
|
|
const uuid = uuidv4();
|
|
|
|
const params = {
|
|
Bucket: process.env.AWS_S3_BUCKET,
|
|
Key: `${uuid}.${type}`,
|
|
Body: base64Data,
|
|
ContentEncoding: 'base64', // required
|
|
ContentType: `image/${type}` // required
|
|
};
|
|
|
|
// Create an object and upload it to the Amazon S3 bucket.
|
|
try {
|
|
const results = await this.s3.send(new PutObjectCommand(params));
|
|
console.log(
|
|
"Successfully created " +
|
|
params.Key +
|
|
" and uploaded it to " +
|
|
params.Bucket +
|
|
"/" +
|
|
params.Key
|
|
);
|
|
} catch (err) {
|
|
console.log("Error", err);
|
|
}
|
|
|
|
return `https://tattletires.s3.us-east-2.amazonaws.com/${params.Key}`
|
|
}
|
|
|
|
async deleteFile(Location) {
|
|
const params = {
|
|
Bucket: process.env.AWS_S3_BUCKET,
|
|
Key: Location.split("s3.amazonaws.com/").pop()
|
|
};
|
|
|
|
const data = await this.s3.deleteObject(params).promise();
|
|
|
|
return data;
|
|
}
|
|
}
|
|
|
|
export default AWSUtil; |