Search code examples
androidretrofitmultipartform-data

How to send multipart with images using Retrofit2?


I need to send the same data from the following image (Postman)

enter image description here

I'm using Retrofit with Coroutines, I tried to use the following snippet to send the request:

@POST("ia")
@Multipart
suspend fun getMeasurement(
    @HeaderMap authenticationHeaders: ApiHeaders,
    @Part("userId") userId: RequestBody,
    @Part("sessionId") sessionId: RequestBody,
    @Part file: MultipartBody.Part,
    @Part file2: MultipartBody.Part,
    @Part file3: MultipartBody.Part,
    @Part file4: MultipartBody.Part,
): Response<MeasurementResponse>

To create the MultipartBody.Part

fun createImageRequestBody(imageUri: Uri, fileName: String): MultipartBody.Part? {
        context.contentResolver?.query(imageUri, null, null, null, null)?.use {
            if (it.moveToFirst()) {
                val picturePath =
                    it.getString(it.getColumnIndex(MediaStore.MediaColumns.DATA))

                val requestBody = File(picturePath).asRequestBody("image/jpeg".toMediaTypeOrNull())
                return MultipartBody.Part.createFormData(
                    "file",
                    "${fileName}.jpeg",
                    requestBody
                )
            }
        }
        return null
    }

to create the other parameters

val userId = user.id.toRequestBody("text/plain".toMediaTypeOrNull())

val sessionId = session.id.toRequestBody("text/plain".toMediaTypeOrNull())

I don't know why this results in an error 413 (entity too large) from the server, and it works fine when I try via Postman. What I'm doing wrong?


Solution

  • I solved the problem just by removing HeaderMap from the parameters, but I don't know why.