Kotlin
S3

KotlinでAmazonS3にファイルをアップロードする

More than 1 year has passed since last update.

依存関係を追加する

compile 'com.amazonaws:aws-java-sdk-s3:1.11.185'

ラッパーを作ってみました

class File(
    private val path: String,
    private val body: String
) {
    companion object {
        val S3_ACCESS_KEY = "xxxxx"
        val S3_SECRET_KEY = "xxxxx"
        val S3_SERVICE_END_POINT = "https://s3-ap-northeast-1.amazonaws.com"
        val S3_REGION = "ap-northeast-1"
        val S3_BUCKET_NAME = "xxxxx"
    }

    fun save() {
        val file = File(path)
        val writer = FileWriter(file)
        writer.write(body)
        writer.close()

        val client = AmazonS3ClientBuilder
            .standard().
            withCredentials(AWSStaticCredentialsProvider(BasicAWSCredentials(S3_ACCESS_KEY, S3_SECRET_KEY)))
            .withClientConfiguration(ClientConfiguration().apply {
                protocol = Protocol.HTTPS
                connectionTimeout = 10000
            })
            .withEndpointConfiguration(EndpointConfiguration(S3_SERVICE_END_POINT, S3_REGION))
            .build()

        try {
            client.putObject(PutObjectRequest(S3_BUCKET_NAME, file.name, file).apply {
                cannedAcl = CannedAccessControlList.PublicRead
            })
        } catch (e: AmazonClientException) {
            e.printStackTrace()
        }
    }
}

使う時はこのように使います

File("/tmp/backup/test", "テストファイルです").save()