Search code examples
androidkotlinkotlin-multiplatformktorktor-client

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.

There is "put" api to upload local audio file as Binary.

Ive created httpclient as follows

 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

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 . I need to do similar thing.

When I checked in Ktor, it shows only multi-part form data can be submitted as binary. But In my case it is Put request.

Please help.


Solution

  • Looks like there is no straightforward way to put file as binary with Ktor.

    I had to go for platform Dependent approaches like OkHttpClient for Android and URLSession for iOS.