React 프로젝트에 s3 버킷을 사용해서 이미지를 불러올려고한다.
s3 버킷 정책 설정과 버킷 생성 후 과정이다.
npm install @aws-sdk/client-s3
는
S3 서비스에만 특화된 클라이언트를 설치하여 AWS SDK v3의 모듈화된 접근 방식을 따르며, S3와 관련된 기능만 필요할 때 효율적입니다.
ASW IAM 이동 후 대시보드에서 사용자를 생성해줍니다.
그 후 생성한 사용자를 클릭하여 보안 자격 증명 탭을 누른 후 아래에 있는 액세스 키를 생성해서 거기에 있는 액세스 키와 시크릿 키를 발급 받고
(저는 vite를 사용했기 때문에)
VITE_APP_AWS_ACCESS_KEY_ID=
VITE_APP_AWS_SECRET_ACCESS_KEY=
형식으로 .env파일에 작성해줬습니다.
(이 과정에서 사용자 탭에서 권한 설정을 추가해줬습니다. AmazonS3FullAccess)
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
// S3에서 가져올 이미지 이름
const imageNames = useMemo(
() => [
"goodsno_maintopnew_202309051403431.jpg",
"goodsno_maintopnew_202309141930171.jpg",
],
[]
);
// S3 객체 생성
const s3 = useMemo(() => {
return new S3Client({
region: "ap-northeast-2",
credentials: {
accessKeyId: import.meta.env.VITE_APP_AWS_ACCESS_KEY_ID,
secretAccessKey: import.meta.env.VITE_APP_AWS_SECRET_ACCESS_KEY,
},
});
}, []);
// 이미지 불러오기
useEffect(() => {
const fetchImagesFromS3 = async () => {
const imageUrls: string[] = await Promise.all(
imageNames.map(async (imageName) => {
try {
const params = {
Bucket: "fe-fordogs-image-bucket",
Key: imageName,
};
const command = new GetObjectCommand(params);
await s3.send(command);
const imageUrl = `https://${params.Bucket}.s3.ap-northeast-2.amazonaws.com/${params.Key}`;
return imageUrl;
} catch (error) {
console.error("S3에서 이미지 가져오기 오류:", error);
return "";
}
})
);
setImageURLs(imageUrls);
};
fetchImagesFromS3();
}, [imageNames, s3]);
이렇게 작성해주니 이미지가 url 형식으로 로딩되었습니다.