스프링 부트 - InputStream을 사용하여 URL로 부터 S3 버킷으로 이미지 업로드하기
작성 일자 : 2024년 10월 26일

개요
스프링에서 개발을 진행하면서 웹 상의 원격 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 버킷에 업로드합니다.
스프링 부트 - InputStream을 사용하여 URL로 부터 S3 버킷으로 이미지 업로드하기
작성 일자 : 2024년 10월 26일

개요
스프링에서 개발을 진행하면서 웹 상의 원격 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 버킷에 업로드합니다.