[英]Put File as Binary with Ktor HttpClient in Kotlin Multiplatform Project
I have a multiplatform project in which api code is shared between iOS and Android.我有一个多平台项目,其中 api 代码在 iOS 和 Android 之间共享。
There is "put" api to upload local audio file as Binary.有“put” api 以二进制形式上传本地音频文件。
Ive created httpclient as follows我创建了httpclient如下
val client = HttpClient {
defaultRequest {
url {
protocol = ServiceConfiguration.protocol
host = ServiceConfiguration.baseUrl
port = ServiceConfiguration.port
}
contentType(ContentType.Application.Json)
}
install(JsonFeature) {
val json = kotlinx.serialization.json.Json {
ignoreUnknownKeys = true
isLenient = true
}
serializer = KotlinxSerializer(json)
}
}
To put the object into api, I am doing as follows要将 object 放入 api,我这样做如下
val response = ServiceRequest.client.put<String>(
body = File(path).readBytes()
)
It works fine and uploads the byte array to backend.它工作正常并将字节数组上传到后端。 But instead of byte array I want to upload the file as plain binary.
但是我想将文件作为普通二进制文件上传,而不是字节数组。
To make it more clear, In Postman mac app we can upload file as binary.为了更清楚,在 Postman mac 应用程序中,我们可以将文件上传为二进制文件。 I need to do similar thing.
我需要做类似的事情。
When I checked in Ktor, it shows only multi-part form data can be submitted as binary.当我签入 Ktor 时,它显示只能以二进制形式提交多部分表单数据。 But In my case it is Put request.
但在我的情况下,它是 Put 请求。
Please help.请帮忙。
Looks like there is no straightforward way to put file as binary with Ktor.看起来没有直接的方法可以使用 Ktor 将文件作为二进制文件。
I had to go for platform Dependent approaches like OkHttpClient for Android and URLSession for iOS.对于平台相关的方法,我必须使用 go,例如用于 Android 的 OkHttpClient 和用于 iOS 的 URLSession。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.