#2 서버리스 프론트엔드 - 사진 파일 업로드(springboot aws s3 gradle)
프로젝트에 사진 업로드 기능을 AWS S3를 spring boot로 구현하며 마주한 Error들을 기록한다.
# 검색어
- 시작은 UI를 준비하고, 구글로 springboot aws s3, spring boot gradle aws s3 라는 키워드로 검색했다.
- 포스팅을 5개 정도 훑어보고 반가운 향로님 블로그가 가장 친절한 설명이 있어 따라해 보기로했다.
# 첫 오류 dependencies 주입
"dependencies 주입은 implementation 명령어로 주입 한다"
- 시작부터 오류와 마주했다. 아래와 같이 따라했더니 gradle이 정상적으로 작동하지 않았다.
- handlebars가 뭔지 모르겠고, dependencyManagement가 뭔지 모르겠고, 무엇보다 왜 spring-cloud라는 패키지를 불러오는지 이해하지 못했다.
- 검색해보니 AWS 공식 사이트에서는 전혀 다른 라이브러리 코드가 있어서 혼란스러웠다. 산넘어 산..
https://docs.aws.amazon.com/ko_kr/sdk-for-java/v1/developer-guide/setup-project-gradle.html
- 결론은 compile이란 명령어는 gradle의 이전 버전에서 사용하는 명령어고 현재는 implementation이 대신하게 되었다는 글을 찾았다. dependencies 위에 모르는 내용(2018년 기준)은 무시하고.. 아래와 같이 한줄만 입력했더니 해결되었다.(2021.11 기준)
# 두 번째 오류
- jojuldo님(향로님) 블로그을 그대로 따라했더니, been에서 AmazonS3Client를 찾을 수 없다는 오류가 나타났다.
AmazonS3Client
- https://stackoverflow.com/questions/41951978/amazons3clientcredentials-is-deprecated
- AmazonS3Client가 deprecated되었고, AwsClientBuilder를 대신 사용하자는 내용이다.
AWSClientBuilder를 사용한 코드 (위치 : /config/AmazonConfig)
@Configuration
public class AmazonS3Config {
@Value("${cloud.aws.credentials.access-key}")
private String accessKey;
@Value("${cloud.aws.credentials.secret-key}")
private String secretKey;
@Value("${cloud.aws.region.static}")
private String region;
@Bean
public AmazonS3Client amazonS3Client() {
BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKey, secretKey);
return (AmazonS3Client) AmazonS3ClientBuilder.standard()
.withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.build();
}
}
프로젝트의 구조
# 세번째 오류 application
- 그 동안 SpringApplication.run(메인프로젝트.class)로 실행만하다가,
- 처음으로 SpringApplicationBuilder를 사용했다.
- AWS IAM으로 S3버킷에 접근하기 위한 key를 사용하기 위함이다.
- yml은 JSON과 같이 타 프로그램과 연동할때 사용하는 언어 (https://www.inflearn.com/questions/16184)
- 특이사항 : S3 버킷에 정책 생성을 코드로 해서 붙였다. (https://devlog-wjdrbs96.tistory.com/323)
@SpringBootApplication
@EnableJpaAuditing
public class MaruMaruSpartaVerSpringApplication {
public static final String APPLICATION_LOCATIONS = "spring.config.location="
+ "classpath:application.yml,"
+ "classpath:aws.yml";
public static void main(String[] args) {
new SpringApplicationBuilder(MaruMaruSpartaVerSpringApplication.class)
.properties(APPLICATION_LOCATIONS)
.run(args);
}
}
yml 파일에 버킷정보, 접근키 등을 작성하여 드디어..
# 썸네일 만들기
- 저장하지 않고 썸네일로 미리 보기 기능을 추가할 수 있다.
- accept로 파일의 타입을 설정해서 이미지 파일이 아닌 파일 업로드를 막을 수 있다.
<div class="file">
<label for="img">파일 업로드</label>
<input type="file" id="img" accept="image/*" onchange="setThumbnail(event);">
<div id="image_container"></div>
</div>
function setThumbnail(event) {
var reader = new FileReader();
reader.onload = function (event) {
var img = document.createElement("img");
img.setAttribute("src", event.target.result);
document.querySelector("div#image_container").appendChild(img);
};
reader.readAsDataURL(event.target.files[0]);
}
Recourse