React

s3 이미지 업로드하기

sungtt 2022. 5. 3. 07:27

s3는 같은 리전끼리는 전송에 요금이 부과되지않는다고한다.

https://hamait.tistory.com/675

 

s3 버킷 생성하기

 

s3 버킷 정책 편집하기

 

s3 cors 정책 편집하기

 

IAM 액세스키, 보안키 발급

 

yarn add react-s3  설치하기

https://www.npmjs.com/package/react-s3

 

공식 사이트 참고하여 업로드 코드 작성 후 업로드 시도 

ReferenceError: Buffer is not defined 오류 

 

ReferenceError: Buffer is not defined 해결방법

https://stackoverflow.com/questions/69686231/react-s3-error-referenceerror-buffer-is-not-defined

yarn add buffer

app.js에 코드삽입

window.Buffer = window.Buffer || require("buffer").Buffer;

 

CORS정책을 설정했지만 CORS 오류, localhost라 헤더가 없어서 그런듯함.

okky에 질문을 하였다. (쓸모없었음)

 

서버에서는 작동하는지 확인하기위해 aws ec2서버에 배포 후업로드 시도하였지만 CORS 오류가 떴다.

 

우측 상단의 아이디에 가져다대면 나오는 모달창의 보안 자격 증명에서

새로운 액세스키와 보안키를 발급받아 코드를 수정했다. 그래도 안됨

 

버킷정책을 아예 따라썼다.

기존에 생성한 것

//기존 정책
{
	"Version": "2012-10-17",
	"Id": "Policy1651526101250",
	"Statement": [
		{
			"Sid": "Stmt1651526090991",
			"Effect": "Allow",
			"Principal": "*",
			"Action": "s3:GetObject",
			"Resource": "arn:aws:s3:::saemoi/*"
		},
		{
			"Sid": "2",
			"Effect": "Allow",
			"Principal": {
				"AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E3AC5L8UWB28II"
			},
			"Action": "s3:GetObject",
			"Resource": "arn:aws:s3:::saemoi/*"
		}
	]
}
//변경 정책
{
    "Version": "2012-10-17",
    "Id": "Policy1651526101250",
    "Statement": [
        {
            "Sid": "PublicListGet",
            "Effect": "Allow",
            "Principal": "*",
            "Action": [
                "s3:List*",
                "s3:Get*"
            ],
            "Resource": [
                "arn:aws:s3:::saemoi",
                "arn:aws:s3:::saemoi/*"
            ]
        },
        {
            "Sid": "2",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E3AC5L8UWB28II"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::saemoi/*"
        }
    ]
}

 

정책을 변경해도 여전히 로컬에선 CORS다시 서버로 배포해봐도 CORS

 

aws-sdk 모듈로 시도해본다.

yarn add aws-sdk

예시대로 코드 작성하고

can't resolve util 오류 만남

https://stackoverflow.com/questions/64402821/module-not-found-error-cant-resolve-util-in-webpack

yarn add util 로 해결하고

로컬에서 업로드 해봤으나 안됨

서버에 배포해도 CORS

 

액세스키를 깃허브에 올리는 바람에 커밋내역을 삭제함

git reset --hard 커밋번호

git push -f

 

액세스키는 새로 발급함

다시 buffer, util, react-s3 설치

 

ACL에 대해 설정해본다.

https://real-dongsoo7.tistory.com/101

 

[AWS 파헤치기] #4 S3 권한설정 ACL & Bucket Policy

S3 (Simple Storage Service) S3는 Simple Storage Service의 약자이며 AWS에서 제공하는 파일서버입니다. 저는 평소에 생각보다 S3를 사용할 일이 많이 생기더라고요. 도메인과 연결하여 정적 사이트를 제공하

real-dongsoo7.tistory.com

여전히 CORS 403

 

 

지개가 알려준 코드

//변경전 
{
	"Version": "2012-10-17",
	"Id": "Policy1651526101250",
	"Statement": [
		{
			"Sid": "PublicListGet",
			"Effect": "Allow",
			"Principal": "*",
			"Action": [
				"s3:List*",
				"s3:Get*",
				"s3:GetObject*"
			],
			"Resource": [
				"arn:aws:s3:::saemoi",
				"arn:aws:s3:::saemoi/*"
			]
		},
		{
			"Sid": "2",
			"Effect": "Allow",
			"Principal": {
				"AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E3AC5L8UWB28II"
			},
			"Action": "s3:GetObject",
			"Resource": "arn:aws:s3:::saemoi/*"
		}
	]
}


//변경 후
{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "AllowPublicRead",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::S3-Bucket-name/*"
        }
    ]
}

안된다.

 

 

매우 짧은시간의 토큰을 사용해서 시스템타임이 범인일수도 있다는 아래 글을 봄

https://stackoverflow.com/questions/26691286/amazon-s3-bucket-returning-403-forbidden

 

Amazon S3 bucket returning 403 Forbidden

I've recently inherited a Rails app that uses S3 for storage of assets. I have transferred all assets to my S3 bucket with no issues. However, when I alter the app to point to the new bucket I get ...

stackoverflow.com

 

아래를 이용해 서버시간을 한국시간대로 변경함(생각해보니 로컬에선 상관없는 문젠데..)

https://inmile.tistory.com/4

 

[Linux] 리눅스 시간을 한국 표준시(KST)로 변경하기

※ 다음 내용은 Ubuntu 리눅스 기준이며, 다른 배포판의 경우 내용이 다를 수 있다. 리눅스를 설치할 때 Timezone을 설정하지 않으면 UST/PST 등으로 기본 설정되어 한국이 아닌 다른 국가의 시간으로

inmile.tistory.com

 

안됨

 

액세스키를 다시 발급받아서 환경변수에 적용해주니

react-s3, react-aws-s3 , aws-sdk 모두 정상 작동한다!!!

 

애초에 원인이 망한 액세스키였던것일까?

 

s3 업로드는 여기서 끝이다.

삽질을 좀 했지만 차례대로 정리해보자면 

 

1. s3 버킷 생성

2. s3 버킷 정책 편집

3. s3 CORS 정책 편집

4. 액세스 차단 허용 편집

5. s3 ACL 편집 (다 허용하고나서 하나씩 해제해본결과 아래처럼만 체크해도 작동함)

7. 계정에 마우스 올리고 보안 자격 증명 들어가서 액세스키ID/시크릿액세스키 발급받기

(깃 등 유출 시 바로 이메일 날라온다.)

8. react-s3 / react-aws-s3 / aws-sdk 셋 중 택 1설치 (3개 다 정상적으로 작동하지만, 난 react-s3로 진행하였다.) 

9. app에 react-s3 코드 삽입, ( 버킷명,레기온주소,액세스키,시크릿액세스키 환경변수로 설정)

10. 업로드 구현

- 10번에서 오류가 날 시

 10-1. buffer 오류 yarn add buffer하고 코드 추가

 10-2. util 오류 yarn add util 하면 끝

11. 업로드 시작

12. 끝!

 

가장 도움이 된 사이트

https://javascript.plainenglish.io/how-to-upload-files-to-aws-s3-in-react-591e533d615e

 

How to Upload Files to AWS S3 in React

In 2 different ways

javascript.plainenglish.io


 

이제 어떡해야 업로드 시 파일주소를 db에 저장하고, 서버에서 다시 호출해서 state값에 할당할 수 있는지 알아봐야함