4

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.

  • did you try something along the lines of: suspend fun putMultipart(partData: List) { httpClient.put("url") { body = MultiPartFormDataContent(partData) } } – dimitris boutas Jan 06 '21 at 20:10
  • Does this answer your question? [How to upload a file using Ktor client](https://stackoverflow.com/questions/60373937/how-to-upload-a-file-using-ktor-client) – Artyom Degtyarev Mar 02 '21 at 07:07
  • I've found a similar question with an answer here - https://stackoverflow.com/questions/60373937/how-to-upload-a-file-using-ktor-client. – Artyom Degtyarev Mar 02 '21 at 07:07
  • 1
    @ArtyomDegtyarev Thanks for the helpful comments, above mentioned urls are using multipart or part data.. But I needed to just put the file as binary body into the request and upload. turns out, With Ktor, we cant do that. I used platform specific libraries to do that. Thank you very much – Kishorekumar E K Jun 17 '21 at 11:55
  • 1
    @KishorekumarEK How are you getting this import File(path).readBytes() is it Java file in kotlin multiplatform? – RaghavPai Aug 18 '21 at 15:16
  • @RaghavPai, No its a ByteArray Type for clarity I've replaced the line with File(path).readBytes() I pass the byteArray from android to this method – Kishorekumar E K Aug 24 '21 at 08:27

1 Answers1

0

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.