Kotlin용 AWS SDK (aws-sdk-kotlin)로 R2 사용하기
Kotlin용 AWS SDK(aws-sdk-kotlin)로 R2를 사용하는 예시예요. S3 클라이언트를 구성하고 버킷·객체를 나열하며 사전 서명 URL을 생성하는 방법을 보여줘요.
출처: 문서
본문
이 예시는 aws-sdk-kotlin ↗︎을 사용해요. S3 클라이언트를 만들 때 R2 구성 자격 증명을 반드시 전달해야 해요.
기본 사용법 (Basic Usage)
import aws.sdk.kotlin.runtime.auth.credentials.StaticCredentialsProvider
import aws.sdk.kotlin.services.s3.S3Client
import aws.sdk.kotlin.services.s3.listObjects
import aws.sdk.kotlin.services.s3.model.GetObjectRequest
import aws.sdk.kotlin.services.s3.model.PutObjectRequest
import aws.sdk.kotlin.services.s3.presigners.presignGetObject
import aws.sdk.kotlin.services.s3.presigners.presignPutObject
import aws.smithy.kotlin.runtime.auth.awscredentials.Credentials
import aws.smithy.kotlin.runtime.net.url.Url
import kotlinx.coroutines.runBlocking
import kotlin.time.Duration.Companion.minutes
val ACCOUNT_ID = "<ACCOUNT_ID>"
val ACCESS_KEY = "<ACCESS_KEY>"
val SECRET_KEY = "<SECRET_KEY>"
fun main() = runBlocking {
val r2Client = S3Client.fromEnvironment {
region = "auto" // Required by SDK, but not used by R2
endpointUrl = Url.parse("https://${ACCOUNT_ID}.r2.cloudflarestorage.com")
credentialsProvider = StaticCredentialsProvider(
Credentials(
accessKeyId = ACCESS_KEY,
secretAccessKey = SECRET_KEY
),
)
}
println("Available buckets:")
r2Client.listBuckets().buckets?.forEach { bucket ->
println("* ${bucket.name}")
}
val bucketName = "<BUCKET_NAME>"
println("\nObjects in bucket '${bucketName}':")
r2Client.listObjects { bucket = bucketName }.contents?.forEach {
println("* ${it.key} (size: ${it.size} bytes, modified: ${it.lastModified})")
}
r2Client.close()
}
Available buckets:
* my-bucket-1
* my-bucket-2
Objects in bucket 'my-bucket-1':
* image1.png (size: 253167 bytes, modified: 2026-01-17T11:30:58.896Z)
* image2.png (size: 247027 bytes, modified: 2026-01-17T11:30:57.779Z)
사전 서명 URL 생성 (Generate presigned URLs)
버킷에 대한 공개 읽기 또는 쓰기 접근 권한을 일시적으로 공유하는 데 사용할 수 있는 사전 서명 링크도 생성할 수 있어요.
val uploadUrl = r2Client.presignPutObject(
input = PutObjectRequest {
bucket = bucketName
key = "README.md"
},
duration = 15.minutes,
).url
println(uploadUrl)
val getUrl = r2Client.presignGetObject(
input = GetObjectRequest {
bucket = bucketName
key = "README.md"
},
duration = 15.minutes,
).url
println(getUrl)
이 사전 서명 URL은 어떤 HTTP 클라이언트에서든 사용할 수 있어요. 예를 들어 PUT URL로 파일을 업로드하려면:
curl -X PUT "https://<your-presigned-put-url>" -H "Content-Type: application/octet-stream" --data-binary "@local-file.txt"
GET URL로 파일을 다운로드하려면:
curl -X GET "https://<your-presigned-get-url>" -o downloaded-file.txt