Search code examples
androidimagefileuploadretrofit

Select image and upload to server android


I want to upload the image to server by selecting from gallery

Opening gallery by

val pickPhoto = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startForResult.launch(pickPhoto)

And then activity result

val startForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult())
{ result: ActivityResult ->
    if (result.resultCode == Activity.RESULT_OK) {
        //  you will get result here in result.data
        if(result.data!=null){
            val f=File(result.data.toString())
            println(f.absolutePath)
        }
    }

}

However I think the file is not correct.

My api call is like

@Multipart
@PUT
fun uploadFile(
    @Url url:String,
    @Part("file") name: RequestBody,
    @Part filepart: MultipartBody.Part
): Response<String>

And I am calling this as

val fileToUpload: MultipartBody.Part =
            MultipartBody.Part.createFormData("file", file.getName())
        val filename: RequestBody =
            file.getName().toRequestBody("text/plain".toMediaTypeOrNull())
        Api.uploadFile(uploadUrl,filename,fileToUpload) 

Its a stream upload


Solution

  • Issue was due to URI only as it was not getting the correct absolute path of file

    to retrive the absolute path

    private fun getRealPathFromURI(contentURI: Uri): String {
        val result: String
        val cursor: Cursor? = requireContext().contentResolver.query(contentURI, null, null, null, null)
        if (cursor == null) {
            result = contentURI.getPath().toString()
        } else {
            cursor.moveToFirst()
            val idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
            result = cursor.getString(idx)
            cursor.close()
        }
        return result
    }
    

    The activity result

    val startForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult())
    { result: ActivityResult ->
        if (result.resultCode == Activity.RESULT_OK) {
            //  you will get result here in result.data
            if(result.data!=null){
                val f=File(getRealPathFromURI(result.data?.data!!))
                viewModel.uploadCheque(f)
            }
        }
    
    }