Trabajo con S3 y almacenamiento en la nube en Kotlin: AWS SDK y Ktor S3 Client

Entrenador de Python en Línea para Principiantes

Aprende Python fácilmente sin sobrecargarte de teoría. Resuelve tareas prácticas con verificación automática, recibe pistas y escribe código directamente en el navegador, sin instalar nada.

Start Course

Trabajo con S3 y almacenamiento en la nube en Kotlin



En el desarrollo moderno con Kotlin, a menudo surge la necesidad de integrarse con almacenamiento en la nube compatible con el protocolo Amazon S3 (Simple Storage Service). Estos pueden ser AWS S3, MinIO, DigitalOcean Spaces, Yandex Object Storage y otros. En este artículo, exploraremos dos enfoques principales: el uso del AWS SDK oficial para Kotlin y un cliente ligero basado en Ktor.



1. AWS SDK para Kotlin (aws-sdk-kotlin)



El SDK oficial de Amazon proporciona una API tipada y asíncrona con soporte completo para corrutinas de Kotlin. Es la solución más completa para trabajar con S3.



Agregar dependencia

Añada en build.gradle.kts:

dependencies {    implementation("aws.sdk.kotlin:s3:1.0.0")    implementation("aws.smithy.kotlin:http-client-engine-ktor:1.0.0")}


Inicialización del cliente

import aws.sdk.kotlin.services.s3.S3Clientimport aws.sdk.kotlin.services.s3.model.*

suspend fun createClient(): S3Client = S3Client.fromEnvironment { region = "ru-central1" // Para MinIO u otros almacenes compatibles con S3: endpointUrl = "https://storage.yandexcloud.net" // Configuración mediante variables de entorno AWS_ACCESS_KEY_ID y AWS_SECRET_ACCESS_KEY}


Carga de archivo (PutObject)

suspend fun uploadFile(client: S3Client, bucket: String, key: String, filePath: String) {    val fileBytes = java.io.File(filePath).readBytes()    client.putObject(        PutObjectRequest {            this.bucket = bucket            this.key = key            this.body = fileBytes.toByteArray()        }    )    println("Archivo $key cargado en el bucket $bucket")}


Descarga de archivo (GetObject)

suspend fun downloadFile(client: S3Client, bucket: String, key: String, savePath: String) {    val response = client.getObject(        GetObjectRequest {            this.bucket = bucket            this.key = key        }    )    val bytes = response.body?.readAll()    if (bytes != null) {        java.io.File(savePath).writeBytes(bytes)        println("Archivo $key guardado en $savePath")    }}


Listar objetos en el bucket

suspend fun listObjects(client: S3Client, bucket: String): List<String> {    val response = client.listObjectsV2(        ListObjectsV2Request {            this.bucket = bucket        }    )    return response.contents?.map { it.key ?: "" } ?: emptyList()}


2. Ktor S3 Client (alternativa ligera)



Si no necesita toda la potencia del AWS SDK, puede usar Ktor junto con la biblioteca ktor-client-s3. Esto proporciona un peso mínimo y control total sobre las solicitudes HTTP.



Agregar dependencias

dependencies {    implementation("io.ktor:ktor-client-core:2.3.0")    implementation("io.ktor:ktor-client-cio:2.3.0")    implementation("io.ktor:ktor-client-content-negotiation:2.3.0")    implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.0")    // Para firmar solicitudes S3    implementation("io.ktor:ktor-client-auth:2.3.0")}


Creación de cliente S3 con Ktor

import io.ktor.client.*import io.ktor.client.request.*import io.ktor.client.statement.*import io.ktor.http.*import io.ktor.utils.io.*

class S3KtorClient( private val endpoint: String, private val accessKey: String, private val secretKey: String) { private val client = HttpClient { install(io.ktor.client.plugins.auth.Auth) { basic { credentials { username = accessKey password = secretKey } } } }

suspend fun putObject(bucket: String, key: String, data: ByteArray) { client.put("

Recommendations