JavaScript에서 AWS 사용방법
1. AWS S3 설정 변경
- S3 버킷 클릭 -> 권한탭 -> CORS 구성 클릭 후 하단 코드 추가
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<AllowedMethod>HEAD</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
2. JavaScript
- <script src="https://sdk.amazonaws.com/js/aws-sdk-2.283.1.min.js"></script> 추가
- 기본 AWS 세팅 코드 추가
...
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.283.1.min.js"></script>
...
<script>
...
var albumBucketName = '버킷명';
var bucketRegion = '리전명 예 : ap-northeast-2';
var IdentityPoolId = 'pool-id';
AWS.config.update({
region: bucketRegion,
credentials: new AWS.CognitoIdentityCredentials({
IdentityPoolId: IdentityPoolId
})
});
var s3 = new AWS.S3({
apiVersion: '2006-03-01',
params: {Bucket: albumBucketName}
});
...
</script>
2.1. 항목 업로드
- 서브 경로명 입력시, 없다면 자동으로 생성됨.
- blob의 url을 바로 사용할 수 없고, file로 변환 후 file을 업로드 해야함.
- 예 :
//이 예제에선 blob을 사용한 url을 업로드함
function uploadToAWS(blob, fileName)
{
var albumPhotosKey = encodeURIComponent('서브경로명') + '/';
var photoKey = albumPhotosKey + fileName;
var file = new File([blob],fileName);
s3.upload({
Key: photoKey,
Body: file,
ACL: 'public-read'
}, function(err, data) {
if (err) {
return alert('There was an error uploading : ', err.message);
}
alert('Successfully uploaded photo.');
});
}
2.2. PresignedURL
- private 의 항목을 임시 url 생성 (타임아웃 지정)
- access key, secret key 관련 참조 : https://mintpot.synology.me:30000/boards/2/topics/195
- 예 :
var bucketName = '버킷명칭';
var bucketRegion = 'ap-northeast-2'; //리전
AWS.config.update({
region: bucketRegion,
credentials: {
accessKeyId: '', //access key
secretAccessKey: // secret access key
}
});
const s3 = new AWS.S3({
apiVersion: '2006-03-01',
params: {Bucket: bucketName, signatureVersion: 'v4' }
});
function GetURL()
{
var params = {Bucket: bucketName , Key: "파일 위치(버킷명 이후경로)", Expires: 60};
var url = s3.getSignedUrl('getObject', params);
console.log('The URL is', url);
return url;
}
'FrontEnd' 카테고리의 다른 글
vue js 내용정리 (1. 설치 ~ 2.3.8. 컴포넌트 - 이벤트 발생시 사용자 정의함수 호출) (0) | 2022.03.25 |
---|---|
FrontEnd 개발 관련 내용정리 (0) | 2022.03.25 |
HTTPS 상에서 Front-end 페이지 테스트 (0) | 2022.03.24 |
FrontEnd 개발 관련 내용정리 (개인) (0) | 2022.03.24 |
JQuery 관련 기초 내용 (0) | 2022.03.24 |