Compressing an Image in Kotlin Failed to read the request form. Multipart body length limit 16384 exceeded Message

55 Views Asked by At

I am trying to compress a file to pass it to the api call but I keep getting the Multipart body length limit 16384 exceeded Message returning from the api call here is the code I have tried. How can I compress the size of the image being uploaded by the user in kotlin. I have also tried using Picasso but it also does not seem to work I keep getting the same message


class RegisterProductAddPhotosViewModel : ViewModel() {
    private lateinit var ctx: Context
    private lateinit var retrofitClient: RetrofitClient
    fun setContext(ctx: Context) {
        this.ctx = ctx
        retrofitClient = RetrofitClient(ctx)
    }

    private fun prepareFilePart(file: File, partName: String, mimeType: String?, fileName: String): MultipartBody.Part {
        val requestBody = file.asRequestBody(mimeType?.toMediaTypeOrNull())
        return MultipartBody.Part.createFormData(partName, fileName, requestBody)
    }


    fun loginUser(email: String, password: String, callback: LoginCallBack) {
        try {
            val retrofitBuilder = Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Constants.baseURL)
                .build()
                .create(APIRequest::class.java)

            val request = AuthenticationLoginRequest(email, password)
            val retrofitData = retrofitBuilder.login(request)

            retrofitData.enqueue(object : Callback<AuthenticationLoginDataResponse> {
                override fun onResponse(
                    call: Call<AuthenticationLoginDataResponse>,
                    response: Response<AuthenticationLoginDataResponse>
                ) {
                    val responseBody = response.body()

                    if (responseBody?.success == true) {
                        val token = responseBody.data?.accessToken ?: ""
                        callback.onTokenReceived(token)
                    } else {
                        val errorMessage = responseBody?.message ?: "Unknown error"
                        callback.onError(errorMessage)
                    }
                }

                override fun onFailure(call: Call<AuthenticationLoginDataResponse>, t: Throwable) {
                    callback.onError(t.message ?: "Unknown error")
                }
            })
        } catch (e: Exception) {
            callback.onError(e.message ?: "Unknown error")
        }
    }

    private fun getMimeType(file: File): String? {
        val extension = file.extension.lowercase()
        return when (extension) {
            "jpg", "jpeg" -> "image/jpeg"
            "png" -> "image/png"
            "gif" -> "image/gif"
            "pdf" -> "application/pdf"
            "svg" -> "image/svg+xml"
            // Add more mime types for other file formats if needed
            else -> null
        }
    }


    fun handleSelectedFile(productId: Int, file: File, filename: String, token: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                Log.e("tag", "Product id: $productId")

                // Compress the image using the Compressor library
                val compressedImageFile = Compressor.compress(ctx, file)

                // Prepare the file part
                val fileRequestBody = compressedImageFile.asRequestBody(getMimeType(compressedImageFile)?.toMediaTypeOrNull())
                val filePart = MultipartBody.Part.createFormData("file", filename, fileRequestBody)


                // Create the content disposition header
                val contentDisposition = MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("Content-Disposition", "form-data; name=\"file\"; filename=\"$filename\"")
                    .build()

                val multipartBodyLength = contentDisposition.contentLength()

                Log.e("tag", "Multipart body length: ${contentDisposition.contentLength()}")
                // Create the API request
                val apiRequest = RetrofitClient(ctx).createAPIRequestWithToken(token)

                // Make the API call
                Log.e("tag", "Content Disposition: $contentDisposition")
                val response = apiRequest.addPhotos(contentDisposition, filePart, productId)

                response.enqueue(object : Callback<ProductPostResponse> {
                    override fun onResponse(call: Call<ProductPostResponse>, resp: Response<ProductPostResponse>) {
                        val responseBody = resp.body()
                        Log.e("tag", "Whole Response: $responseBody")
                        Log.e("tag", "Response success message: ${resp.message()}")
                        if (resp.isSuccessful) {
                            // Handle the response as needed
                        } else {
                            // Handle error response
                        }
                    }

                    override fun onFailure(call: Call<ProductPostResponse>, t: Throwable) {
                        // Handle exceptions here
                        Log.e("tag", "Exception: ${t.message}")
                    }
                })

            } catch (e: IOException) {
                // Handle exceptions here
                Log.e("tag", "Exception: ${e.message}")
            }
        }
    }


}
0

There are 0 best solutions below