【问题标题】:KTOR - Unzip file in POST routingKTOR - 在 POST 路由中解压缩文件
【发布时间】:2021-07-28 22:52:58
【问题描述】:

我想解压缩在 Ktor(bloc rounting)中的 http 查询(内容类型:application/x-gzip)正文中发送的文件 zip。 我试过这个:

val zip_received=call.receiveStream() val incomingContent = GZIPInputStream(zip_received).toByteReadChannel()

但是我收到了这个错误:

java.lang.IllegalStateException:不允许在此调度程序上获取阻塞原语。考虑使用异步通道或使用 withContext(Dispatchers.IO) { call.receive().use { ... } }。

我无法编写这样的函数。 我可以帮忙吗?

谢谢

【问题讨论】:

    标签: kotlin ktor


    【解决方案1】:

    您可以使用以下代码将 GZip 未压缩的请求正文读取为字符串:

    import io.ktor.server.engine.*
    import io.ktor.server.netty.*
    import io.ktor.application.*
    import io.ktor.request.*
    import io.ktor.routing.*
    import kotlinx.coroutines.Dispatchers
    import kotlinx.coroutines.withContext
    import java.io.InputStream
    import java.util.zip.GZIPInputStream
    
    fun main(args: Array<String>) {
        embeddedServer(Netty, port = 9090) {
            routing {
                post("/") {
                    withContext(Dispatchers.IO) {
                        call.receive<InputStream>().use { stream ->
                            val gzipStream = GZIPInputStream(stream)
                            val uncompressedBody = String(gzipStream.readAllBytes())
                            println(uncompressedBody)
                        }
                    }
                }
            }
        }.start()
    }
    

    【讨论】:

    • 嗨。谢谢它完美的工作。我只需要更改 readBytes() 而不是 readAllBytes 因为此方法不存在。可能是我的 GZIPInputStream 版本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    相关资源
    最近更新 更多