How to convert content uri to file?

1.3k views Asked by At

I want to send multiple images to my database using retrofit. I am using this code to select multiple images.

  private val galleryLauncher =
        registerForActivityResult(ActivityResultContracts.GetMultipleContents()) { list ->
            //TODO  convert all content uris to File
        }

I have tried a bunch of image picker libraries but none of them works in my device (Android R). How do I convert them to file? Please help.

Is there any other method to send images to server via Retrofit2?

2

There are 2 answers

2
Ankit Verma On BEST ANSWER

I used this dependency

 implementation "commons-io:commons-io:2.7"

And this method

private fun createFileFromUri(name: String, uri: Uri): File? {
        return try {
            val stream = context.contentResolver.openInputStream(uri)
            val file =
                File.createTempFile(
                    "${name}_${System.currentTimeMillis()}",
                    ".png",
                    context.cacheDir
                )
            FileUtils.copyInputStreamToFile(stream, file)  // Use this one import org.apache.commons.io.FileUtils
            file
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }
1
Mr. G On

private val galleryLauncher = registerForActivityResult(ActivityResultContracts.GetMultipleContents()) { list -> //TODO convert all content uris to File }