이노베이션 캠프

[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을 받는 기능을 배정받았다
@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