50 lines
1.4 KiB
JavaScript
50 lines
1.4 KiB
JavaScript
import AWS from 'aws-sdk';
|
|
import { Buffer } from 'node:buffer';
|
|
|
|
|
|
class AWSUtil {
|
|
constructor() {
|
|
this.s3 = new AWS.S3({
|
|
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
|
|
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
|
|
});
|
|
}
|
|
|
|
async uploadFile(base64, folder, ACL = "public-read") {
|
|
const base64Data = Buffer.from(base64.replace(/^data:image\/\w+;base64,/, ""), 'base64');
|
|
const type = base64.split(';')[0].split('/')[1];
|
|
const userId = 1;
|
|
const params = {
|
|
Bucket: process.env.AWS_S3_BUCKET,
|
|
Key: `${userId}.${type}`,
|
|
Body: base64Data,
|
|
ACL,
|
|
ContentEncoding: 'base64', // required
|
|
ContentType: `image/${type}` // required
|
|
}
|
|
|
|
let location = '';
|
|
let key = '';
|
|
try {
|
|
const { Location, Key } = await this.s3.upload(params).promise();
|
|
location = Location;
|
|
key = Key;
|
|
} catch (error) {
|
|
console.log(error);
|
|
}
|
|
return {location, 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; |