이노베이션 캠프
[TIL] 26일차
hjkim0502
2022. 8. 27. 00:47
1. Spring
- Spring 주특기 마지막 주차에 예상치 못하게 팀플을 하게 되었는데 괜찮은 것 같다.
- 이번 기회에 많이 익숙치 않은 깃과 협업을 좀 더 연습하면 좋을 것 같다.
- GitHub Desktop에서 원격에 있는 repo 불러오기 -> clone repository
- IntelliJ에서 원격에 이미 만들어져 있는 repo 불러오기 -> get from version control
- (새로 생성은 share project on Github -> commit directory)
- find action (ctrl + shift + A)
- AWS S3 서비스를 이용해 게시글을 작성할 때 이미지를 업로드하고, 응답으로 이미지 url을 받는 기능을 배정받았다
- https://devlog-wjdrbs96.tistory.com/323, https://studyandwrite.tistory.com/497?category=1006444
- 두 블로그를 참고하여 만들었고, 이미지 파일만 받는 것으로 되어있기 때문에 관련 예외 처리는
- https://kimvampa.tistory.com/222 를 참고하여 완성했다
@RequiredArgsConstructor
@RestController
public class ImageController {
private final ImageService imageService;
@PostMapping("/api/auth/post/image")
public ResponseDto<?> uploadFile(@RequestParam("img") MultipartFile multipartFile,
@RequestParam String fileSize) throws IOException {
return imageService.upload(multipartFile.getInputStream(), multipartFile.getOriginalFilename(), fileSize); // url -> 다운로드
}
}
@RequiredArgsConstructor
@Service
public class ImageService {
@Value("${cloud.aws.s3.bucket}")
private String bucket;
private final AmazonS3Client amazonS3Client;
public ResponseDto<?> upload(InputStream inputStream, String originFileName, String fileSize) {
// 파일 변환 예외 처리
File checkFile = new File(originFileName);
String type = null;
try {
type = Files.probeContentType(checkFile.toPath());
} catch (IOException e) {
e.printStackTrace();
}
if(type == null || !type.startsWith("image")) {
return ResponseDto.fail("ONLY_IMAGE",
"파일 변환에 실패했습니다.");
}
// url 생성
String s3FileName = UUID.randomUUID() + "-" + originFileName;
ObjectMetadata objMeta = new ObjectMetadata();
objMeta.setContentLength(Long.parseLong(fileSize));
amazonS3Client.putObject(bucket, s3FileName, inputStream, objMeta);
String url = amazonS3Client.getUrl(bucket, s3FileName).toString();
return ResponseDto.success(url);
}
}
- 완성하고 스프링을 돌리는데 tomcat이 켜지면서 다 작동은 하는데 괜히 찜찜하게 아래의 에러가 떴다
com.amazonaws.SdkClientException: Failed to connect to service endpoint
- 검색을 통해 알아낸 것은 build.gradle에 'org.springframework.cloud:spring-cloud-starter-aws' 의존성을 넣어주면 aws 환경에서는 문제없지만 로컬환경에서는 뜨는 에러라고 한다
- 따라서 Run의 edit configuration에 들어가서 vm option에 '-Dcom.amazonaws.sdk.disableEc2Metadata=true'를 추가하니 해당 에러는 없어지고 어플리케이션 실행 시 딜레이가 사라졌다.
- https://thalals.tistory.com/289
- S3는 버킷이라는 곳에 파일을 객체의 형태로 저장한다
- EC2의 EBS를 하드디스크에 비유한다면 S3는 구글드라이브에 비유할 수 있음 (프로그램 설치, 구동 불가)
- https://inpa.tistory.com/entry/AWS-%F0%9F%93%9A-S3-%EB%B2%84%ED%82%B7-%EC%83%9D%EC%84%B1-%EC%82%AC%EC%9A%A9%EB%B2%95-%EC%8B%A4%EC%A0%84-%EA%B5%AC%EC%B6%95#S3_%EB%B2%84%ED%82%B7_/_%EA%B0%9D%EC%B2%B4_%EA%B0%9C%EB%85%90
- IAM은 AWS 내의 계정 관리 서비스
- SDK는 AWS 서비스를 프로그래밍 친화적으로 사용할 수 있게 해주는 도구