0

I'm totally new to kotlin. I'm writing a network call to create a product like following code. But ktor's FormDataContent doesn't allow me to put file as MultiPartFormDataContent. Show me a proper way please.

import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.request.forms.*
import io.ktor.http.*

import java.io.File

class ProductService(private val httpClient: HttpClient) {
    companion object {
        private const val BASE_URL = "http://localhost:8080"
        private const val PRODUCT_ENDPOINT = "/products"
    }

    suspend fun createProduct(product: Product, imageFile: File) {
        val formData = FormDataContent(Parameters.build {
            append("code", product.code)
            append("name", product.name)
            append("description", product.description)
            append("price", product.price)
        })

        if (imageFile != null) {
            formData.append("imageFile", imageFile) // error 
        }


        httpClient.post<Unit> {
            url("$BASE_URL$PRODUCT_ENDPOINT")
            body = formData
        }
    }
}
Zin Win Htet
  • 2,448
  • 4
  • 32
  • 54

1 Answers1

1

The FormDataContent represents a request with the application/x-www-form-urlencoded content type. The body of that type is encoded as a String, so you cannot append binary data via Ktor's API.

Here is a good answer that explains the difference between multipart/form-data and application/x-www-form-urlencoded.

Aleksei Tirman
  • 4,658
  • 1
  • 5
  • 24