const { S3Client, DeleteObjectCommand } = require('@aws-sdk/client-s3');
const multer = require('multer')
const multerS3 = require('multer-s3')
require('dotenv').config()
// S3 지역 및 인증 수단 변경
const s3 = new S3Client({
region: process.env.AWS_REGION,
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
},
});
// S3 버킷 이미지 삭제 함수
async function deleteImageFromS3( imageKey ) {
const params = {
Bucket: 'hapoomimagebucket', // 버킷 이름
Key: imageKey, // 삭제할 이미지의 키 'images/1691343931840_multer.png'
};
try {
const command = new DeleteObjectCommand(params);
await s3.send(command);
console.log(`S3에서 이미지 삭제 완료: ${imageKey}`);
} catch (error) {
console.error('S3 이미지 삭제 중 오류 발생:', error);
}
}
module.exports = deleteImageFromS3
const aws = require('aws-sdk');
const multer = require('multer');
const multerS3 = require('multer-s3-transform');
const sharp = require('sharp');
require('dotenv').config();
const express = require('express');
const app = express();
const path = require('path');
const PORT = 2023;
const s3 = new aws.S3({
region: process.env.AWS_REGION,
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
},
});
const fieldsMulterMiddleware = multer({
storage: multerS3({
s3: s3,
bucket: 'hapoomimagebucket',
contentType: multerS3.AUTO_CONTENT_TYPE,
acl: 'public-read',
// shouldTransform: true
// : 업로드된 파일에 대해 변환 작업을 수행헤야 함을 나타낸다.
shouldTransform: true,
transforms: [
{
// multer-s3-transform 라이브러리 내에서 변환 작업을 식별하기 위한 고유한 식별자
id: 'resized', // 아무 텍스트나 와도 된다.
key: function (req, file, cb) { // cb = callback
const ext = path.extname(file.originalname); // 확장자
const filename = path.basename(file.originalname, ext) // 확장자 제외, 파일이름
cb(null, `images/${Date.now().toString()}_${filename}.jpeg`);
},
transform: function (req, file, cb) {
cb(null,
// file.buffer
// : multer-s3-transform 라이브러리가 업로드된 파일을 처리한 결과로써 생성한 버퍼다.
sharp(file.buffer)
.resize(100)
.toFormat('jpeg') // 어느 이미지 파일이든 jpeg로 변환한다 명시하고 있다.
);
},
},
],
}),
limits: { fileSize: 5 * 1024 * 1024 },
});
// delete 함수
function deleteS3(imageUrl) {
const params = {
Bucket: 'hapoomimagebucket',
Key: imageUrl
}
s3.deleteObject(params, (err, data) => {
if(err) {
console.log('이미지 삭제 실패', err)
} else {
console.log('이미지 삭제 성공', data)
}
})
};
app.get('/upload', (req, res) => {
res.sendFile(path.join(__dirname, 'multipart.html'));
});
app.post('/upload', fieldsMulterMiddleware.single('image'), (req, res) => {
console.log(req.file);
res.send('ok');
});
app.listen(PORT, () => {
console.log(`${PORT} 포트에서 서버가 실행되었습니다!`);
});
module.exports = deleteS3
const images = await Images.findAll({ where: { postId: post.postId } });
const s3DeletePromises = images.map((image) => {
const imagePath = new URL(image.dataValues.url).pathname.substr(1)
return deleteS3(imagePath)
})
await Promise.all(s3DeletePromises)
URL
URL 객체는 JS 내장 객체 중 하나로, URL 문자열을 다루기 위한 여러 메서드와 속성을 제공한다.
URL을 파싱하고 조작하는데 사용되며 URL 객체를 생성할 때, URL 문자열을 전달하여
URL의 구성 요소에 접근할 수 있다.
pathname