I am Using ktor with kmm to upload a list of images to server But there is no available guide in the docs to make me upload list of files i am converting my files to byte array and uploading them
I tried to upload it this way
mainClient.post {
setBody(
MultiPartFormDataContent(
formData {
append("attachments[]", listOf(toBytes(kmmFile),toBytes(kmmFile)) )
}
)
)
}
but got connection refused
CodePudding user response:
You can iterate through all byte arrays in a collection and call the append
method for each of them. Here is an example:
val images: List<ByteArray> // assigned externally
val response = client.post("https://httpbin.org/post") {
setBody(MultiPartFormDataContent(
formData {
for (bytes in images) {
append("attachments[]", bytes)
}
}
))
}
CodePudding user response:
I use below code for uploading single file and run forEach when call this method(for each n append doesn't work for me). I think your serve must be supported upload multiple file at same time.
override suspend fun upload(
uploadFiles: Map<String, File>,
texts: Map<String, String>
): ResultWrapper<ResponseData<List<UploadFileDto>>> {
return {
httpClient.submitForm {
url(BASE_URL "api/v1/static/upload-file")
method = HttpMethod.Post
setBody(MultiPartFormDataContent(
formData {
headers {
append(
"document",
uploadFiles.entries.first().value.readBytes(),
Headers.build {
append(
HttpHeaders.ContentDisposition,
"filename=${uploadFiles.entries.first().value.name}"
)
})
}
}
))
}.body()
}