Travailler avec S3 et les stockages cloud en Kotlin : AWS SDK et Ktor S3 Client

Formateur Python en ligne pour débutants

Apprenez Python facilement sans surcharge théorique. Résolvez des tâches pratiques avec vérification automatique et écrivez du code directement dans le navigateur.

Start Course

Travailler avec S3 et les stockages cloud en Kotlin

\n\n

Dans le développement moderne en Kotlin, il est souvent nécessaire d'intégrer des stockages cloud compatibles avec le protocole Amazon S3 (Simple Storage Service). Il peut s'agir d'AWS S3, MinIO, DigitalOcean Spaces, Yandex Object Storage, etc. Dans cet article, nous examinerons deux approches principales : l'utilisation du AWS SDK officiel pour Kotlin et d'un client léger basé sur Ktor.

\n\n

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

\n\n

Le SDK officiel d'Amazon fournit une API typée et asynchrone, prenant entièrement en charge les coroutines Kotlin. C'est la solution la plus complète pour travailler avec S3.

\n\n

Ajout de la dépendance

\n

Ajoutez dans build.gradle.kts :

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

Initialisation du client

\n
import aws.sdk.kotlin.services.s3.S3Client\nimport aws.sdk.kotlin.services.s3.model.*\n\nsuspend fun createClient(): S3Client = S3Client.fromEnvironment {\n    region = "ru-central1"\n    // Pour MinIO ou autres stockages compatibles S3 :\n    endpointUrl = "https://storage.yandexcloud.net"\n    // Configuration via les variables d'environnement AWS_ACCESS_KEY_ID et AWS_SECRET_ACCESS_KEY\n}
\n\n

Téléchargement d'un fichier (PutObject)

\n
suspend fun uploadFile(client: S3Client, bucket: String, key: String, filePath: String) {\n    val fileBytes = java.io.File(filePath).readBytes()\n    client.putObject(\n        PutObjectRequest {\n            this.bucket = bucket\n            this.key = key\n            this.body = fileBytes.toByteArray()\n        }\n    )\n    println("Fichier $key téléchargé dans le bucket $bucket")\n}
\n\n

Téléchargement d'un fichier (GetObject)

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

Liste des objets dans le bucket

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

2. Ktor S3 Client (alternative légère)

\n\n

Si vous n'avez pas besoin de toute la puissance du AWS SDK, vous pouvez utiliser Ktor avec la bibliothèque ktor-client-s3. Cela offre un poids minimal et un contrôle total sur les requêtes HTTP.

\n\n

Ajout des dépendances

\n
dependencies {\n    implementation("io.ktor:ktor-client-core:2.3.0")\n    implementation("io.ktor:ktor-client-cio:2.3.0")\n    implementation("io.ktor:ktor-client-content-negotiation:2.3.0")\n    implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.0")\n    // Pour la signature des requêtes S3\n    implementation("io.ktor:ktor-client-auth:2.3.0")\n}
\n\n

Création d'un client S3 avec Ktor

\n
import io.ktor.client.*\nimport io.ktor.client.request.*\nimport io.ktor.client.statement.*\nimport io.ktor.http.*\nimport io.ktor.utils.io.*\n\nclass S3KtorClient(\n    private val endpoint: String,\n    private val accessKey: String,\n    private val secretKey: String\n) {\n    private val client = HttpClient {\n        install(io.ktor.client.plugins.auth.Auth) {\n            basic {\n                credentials {\n                    username = accessKey\n                    password = secretKey\n                }\n            }\n        }\n    }\n\n    suspend fun putObject(bucket: String, key: String, data: ByteArray) {\n        client.put("                    

Recommendations