AWS-SDK S3 파일 삭제
1. 개요
파일 업로드, 다운로드에 대해서는 Presigned url을 이용 하여 클라이언트 단에서 처리가 가능하지만 삭제는 Presigned url이 지원 안되서 aws-sdk로 직접 처리해야한다. 또한 디렉토리를 통째로 비우거나 하는 경우에는 파일 리스트들 먼저 조회하여 해당 파일들의 Key들을 통해서 삭제해야한다.
2. 진행순서
다음과 같은 순서로 진행하였다.
- 특정 Path의 디렉토리 Clear 요청
- 해당 Path의 파일 리스트 조회
- 조회된 파일들의 Key (S3에서의 Path) 추출
- 추출한 Key 배열을 DeleteObjectsCommand 로 넘겨주고 삭제
AWS-SDK 에 DeleteObjectCommand (단일파일 Key 이용) 와 DeleteObjectsCommand (다수파일 삭제가능) 으로 두가지가 있다.
3. 코드
// 미리 REGION, SECRET등을 구성해둔 S3 client
import s3Client from "lib/s3Client";
let { filePath } = req.body;
if (!filePath) {
throw "No file path";
}
filePath = path.join(filePath);
// windows 환경일시
filePath = (filePath as string).replaceAll("\\", "/");
// 해당 Path의 파일 리스트 가져오기
const listParams = {
Bucket: process.env.S3_BUCKET_NAME,
Prefix: filePath,
};
const fileList = await s3Client.send(new ListObjectsCommand(listParams));
console.log(`S3 delete requested path info : ${filePath}`);
// Path에 파일이 없을 경우가 있으므로 처리한다
if (Array.isArray(fileList.Contents) && fileList.Contents.length > 0) {
const deleteObjectCommand = new DeleteObjectsCommand({
Bucket: process.env.S3_BUCKET_NAME,
Delete: {
Objects: fileList.Contents.map((v) => {
return { Key: v.Key };
}),
},
});
const result = await s3Client.send(deleteObjectCommand);
console.log(`Delete request result: ${JSON.stringify(result, null, "\t")}`);
} else {
console.log(`No files to delete`);
}