PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 31, 2022

[FIXED] How to convert content uri to file?

 July 31, 2022     android, file-upload, kotlin, retrofit2.6, uri     No comments   

Issue

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?


Solution

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
        }
    }


Answered By - Ankit Verma
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing