https://kotlinlang.org logo
#ktor
Title
# ktor
r

ritesh

05/29/2020, 12:27 PM
Hey folks 👋 I’m facing some issues with sending multipart data using Ktor for a multiplatform project. Basically I’m converting the image to
ByteArray
and then passing it in the multipart block but server is not accepting it as a multipart request but sees it like a regular post call (and the API is working fine on postman),
Copy code
val data: ByteArray = ...
val urlString: String = ...
httpClient.request<T>(urlString) {
    method = <http://HttpMethod.Post|HttpMethod.Post>
	body = MultiPartFormDataContent(
    	formData {
        	append("avatar", data)
    	}
	)
}
Can someone point me to right direction what could be wrong/missing here? Is there some other way to upload an image? Do we have to manually set
"Content-Type"
as
multipart/form-data
somewhere? 🤔
e

e5l

05/29/2020, 3:39 PM
Hi, sorry for the delay! If your server doesn’t accept multipart you can send it as
ByteArrayContent
body with
Content-Type
param u need.
r

ritesh

05/29/2020, 5:36 PM
Thanks for following up 🙌 Actually my server does support multi-part but its just that I’m not able to correctly form the multi-part payload so was wondering if you see anything wrong with the above snippet?
I tested it with both postman and an iOS library and the request works fine but when sending it via Ktor is returning an error where the server doesn’t recognise it as a multi-part request.
Sharing the solution (at least what worked for me, working with a Django server) for someone who might need it in future. So apparently we need to send
Content-Disposition
as header for multipart to work.
Copy code
body = MultiPartFormDataContent(
    formData {
        append(
            "avatar",
            data,
            Headers.build {
                append(HttpHeaders.ContentDisposition, "filename=<name>")
            }
        )
    }
)
👏 4
3 Views