1

How to upload File using kotlin coroutines (retrofit).

Is it possible that i send using syntax similar to this for sending files to server? The current multipart upload seems to be taking a lot of extra code for creating MultipartBody.body and sending to server. Is there any reason for the same ?

Code syntax that i am trying.

data class AddCategoryRequest(
    val name: String,
    val image: File?,
    val subCategory: Boolean,
    val parentCategoryId: Int
)

/**
  * Category Create API Call
  */
@POST(Urls.SUB_URL_CREATE_CATEGORY)
suspend fun createCategory(
    @Body createCategoryRequest: AddCategoryRequest
): Category

1 Answers1

0

This is how I'm uploading a file in Kotlin with Retrofit + Coroutines:

@PUT("")
suspend fun uploadFile(@Url url: String, @Body body: RequestBody)

And call it like this:

private suspend fun uploadFile(
    localFileEntry: LocalFileEntry,
    file: File
) {
    val requestBody: RequestBody =
        file.asRequestBody("image/jpeg".toMediaTypeOrNull())
    kotlin.runCatching {
        apiInterface.uploadFile(fileUploadInfo.url, requestBody)
    }.onFailure {
        it.printStackTrace()
    }
}