KTOR - 在 POST 路由中解压文件
KTOR - Unzip file in POST routing
我想解压缩在 Ktor 中的 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 { ... } } 代替。
我不会写这样的函数。
我可以帮忙吗?
谢谢
您可以使用以下代码将 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()
}
我想解压缩在 Ktor 中的 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 { ... } } 代替。
我不会写这样的函数。 我可以帮忙吗?
谢谢
您可以使用以下代码将 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()
}