Application
File storage
Save and read files on disk or in S3, with one API.
StorageService stores files by key (a path-like name such as avatars/42.png). The code stays the same whether the files live on a laptop disk, in memory (tests) or in an S3 bucket: only the driver in the module changes.
Kest.run<AppModule> {
import(StorageModule.forRoot {
driver = if (System.getenv("ENV") == "production")
S3Storage(endpoint = "https://s3.eu-west-1.amazonaws.com", region = "eu-west-1", bucket = "shop-files",
accessKey = System.getenv("S3_KEY"), secretKey = System.getenv("S3_SECRET"), pathStyle = false)
else LocalStorage(Path.of("uploads"))
})
}@Controller("/avatars")
class AvatarController(private val storage: StorageService) {
@Post("/{id}") fun upload(@Param("id") id: String, @FormFile("file") file: UploadedFile): Map<String, Any?> {
storage.put("avatars/$id.png", file.bytes, file.contentType)
return mapOf("url" to storage.signedUrl("avatars/$id.png")) // S3: a link that works for 15 minutes; local disk: null
}
@Get("/{id}") fun download(@Param("id") id: String): StreamableFile {
val file = storage.get("avatars/$id.png") ?: throw NotFoundException()
return StreamableFile(file.stream, file.info.contentType ?: "application/octet-stream") // streamed, not read into memory
}
}| Method | What it does |
|---|---|
put(key, bytes or stream, contentType?) | writes (or replaces) the file |
get(key) | a StoredObject (info + stream), or null when it does not exist |
head(key) / exists(key) | size, content type and last-modified without reading the file |
delete(key) | true if something was deleted |
list(prefix, limit) | file infos below a prefix |
signedUrl(key, expires) | a temporary download link (S3 drivers); null when the driver has none |
Drivers
| Driver | Use it for |
|---|---|
LocalStorage(path) | development and single-server apps. A key can never escape the directory; writes are atomic (temporary file, then move). |
InMemoryStorage() | tests |
S3Storage(...) | AWS S3 and anything that speaks the S3 API: MinIO, Cloudflare R2, DigitalOcean Spaces, Backblaze B2, Google Cloud Storage's S3-compatible endpoint. pathStyle = true for MinIO-style host/bucket/key URLs. |
To add another backend implement StorageDriver (put, get, delete, head, list).
Keys are checked: empty keys, keys longer than 1024 characters, a leading /, and .. segments are refused with a StorageException.
What is verified
The local and in-memory drivers and the request signing (AWS Signature Version 4, checked against AWS's published test vectors and a fake S3 server) have automated tests. The S3 driver has not yet been run against a real S3 or MinIO server: do a first upload and download against your bucket before relying on it. Uploads are held in memory (put takes a whole byte array), so very large files need a streaming driver, which is not built.