Get File from URI

from the CommonsWare Community archives

At November 9, 2021, 5:39pm, grrigore asked:

I’m having a hard time getting a File’s path from a URI. The scenario is the following:

user picks an image from the gallery and that yields a URI. However, I need to get the file path in order to get some data regarding the file size, etc.

I’m thinking about getting the bytes using the URI and creating a temporary file with those bytes. Is this a good approach?


At November 9, 2021, 5:58pm, mmurphy replied:

A Uri is not a file. For example, https://community.commonsware.com/t/get-file-from-uri/624 is a Uri. It might not be a file on any filesystem on any computer on the planet.

The details here matter. What exactly is your approach for doing this?

The details here matter. Depending on how you are getting the Uri, you might be able to use DocumentFile or MediaStore to get the size of the content. And it is unclear what is covered in “etc.”.

There are scenarios where that is needed (e.g., an import operation to add the image to your app, in a way that it survives the original image being deleted). However, without the details, it is difficult to answer the question.


At November 9, 2021, 7:45pm, grrigore replied:

This is how I’m doing right now:

val getIntent = Intent(Intent.ACTION_GET_CONTENT)
getIntent.type = "image/*"

val pickIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
pickIntent.type = "image/*"

val chooserIntent = Intent.createChooser(getIntent, "Select Image")
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayOf(pickIntent))

Will check this out. Thank you!


At November 9, 2021, 8:01pm, mmurphy replied:

While ACTION_GET_CONTENT and ACTION_PICK return Uri values, their originating providers will be substantially different. I do not know if DocumentFile will work with one from ACTION_PICK.

You can query() a ContentResolver given the Uri from either source, though, and query on the OpenableColumns to get a display name and a size. In principle, I would expect that to work for Uri values from both sources.


At November 9, 2021, 8:06pm, grrigore replied:

Thank you! I understand. However, in older android versions there were methods like

that used to work.


At November 9, 2021, 8:35pm, mmurphy replied:

That second link is not horrible. For example, it queries for the OpenableColumns to get a display name.

The first link’s approach only ever worked if the scheme of the Uri is file. For any other scheme, all bets are off as to what the path means. So, for example, https://community.commonsware.com/t/get-file-from-uri/624/5 is a Uri, but /t/get-file-from-uri/624/5 is not a relevant filesystem path on any computer.

With regards to your two Intent actions:


At November 9, 2021, 8:38pm, grrigore replied:

I think I got it! Thank you for your time!