스프링 부트 - InputStream을 사용하여 URL로 부터 S3 버킷으로 이미지 업로드하기

2024. 10. 26. 22:41· Cloud Architecture
목차
  1. 개요
  2. 의존성 추가
  3. 코드 예시
  4. URL Connection
  5. Input Stream 생성 및 PutObjectRequest 생성
  6. Request Body 생성 및 이미지 업로드

스프링 부트 - InputStream을 사용하여 URL로 부터 S3 버킷으로 이미지 업로드하기

 

작성 일자 : 2024년 10월 26일


 

Cloud illustrated by Dalle3

 

 

개요

 

스프링에서 개발을 진행하면서 웹 상의 원격 URL에서 데이터를 가져와 S3 버킷에 이미지를 업로드하는 로직이 필요한 경우가 있습니다.

 

이번 포스팅에서는 HttpURLConnection과 AWS SDK for Java v2를 사용하여 이미지를 S3 버킷에 업로드하는 방법에 대해 알아보겠습니다.

 


 

 

의존성 추가

 

dependencies {
    implementation 'software.amazon.awssdk:s3:2.28.23'
}
  • 추가로, S3Config 클래스를 생성하고 AWS Credentials를 설정합니다.

 


 

 

코드 예시

 

public class ImageUploader {

    private static final Logger log = LoggerFactory.getLogger(ImageUploader.class);

    private final S3Client s3Client;
    private final String bucketName;
    private final String bucketPublicUrl;

    public ImageUploader(S3Client s3Client, String bucketName, String bucketPublicUrl) {
        this.s3Client = s3Client;
        this.bucketName = bucketName;
        this.bucketPublicUrl = bucketPublicUrl;
    }

    public String uploadImageFromUrl(String imageUrl, String fileName) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;

        try {
            // Initialize connection to the image URL
            URL url = new URL(imageUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(10000); // 10 seconds
            connection.setReadTimeout(30000); // 30 seconds

            // Check if the connection was successful
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new RuntimeException("Failed to download image from URL: " + responseCode);
            }

            // Retrieve the input stream from the URL connection
            inputStream = new BufferedInputStream(connection.getInputStream());

            // Prepare S3 PutObject request
            PutObjectRequest putObjectRequest = PutObjectRequest.builder()
                    .bucket(bucketName)
                    .key(fileName)
                    .contentType("image/webp")
                    .build();

            // Get content length from the connection
            long contentLength = connection.getContentLengthLong();

            // Create request body for S3 from the input stream
            RequestBody requestBody = RequestBody.fromInputStream(inputStream, contentLength);

            // Upload the image to S3
            s3Client.putObject(putObjectRequest, requestBody);

            // Return the public URL of the uploaded image
            return String.format("%s/%s", bucketPublicUrl, fileName);

        } catch (Exception e) {
            log.error("Failed to upload image to S3", e);
            throw new RuntimeException("Failed to upload image to S3", e);
        } finally {
            // Ensure resources are closed properly
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("Failed to close input stream", e);
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
}

 


 

 

URL Connection

 

URL url = new URL(imageUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(10000); // 10 seconds
connection.setReadTimeout(30000); // 30 seconds
  • HttpURLConnection을 사용하여 원격 URL에 연결합니다.

 


 

Input Stream 생성 및 PutObjectRequest 생성

inputStream = new BufferedInputStream(connection.getInputStream());

PutObjectRequest putObjectRequest = PutObjectRequest.builder()
        .bucket(bucketName)
        .key(fileName)
        .contentType("image/webp")
        .build();

 


 

Request Body 생성 및 이미지 업로드

long contentLength = connection.getContentLengthLong();

RequestBody requestBody = RequestBody.fromInputStream(inputStream, contentLength);

s3Client.putObject(putObjectRequest, requestBody);
  • RequestBody.fromInputStream을 사용하여 InputStream을 RequestBody로 변환합니다.
  • S3Client.putObject를 사용하여 이미지를 S3 버킷에 업로드합니다.
저작자표시 (새창열림)
  1. 개요
  2. 의존성 추가
  3. 코드 예시
  4. URL Connection
  5. Input Stream 생성 및 PutObjectRequest 생성
  6. Request Body 생성 및 이미지 업로드
'Cloud Architecture' 카테고리의 다른 글
  • 스프링부트에서 Cloudflare R2 스토리지 사용하기(AWS SDK for JAVA 2.x)
  • Proxmox VE Helper-Scripts를 통해 생성한 LXC에서 root 유저 ssh 접근 설정하기
  • Digital Ocean에 VM 인스턴스 생성하기
gerrymandering
gerrymandering
gerrymandering
gerrymandering
gerrymandering
전체
오늘
어제
  • 분류 전체보기 (76) N
    • SOLID 원칙 (6)
    • 번역 (4)
    • Nginx (1)
    • Tailwind CSS (1)
    • AWS (7)
      • DMS를 사용한 RDS to OpenSearch .. (3)
      • ECS를 이용한 Blue-Green 무중단 배포 .. (7)
    • NextJS (2)
    • 기타 (10) N
    • Prompt Engineering (6)
    • 읽어볼만한 글 (3)
      • 기술 (0)
      • 쓸만한 툴 (0)
      • 아이템 (0)
      • 웹 디자인 (0)
      • 기타 (3)
    • Cloud Architecture (4)
    • Trouble Shooting (9)
    • Spring (11)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

최근 댓글

최근 글

글쓰기 / 관리자
hELLO · Designed By 정상우.v4.2.1
gerrymandering
스프링 부트 - InputStream을 사용하여 URL로 부터 S3 버킷으로 이미지 업로드하기
상단으로

티스토리툴바

단축키

내 블로그

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

블로그 게시글

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

모든 영역

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

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