2025-10-26 09:11:04 +08:00

53 lines
1.2 KiB
TypeScript

import { S3Client, PutObjectCommand, DeleteObjectCommand } from '@aws-sdk/client-s3'
const s3Client = new S3Client({
endpoint: process.env.S3_ENDPOINT,
region: process.env.S3_REGION || 'us-east-1',
credentials: {
accessKeyId: process.env.S3_ACCESS_KEY_ID!,
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY!,
},
forcePathStyle: true, // MinIO requires path-style
})
export async function uploadToS3(
file: Buffer,
fileName: string,
contentType: string
): Promise<string> {
const key = `${process.env.S3_FILE_PATH || ''}${fileName}`
const command = new PutObjectCommand({
Bucket: process.env.S3_BUCKET!,
Key: key,
Body: file,
ContentType: contentType,
ACL: 'public-read',
})
await s3Client.send(command)
return `${process.env.S3_PUBLIC_DOMAIN}/${key}`
}
export async function deleteFromS3(fileUrl: string): Promise<void> {
try {
// Extract key from URL
const url = new URL(fileUrl)
const key = url.pathname.slice(1) // Remove leading slash
const command = new DeleteObjectCommand({
Bucket: process.env.S3_BUCKET!,
Key: key,
})
await s3Client.send(command)
} catch (error) {
console.error('Error deleting from S3:', error)
throw error
}
}
export { s3Client }