Using DigitalOcean Spaces in Ktor (Kotlin)

G’day, today I’m going to show you how to upload files to DigitalOcean Spaces using Ktor and the AWS S3 SDK in (almost) no time.

First of all, just to get to common ground, what is DigitalOcean Spaces?

Beautifully simple and reliable object storage

This is what DigitalOcean says Spaces are, can’t speak about reliability (yet) but they’re definitely simple to use, given the fact they claim to be AWS S3 compatible, and can easily be implemented by using the AWS S3 SDK.

Let’s get started by creating a sample space. Currently, as of writing this (01/10/2017) they’re free for two months. Just head over to DigitalOcean.com (Affiliate Link) and create a new space.

Screenshot with DO Spaces Website

Currently the only region supporting Spaces is NYC3 with more coming soon.After successfully setting up the Space, you’ll be greeted with an empty directory listing. (It’ll be filled soon ;-))

Screenshot DO Spaces Buckets

For my setup I’m assuming you’re familiar with (or did checkout a getting-started) for Ktor. I’m using IntelliJ and just set up the router with a single endpoint /upload responding to POST requests.

Screenshot with Sourcecode

After ensuring we’re only left with types of FileItem, we can go ahead and instantiate the S3 Client and populate it with our credentials (retrieved by using environment variables).

Screenshot with Sourcecode

Note how we’re using a custom endpoint configuration and setting it to the digitaloceanspaces.com domain. The AWSACCESSKEY and AWSACCESSSECRET can be created in the DigitalOcean API settings.

Now that we’re having a functional upload client handy, we can just start iterating over our files and put them into the bucket, also we’re going to apply an ACL (Access Control List) to make our files publicly readable by anyone who has a link to them, please make sure to be careful what you’re uploading as those files will be exposed. If you rather would like to keep them secret (you’ll still be able to access them with you credentials) you maybe skip setting the ACL.

Screenshot with Sourcecode

Once done uploading, we’ll communicate to the user that we were successful. Obviously, in a production-ready world, you’ll need to catch errors and them, but this would exceed the scope of this post.

Let’s give it a try using Postman…

Screenshot from Postman

Looks promising already, let’s head over to the web app to see if the JPG is in our Space.

Victory Gif Meme

The uploaded file will now be readily accessible in you Space…