
Frontend에서 S3 버킷에 파일을 업로드 하는 것을 알아보겠습니다.
다음은 이 글의 동영상 강좌입니다.
slider-front 프로젝트를 열고 admin 페이지를 생성합니다.
내용은 index.vue를 복사하여 만듭니다.
/pages/admin/index.vue
<template>
  <div>
    <div>관리자 페이지</div>
  </div>
</template>
<script>
export default {
  name: 'IndexPage',
  computed: {
    accessToken() {
      return this.$store.state.accessToken
    }
  }
}
</script>관리자 메뉴 링크 클릭시 위 페이지로 이동하도록 아래와 같이 변경합니다.
/layouts/default.vue
async admin() {
  await this.$router.replace('/admin/');
}
관리자 메뉴의 링크가 잘 작동하는지 테스트를 합니다.
dotenv와 aws-sdk 패키지를 추가합니다.
yarn add @nuxtjs/dotenv dotenv aws-sdkaws 설정을 위해 plugins 폴더를 추가하고 env-var.js 파일을 아래와 같이 추가합니다.
export default ({
    app, context
}, inject) => {
    const env = {}
    env.S3_BUCKET = 'codegear-slider-bucket'; //버킷명 입력
    env.S3_REGION = 'ap-northeast-2'; //리전명 입력
    env.S3_IDENTITY_POOL_ID = '설정한 IDENTITY_POOL_ID값 입력';
    inject('env', env)
}
파일 업로드를 위해 Bootstrap-Vue의 Form File Component를 추가합니다.
https://bootstrap-vue.org/docs/components/form-file
BootstrapVue
Quickly integrate Bootstrap v4 components with Vue.js
bootstrap-vue.org
Admin 페이지를 다음과 같이 수정합니다.
/admin/index.vue
<template>
    <div>
        <b-form-file
            ref="file-input"
            v-model="file1"
            :state="Boolean(file1)"
            placeholder="Choose a file or drop it here..."
            drop-placeholder="Drop file here..."
            accept="image/*"
        ></b-form-file>
        <div class="mt-3">Selected file: {{ file1 ? file1.name : '' }}</div>
        <b-button @click="clearFiles" class="mr-2">Reset</b-button>
        <b-button @click="upload" class="mr-1">Upload</b-button>
    </div>
</template>
<script>
import AWS from 'aws-sdk';
export default {
    name: 'IndexPage',
    data() {
        return {
            file1: null,
            bucketName: this.$env.S3_BUCKET,
            bucketRegion: this.$env.S3_REGION,
            IdentityPoolId: this.$env.S3_IDENTITY_POOL_ID,
        }
    },
    computed: {
        accessToken() {
            return this.$store.state.accessToken;
        }
    },
    methods: {
        clearFiles() {
            this.$refs['file-input'].reset()
        },
        async upload() {
            if(!this.file1) {
                alert('File을 선택해주세요.')
            }else{
                console.log(this.file1);
                console.log(`${this.bucketRegion} ${this.bucketName}`);
                AWS.config.region = this.bucketRegion;
                AWS.config.credentials = new AWS.CognitoIdentityCredentials({
                    IdentityPoolId: this.IdentityPoolId,
                });
                const s3 = new AWS.S3({
                    apiVersion: '2006-03-01',
                    params: {
                        Bucket: this.bucketName+'/images'
                    }
                });
                await s3.upload({
                    ACL: 'public-read',
                    Body: this.file1,
                    Key: this.file1.name
                }, (error)=>{
                    if(error){
                        this.errorHandler(error);
                        // return alert('There was an error uploading your photo: ', error.message);
                    }
                }).promise().then((data)=>{
                    console.log('File uploaded!!!')
                    console.log(data);
                })
            };
        },
    }
}
</script>파일 업로드 테스트를 해봅니다.

위와 같이 정상적으로 업로드가 안되고 AccessDenied가 나올 경우,
AWS의 IAM - 역할 메뉴에서 다음 항목을 검색합니다.
Cognito_SliderS3AccessUnauth_Role
해당항목을 클릭하고 들어가면,
아래와 같은 정책 이름이 보입니다.

"oneClick_Cognito_SliderS3AccessUnauth_Role_..." 항목을 클릭합니다.
JSON을 선택하여 아래와 같이 작성 후 정책 검토를 한 후 저장합니다.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:*"
            ],
            "Resource": [
                "arn:aws:s3:::codegear-slider-bucket/*",
                "arn:aws:s3:::codegear-slider-bucket"
            ]
        }
    ]
}
'Nestjs 활용 동영상강좌' 카테고리의 다른 글
| Nestjs 프로젝트를 Docker로 배포하기 (2) | 2022.12.30 | 
|---|---|
| (풀스택) Node(Nest)와 Vue(Nuxt)로 사이트 만들기 - 12.이미지 슬라이드 개발 (0) | 2022.12.20 | 
| (풀스택) Node(Nest)와 Vue(Nuxt)로 사이트 만들기 - 11.이미지 조회 및 삭제 (0) | 2022.12.18 | 
| (풀스택) Node(Nest)와 Vue(Nuxt)로 사이트 만들기 - 10.업로드 파일 DB 저장 (0) | 2022.12.11 | 
| (풀스택) Node(Nest)와 Vue(Nuxt)로 사이트 만들기 - 08.AWS S3 설정 (0) | 2022.10.22 | 
| (풀스택) Node(Nest)와 Vue(Nuxt)로 사이트 만들기 - 07.사용자 권한 관리 (0) | 2022.10.15 | 
| (풀스택) Node(Nest)와 Vue(Nuxt)로 사이트 만들기 - 06.Front 로그인 (with Jwt Token) (0) | 2022.10.03 | 
| (풀스택) Node(Nest)와 Vue(Nuxt)로 사이트 만들기 - 05.JWT인증 (0) | 2022.10.01 |