Search code examples
androidkotlinkotlin-multiplatformktorkmm

How can i add headers to ktor request if i use submitFormWithBinaryData()?


Code below is to upload an file using ktor and kmm ...

val client = HttpClient(Apache) {}
    val file = File("path/to/some.file")
    val chatId = "123"
    
    client.submitFormWithBinaryData(
        url = "https://api.telegram.org/bot<token>/sendDocument?chat_id=$chatId",
        formData = formData {
            append("document", file.readBytes(), Headers.build {
                append(HttpHeaders.ContentDisposition, "filename=${file.name}")
            })
        }
    )

Solution

  • You can't do that using the submitFormWithBinaryData method. Use the post or request method. Here is an example:

    client.post("https://api.telegram.org/bot<token>/sendDocument?chat_id=$chatId") {
        header("custom", "value")
        body = MultiPartFormDataContent(formData {
            append("document", file.readBytes(), Headers.build {
                append(HttpHeaders.ContentDisposition, "filename=${file.name}")
            })
        })
    }