androidkotlinktorktor-client

Serializer for class 'MultipartBody' is not found


Hi I am trying to make multiform request with ktor but I am getting above error. How can I serilize MultiPartBody?

   val body = MultipartBody.Builder().setType(MultipartBody.FORM)
    .addFormDataPart("choice","John Wick")
    .addFormDataPart("image",path,
        File(path).asRequestBody("application/octet-stream".toMediaType()))
    .build()

val httpResponse = client.post {
    url("https://example.com")
    setBody(body)
    header("Content-Type","application/json")
    header("Authorization", "Bearer key")
}

Solution

  • Ktor cannot send directly an object of the okhttp3.MultipartBody class. Please use the MultiPartFormDataContent class instead:

    val body = MultiPartFormDataContent(
        formData {
            append("choice", "John Wick")
            append("image", File(path).readBytes(), Headers.build {
                append(HttpHeaders.ContentType, "application/octet-stream")
                append(HttpHeaders.ContentDisposition, "filename=\"file\"")
            })
        }
    )