Last active
July 17, 2025 18:01
-
-
Save umpteenthdev/05651507613f77a7d17d11cb9d293da5 to your computer and use it in GitHub Desktop.
Ktor Client. How to send byteArray using multipart/form data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import io.ktor.client.HttpClient | |
| import io.ktor.client.call.call | |
| import io.ktor.client.engine.okhttp.OkHttp | |
| import io.ktor.client.request.forms.MultiPartFormDataContent | |
| import io.ktor.client.request.forms.formData | |
| import io.ktor.client.request.url | |
| import io.ktor.http.Headers | |
| import io.ktor.http.HttpHeaders | |
| import io.ktor.http.HttpMethod | |
| import kotlinx.coroutines.GlobalScope | |
| import kotlinx.coroutines.launch | |
| import kotlinx.io.streams.asInput | |
| class SendMultipart { | |
| fun sendBytes(url: String, imageBytes: ByteArray, fileName: String) { | |
| GlobalScope.launch { | |
| val result = | |
| HttpClient(OkHttp).call { | |
| url(url) | |
| method = HttpMethod.Post | |
| body = MultiPartFormDataContent( | |
| formData { | |
| append( | |
| "document", | |
| imageBytes, | |
| Headers.build { | |
| append(HttpHeaders.ContentType, "images/*") // Mime type required | |
| append(HttpHeaders.ContentDisposition, "filename=$fileName") // Filename in content disposition required | |
| } | |
| ) | |
| } | |
| ) | |
| }.response | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment