How to upload image file using retrofit with jetpack compose android

723 Views Asked by At

I want to upload image file on server using retrofit2 in android jetpack compose. I try but i can't do this. My code is here

# api interface**
interface ImageService {
    @Multipart
    suspend fun uploadImage(
        @Part image: MultipartBody.Part,
    )
}

repository**

class ImageRepository @Inject constructor (private val imageService: ImageService) {

    suspend fun uploadImage(file: File) : Boolean {
        return try {
            imageService.uploadImage(
                image = MultipartBody.Part
                    .createFormData(
                        "image",
                        file.name,
                        file.asRequestBody()
                    )
            )
        
            true
        } catch (e: IOException) {
            e.printStackTrace()        
            false
        } catch (e: HttpException) {
            e.printStackTrace()
            false
        }

    }
}

view model**

    fun uploadImage(file: File) {

        viewModelScope.launch {
           imageRepository.uploadImage(file)
        }
}

Screen**

@Composable
fun PickImage() {

    val context = LocalContext.current
    val imageViewModel = viewModel<ImageViewModel>()


    Column {

        val imageUri = remember { mutableStateOf<Uri?>(null) }

        val launcher = rememberLauncherForActivityResult(
            contract = ActivityResultContracts.GetContent(),
            onResult = {
                imageUri.value = it
            }
        )

        if (imageUri.value != null) {
            Image(
                painter = rememberAsyncImagePainter(model = imageUri.value),
                contentDescription = null,
                modifier = Modifier.size(200.dp)
            )
        }
        Spacer(modifier = Modifier.height(10.dp))
        Button(onClick = {
            launcher.launch("image/*")
        }) {
            Text(
                text = "Gallery",
                fontWeight = FontWeight.Bold,
                fontSize = 30.sp
            )
        }

        //Upload
        Button(onClick = {

            val inputStream = context.contentResolver.openInputStream(imageUri.value!!)

            val file = File(context.cacheDir, "mage.png")
            file.createNewFile()
            file.outputStream().use {
                inputStream!!.copyTo(it)
            }

            imageViewModel.uploadImage(file)

        }) {
            Text(text = "Upload")
        }
    }
}

I also tried to upload file using xml and kotlin. So with kotlin the file upload successfully. But when I use compose i face problem. Can any one have idea about this. Kindly share with me. Thanks!

0

There are 0 best solutions below