ktor client post multipart/form-data
Asked Answered
C

2

10

How can I post file as multipart/form-data use ktor client? I want to use it for telegram bot API "send document". I need to achieve the same result as the curl command

curl -F document=@"path/to/some.file" https://api.telegram.org/bot<token>/sendDocument?chat_id=<chat_id>
Cissy answered 3/11, 2021 at 19:51 Comment(2)
Does this answer your question? Uploading files to telegram bot api using ktorSternlight
Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.Tyndall
T
7

You can use the submitFormWithBinaryData method to send mutlipart/form-data request. Here is a solution:

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}")
        })
    }
)
Twyla answered 4/11, 2021 at 8:39 Comment(3)
I see many examples like these but i hope nobody uses them in production because what if the file in question is 10MB... it will be leaded into memory and crash the phone.Parlando
Can you tell how to import this File in CommonMain.Horeb
Please can you look at my question: https://mcmap.net/q/1166096/-problem-translating-retrofit-multipart-call-to-ktor/472270 ?Debose
G
2

If the file is large, you won't want to read the whole thing into memory. Instead, you can stream the upload.

val file = File("path/to/some.file")
client.submitFormWithBinaryData(
  url = "https://api.telegram.org/bot<token>/sendDocument?chat_id=$chatId",
  formData = formData {
    append(
      "document".quote(),
      InputProvider(file.length()) { file.inputStream().asInput() },
      Headers.build {
        append(HttpHeaders.ContentDisposition, "filename=${file.name.quote()}")
      }
    )
  }
)
Generate answered 2/6, 2023 at 20:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.