From 8f25c123dde77d9c44443b1389097a2270164f1f Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Thu, 24 Nov 2022 11:27:30 +0600 Subject: [PATCH] add download and downloadToTemporalFile extensions --- CHANGELOG.md | 1 + .../ktor/server/DownloadFileItem.kt | 56 +++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 ktor/server/src/jvmMain/kotlin/dev/inmo/micro_utils/ktor/server/DownloadFileItem.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 52c6f0333bc..47ff8f9da13 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ * New universal `uniUpload` extension for `HttpClient` * `Server`: * New universal `handleUniUpload` extension for `ApplicationCall` + * Add extensions `download` and `downloadToTemporalFile` ## 0.14.2 diff --git a/ktor/server/src/jvmMain/kotlin/dev/inmo/micro_utils/ktor/server/DownloadFileItem.kt b/ktor/server/src/jvmMain/kotlin/dev/inmo/micro_utils/ktor/server/DownloadFileItem.kt new file mode 100644 index 00000000000..2056a6e704b --- /dev/null +++ b/ktor/server/src/jvmMain/kotlin/dev/inmo/micro_utils/ktor/server/DownloadFileItem.kt @@ -0,0 +1,56 @@ +package dev.inmo.micro_utils.ktor.server + +import com.benasher44.uuid.uuid4 +import io.ktor.http.content.PartData +import io.ktor.utils.io.copyTo +import io.ktor.utils.io.core.copyTo +import io.ktor.utils.io.jvm.javaio.copyTo +import io.ktor.utils.io.streams.asOutput +import java.io.File + +fun PartData.FileItem.download(target: File) { + provider().use { input -> + target.outputStream().use { + input.copyTo(it.asOutput()) + } + } +} + +fun PartData.FileItem.downloadToTemporalFile(): File { + val outputFile = File.createTempFile(uuid4().toString(), ".temp").apply { + deleteOnExit() + } + download(outputFile) + return outputFile +} + +fun PartData.BinaryItem.download(target: File) { + provider().use { input -> + target.outputStream().use { + input.copyTo(it.asOutput()) + } + } +} + +fun PartData.BinaryItem.downloadToTemporalFile(): File { + val outputFile = File.createTempFile(uuid4().toString(), ".temp").apply { + deleteOnExit() + } + download(outputFile) + return outputFile +} + +suspend fun PartData.BinaryChannelItem.download(target: File) { + val input = provider() + target.outputStream().use { + input.copyTo(it) + } +} + +suspend fun PartData.BinaryChannelItem.downloadToTemporalFile(): File { + val outputFile = File.createTempFile(uuid4().toString(), ".temp").apply { + deleteOnExit() + } + download(outputFile) + return outputFile +}