Skip to content

Instantly share code, notes, and snippets.

@felipefpx
Created August 13, 2020 01:41
Show Gist options
  • Save felipefpx/b22dcaf506ee9c094415f58928444012 to your computer and use it in GitHub Desktop.
Save felipefpx/b22dcaf506ee9c094415f58928444012 to your computer and use it in GitHub Desktop.
Upload files using OkHttp multi-part request
fun uploadFile(
url: String,
headers: Map<String, String>,
files: Map<String, Attachment>,
formDataParts: Map<String, Any>
): Request {
val body =
MultipartBody.Builder()
.setType(MultipartBody.FORM)
.apply {
formDataParts.forEach { (key, value) -> addFormDataPart(key, value.toString()) }
files.forEach { (field, attachment) ->
addFormDataPart(
field,
attachment.file.name,
attachment.file.asRequestBody(attachment.mediaType.toMediaTypeOrNull())
)
}
}
.build()
return Request.Builder()
.url(url)
.addHeader("Content-Type", "multipart/form-data")
.apply { headers.forEach { (name, value) -> addHeader(name, value) } }
.post(body)
.build()
}
class Attachment(
val file: File,
val mediaType: String
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment