Search code examples
androidkotlinretrofit

Retrofit post api with multipart list


As we can send list of Request body to api call in retrofit like below

@POST("task/updatedropoff")
    @Multipart
    fun taskUpdateDropOff(
        @Header("apikey") token: String,
        @PartMap user: HashMap<String, RequestBody>,
        @Part image1: MultipartBody.Part? = null,
    ): Call<BaseClass<String>>?

How can we send the list of Parts same as the list of Request body?

I have searched it in retrofit library, android and stack but to no solution.


Solution

  • You can use @Part List<MultipartBody.Part> to send a list of parts. Each part of the list can represent different files or data. The key is constructing a list of MultipartBody.Part objects for each item you want to send.

    Here is an example below how you can upload it.

    interface ApiService {
        @Multipart
        @POST("upload")
        suspend fun uploadFiles(
            @Part files: List<MultipartBody.Part>
        ): Response<ResponseBody>
    }
    

    for creating list:

    fun createMultipartList(fileUris: List<Uri>, context: Context): List<MultipartBody.Part> {
        val parts = mutableListOf<MultipartBody.Part>()
        
        fileUris.forEach { uri ->
            val file = File(uri.path)
            val requestBody = file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
            val part = MultipartBody.Part.createFormData("file", file.name, requestBody)
            parts.add(part)
        }
        
        return parts
    }