I want send profile image to server i use retrofit with jetpack compose, but i get this error: 400 Required Part [image] not specified can u help me?
My composable
val photoPicker = rememberLauncherForActivityResult(
contract = ActivityResultContracts.PickVisualMedia(),
) { uri ->
if (uri != null) {
if (Build.VERSION.SDK_INT < 28) {
profileImageBitmap.value =
MediaStore.Images.Media.getBitmap(ctx.contentResolver, uri)
} else {
val source = ImageDecoder.createSource(ctx.contentResolver, uri)
profileImageBitmap.value = ImageDecoder.decodeBitmap(source)
mainViewModel.uploadMyPhotoRequest(profileImageBitmap.value!!)
}
}
}
My VM
fun uploadMyPhotoRequest(image: Bitmap) {
val stream = ByteArrayOutputStream()
image.compress(Bitmap.CompressFormat.JPEG, 80, stream)
val byteArray = stream.toByteArray()
val body = MultipartBody.Part.createFormData(
"avatar", "photo",
byteArray.toRequestBody("image/jpeg".toMediaTypeOrNull(), 0, byteArray.size)
)
viewModelScope.launch {
try {
apiService.uploadPhoto(body)
} catch (e: Exception) {
e.message
}
}
}
apiService
@Headers("Content-Type: multipart/form-data")
@Multipart
@POST("photo")
suspend fun uploadPhoto(@Part image: MultipartBody.Part)
i try this and get 400 code Build.VERSION.SDK_INT > 28 not watch on code < api 28
You are declaring your body as
val body = MultipartBody.Part.createFormData(
"avatar", "photo",
byteArray.toRequestBody("image/jpeg".toMediaTypeOrNull(), 0, byteArray.size)
)
The error is
Required Part [image] not specified
So, shouldn't you specify "image"
instead of "avatar"
?