0

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?

Ankit Verma
  • 496
  • 5
  • 21
  • You should save Uri's content (using openInputStream) in your cacheDir of filesDir temporarily & then send via Retrofit. – Darshan Dec 04 '21 at 14:37
  • "How do I convert them to file?" -- you do not need a file, most likely. "Is there any other method to send images to server via Retrofit2?" -- you can use a `RequestBody` that works with your `Uri`. See [this](https://commonsware.com/blog/2020/07/05/multipart-upload-okttp-uri.html) and [this](https://cketti.de/2020/05/23/content-uris-and-okhttp/). – CommonsWare Dec 04 '21 at 15:18

2 Answers2

2

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
        }
    }
Ankit Verma
  • 496
  • 5
  • 21
  • I got "unresolved reference: context". How will it recognize context? – thelamp Jul 18 '22 at 22:18
  • @thelamp you can pass context in the function parameter if you are calling it from an activity/fragment or get the application context there if you are using a viewModel extended from AndroidViewModel. – Ankit Verma Jul 20 '22 at 07:28
-2

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

Mr. G
  • 1
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 04 '21 at 17:13