AWS

Spring boot , aws S3 버킷에 이미지 업로드

2021. 10. 25. 08:45

 S3 버킷에 이미지를 업로드 할 일이 생겨서 이것저것 찾아보았습니다. 

다른 블로그 분의 게시글을 참고하여 작성하였고 추후에 Rest로 구현해보겠습니다. 

 

* AWS 관련 설정은 생략합니다.

 

0. 가장 먼저 access key, secret key를 발급받습니다.

우측 "내 보안 자격 증명"을 클릭합니다.

 

키를 생성합니다.

 

 

1. 필요한 라이브러리 셋팅

// AWS S3
implementation platform('com.amazonaws:aws-java-sdk-bom:1.11.1000')
implementation 'com.amazonaws:aws-java-sdk-s3'

// html,  렌더링
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

 

2. 파일 업로드 뷰 [ resources/templates/index.html ]

<input type="file" id="file">

<script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossOrigin="anonymous"></script>
<script>
    $(function() {
        $('#file').on('change', function () {
            var formData = new FormData();
            var userImg = $('#file');
            var originalFileName = userImg[0].files[0].name;

            formData.append('userImg', userImg[0].files[0], originalFileName);

            $.ajax({
                type: 'post',
                url: '/apis/upload-img',
                data: formData,
                dataType: 'json',
                processData: false, // 파일 전송할 때는 false(query string을 만들지 않기 위함)
                contentType: false, // default ->  "application/x-www-form-urlencoded; charset=UTF-8", false -> "multipart/form-data"
                error: function (xhr, status, error) {
                    alert('파일 업로드 실패');
                },
                success: function (json) {
                    alert('파일 업로드 성공');
                }
            });
        });
    });
</script>

 

3. application-aws.yml 저장

cloud:
  aws:
    s3:
      bucket: [ 버킷명 - arn 콜론 맨 끝 위치해 있는 이름입니다. ]
    region:
      static: ap-northeast-2
    stack:
      auto: false
    credentials:
      instanceProfile: true # AWS CLI에서 aws configure list 정보 반영 확인 여부
      accessKey: [ access key를 적어줍니다. ]
      secretKey: [ secret key를 적어줍니다. ]

 

4. .gitignore에 application-yml 추가 

application-aws.yml

 

5. application.yml에 프로필 추가

spring:
  profiles:
    include:
      - aws

 

6. Service 코드

@Slf4j
@Service
@RequiredArgsConstructor
public class AwsS3Service {

	@Value("${cloud.aws.credentials.accessKey}")
	private String accessKey;

	@Value("${cloud.aws.credentials.secretKey}")
	private String secretKey;

	@Value("${cloud.aws.s3.bucket}")
	private String bucket;

	private AmazonS3 s3Client;

	// 생성자 생성 이전에 S3 정보를 생성
	@PostConstruct
	public void setS3Client() {
		AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);

		s3Client = AmazonS3ClientBuilder.standard()
			.withCredentials(new AWSStaticCredentialsProvider(credentials))
			.withRegion(Regions.AP_NORTHEAST_2)
			.build();
	}

	// s3 sdk를 이용하여 실제 이미지를 업로드하는 부분
	public String uploadImage(MultipartFile file) {
		String fileName = file.getOriginalFilename();

		try {
			s3Client.putObject(new PutObjectRequest(bucket, fileName, file.getInputStream(), null)
				.withCannedAcl(CannedAccessControlList.PublicRead));
		} catch (IOException e) {
			e.printStackTrace();
		}

		return s3Client.getUrl(bucket, fileName).toString();
	}
}

 

 

7. controller 코드

@Slf4j
@Controller
@RequiredArgsConstructor
public class AwsS3Controller {

	@Autowired
	private final AwsS3Service awsS3Service;

	// >> pt 5. thymeleaf 모듈이 있어야 포워딩 가능
	@GetMapping("/apis/upload")
	public String getMainPage() {
		log.info("log");
		return "index";
	}

	@PostMapping("/apis/upload-img")
	@ResponseBody
	public ResponseEntity<ApiResponseMessage> uploadImage(@RequestParam("userImg") MultipartFile file) {

		String imageUrl = awsS3Service.uploadImage(file);

		if (imageUrl == null) {
			ApiResponseMessage message = new ApiResponseMessage("Fail", "Upload Fail", "", "");
			return new ResponseEntity<>(message, HttpStatus.BAD_REQUEST);
		}
		ApiResponseMessage message = new ApiResponseMessage("Success", imageUrl, "", "");

		return new ResponseEntity<>(message, HttpStatus.OK);
	}
}

 

8. 반환될 응답 메시지 형식 (자유) 

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ApiResponseMessage {

	private String status;
	private String message;
	private String errorMessage;
	private String errorCode;
}

 

 

9. 실행 후 파일 업로드 하면 S3에 올라간 것을 확인할 수 있습니다. 

 

 

 

 

 

[참고 코드]

[1] https://cbw1030.tistory.com/m/335?category=1067183

'AWS' 카테고리의 다른 글

AWS 프리티어 EC2 스프링 부트 빌드 문제 (AWS EC2 스왑 메모리 할당)  (0) 2021.10.30
rest api로 spring boot + S3 버킷 이미지 업로드  (0) 2021.10.25
[Spring Boot + Jenkins 3/3] Jenkins 빌드 후 배포까지  (0) 2021.10.06
[Spring Boot + Jenkins 2/3] GitHub 에서 Jenkins 연동하여 빌드하기  (0) 2021.10.04
[Spring Boot + Jenkins 1/3] Ubuntu(18.04) Jenkins 설치  (0) 2021.09.30
'AWS' 카테고리의 다른 글
  • AWS 프리티어 EC2 스프링 부트 빌드 문제 (AWS EC2 스왑 메모리 할당)
  • rest api로 spring boot + S3 버킷 이미지 업로드
  • [Spring Boot + Jenkins 3/3] Jenkins 빌드 후 배포까지
  • [Spring Boot + Jenkins 2/3] GitHub 에서 Jenkins 연동하여 빌드하기
mers
mers
mers
nathan 개발블로그
mers
전체
오늘
어제
  • 분류 전체보기 (31)
    • Spring (7)
    • JAVA (1)
    • 알고리즘 (2)
    • AWS (13)
    • Linux (1)
    • Docker (2)
    • Git (2)
    • CI & CD (2)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • docker
  • rest api
  • ubuntu18.04
  • Spring Boot
  • S3
  • github
  • Spring
  • 스프링시큐리티
  • Method Security
  • codedeploy
  • https
  • JWT
  • dockerhub
  • docker-compose
  • git action
  • FCM
  • github actions
  • 젠킨스
  • springboot
  • jib
  • EC2
  • AWS
  • jenkins
  • CI/CD
  • transactional
  • mybatis
  • redis
  • Firebase Messaging
  • nuxt.js
  • 스프링부트

최근 댓글

최근 글

hELLO · Designed By 정상우.
mers
Spring boot , aws S3 버킷에 이미지 업로드
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.