본문 바로가기

서버

aws ec2) 이미지 업로드를 위해 s3와 연동

728x90

1. IAM 사용자 추가

2. spring boot에서 설정

3. 이미지 업로드 테스트

 


1. IAM 사용자추가

 

aws console > IAM 사용자 생성

이동 후

 

 

 

 

 

생성이 되면

accesskey, secretkey를 

나만 보도록 저장해야된다. 

생성한 이후로 다시 볼 수 없으니 꼭 어딘가에 기록해야함

 

 

 

 


2. spring boot에서 설정

 

2-1 pom.xml 에서 

spring-cloud-starter-aws 패키지 추가

 

		<dependency>
		    <groupId>org.springframework.cloud</groupId>
		    <artifactId>spring-cloud-starter-aws</artifactId>
		    <version>2.2.1.RELEASE</version>
		</dependency>

 

 

 

2-2 S3Config.java 파일 s3연동 configuration 파일 생성

 

package com.newlecture.web;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;

@Configuration
public class S3Config {
	
    @Value("${cloud.aws.credentials.access-key}")
    private String iamAccessKey;
    
    @Value("${cloud.aws.credentials.secret-key}")
    private String iamSecretKey;
    
    @Value("${cloud.aws.region.static}")
    private String region;
    
    @Bean
    public AmazonS3Client amazonS3Client(){
        BasicAWSCredentials awsCredentials = new BasicAWSCredentials(iamAccessKey, iamSecretKey);
        return (AmazonS3Client) AmazonS3ClientBuilder.standard()
                .withRegion(region).enablePathStyleAccess()
                .withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
                .build();
    }
}

 

 

2-3. application.properties설정

 

cloud.aws.s3.bucket=버켓값
cloud.aws.region.static=지역값
cloud.aws.region.auto=false
cloud.aws.stack.auto=false
cloud.aws.credentials.access-key=${access_key:test}
cloud.aws.credentials.secret-key=${secret_key:test}

 

버켓값 지역값은 다음 사진으로 확인하면 된다

 

 

 

 

 

 

s3 버켓들어가면

 

us-east2 확인

만약 us-east2라면 

cloud.aws.s3.bucket=버켓값
cloud.aws.region.static=us-east-2
cloud.aws.region.auto=false
cloud.aws.stack.auto=false
cloud.aws.credentials.access-key=${access_key:test}
cloud.aws.credentials.secret-key=${secret_key:test}

 

 

 

2-4 Controller에 이미지 업로드 로직 추가

 

 

다 볼 필요 없고

두 개 메소드만 확인해서 

 

putS3, deleteS3

 

본인 환경에 맞춰서 하면 됨

 

 

	public int uploadFileAws(MultipartFile uploadFile, String param) throws IllegalStateException, IOException {
		Date date = new Date();
		StringBuilder sb = new StringBuilder();

		ObjectMapper mapper = new ObjectMapper();
		BoardEntity bEnt;
		bEnt = mapper.readValue(param, BoardEntity.class);
		
		if (uploadFile != null) {
			String dirPath = System.getProperty("user.home") + "/" + UUID.randomUUID() + uploadFile.getOriginalFilename();
			File convertFile = new File(dirPath);
			uploadFile.transferTo(convertFile);
			
			log.debug("###dirPath >>> " + dirPath);
			
			String fileName = "static/upload" + dirPath;
			putS3(convertFile, fileName);			
			bEnt.setImage_path(fileName);

			// 로컬에 저장해놓은 파일 삭제
			convertFile.delete(); 
		}
		
		int result = bDao.addBoard(bEnt);
		return result;
	}
	
    /**
     * S3로 업로드
     * @param uploadFile : 업로드할 파일
     * @param fileName : 업로드할 파일 이름
     * @return 업로드 경로
     */
    public String putS3(File uploadFile, String fileName) {
        amazonS3Client.putObject(new PutObjectRequest(bucket, fileName, uploadFile).withCannedAcl(
                CannedAccessControlList.PublicRead));
        return amazonS3Client.getUrl(bucket, fileName).toString();
    }
        
    /**
     * S3에 있는 파일 삭제
     * 영어 파일만 삭제 가능 -> 한글 이름 파일은 안됨
     */
    public void deleteS3(String filePath) throws Exception {
        try{
            String key = filePath.substring(56); // 폴더/파일.확장자

            try {
                amazonS3Client.deleteObject(bucket, key);
            } catch (AmazonServiceException e) {
                log.info(e.getErrorMessage());
            }

        } catch (Exception exception) {
            log.info(exception.getMessage());
        }
        log.info("[S3Uploader] : S3에 있는 파일 삭제");
    }

 

이미지 업로드 로직은 다음과 같음

> System.getProperty("user.home")으로 현재 작업중인 디렉토리를 prefix로 두기

> 고유값 추가하기 - UUID.randomUUID();

> 프론트에서 formData형식으로 받은 파일에서 originalFile이름가져오기

 

> ↑위 세개 값으로 빈 껍데기 파일을 만듬 (File convertFile = new File(디렉토리);)

 

> 만들어놓은 빈 껍데기 파일에 byte값을 밀어 넣음(uploadFile.transferTo(convertFile)

> 바이트값 들어있는 파일, 저장할 경로 두개의 파라미터를 putS3 메소드에 넣음

 

> s3에 넣었으니 ec2에 있는 바이트값 들어있는 이미지파일을 삭제 (convertFile.delete())