0

enter image description here

I want to upload a pdf file with other fields using Retrofit2. But I don't know how to create a request body for it.

  @POST("filebase/upload")
suspend fun uploadPdfDocument(@Header(HEADER_AUTHORIZATION) authorization: String, @Body requestBody: RequestBody): UploadPdfDocumetResponse?

Please help me!

Parag Rane
  • 179
  • 4
  • 15

1 Answers1

1

If in your dependencies exists okhttp3 then you can use this beautiful extenstion function

import okhttp3.RequestBody.Companion.asRequestBody

yourPdfFile.asRequestBody(yourPdfFile.getExtension())

getExtension() function below

fun File.getExtension(): MediaType? {
    var type: String? = null
    val encoded: String = try {
        URLEncoder.encode(name, "UTF-8").replace("+", "%20")
    } catch (e: Exception) {
        name
    }
    val extension = MimeTypeMap.getFileExtensionFromUrl(encoded)
    if (extension != null) {
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)
    }

    return type?.toMediaType()
}