Search code examples
androidgoogle-cloud-storage

Open File from Uri using media picker in Android


I'm using rememberLauncherForActivityResult to get an image as Uri using Modifier.clickable { launcher.launch("image/*") }.

Following https://firebase.google.com/docs/storage/android/upload-files#upload_from_a_local_file , I'm doing the equivalent of:

val file = Uri.fromFile(File(imagePath))
val uploadTask = eventImageRef.putFile(file)

where imagePath is equivalent to imageUri.path where imageUri is just the Uri obtained from rememberLauncherForActivityResult linked to the image the user selects with media picker.

However, when trying to upload, ENOENT is raised:

Caused by: java.io.FileNotFoundException: /picker_get_content/0/com.android.providers.media.photopicker/media/1000006961: open failed: ENOENT (No such file or directory)

indeed, the Uri as File() does not exist and the system is unable to find it.

My question is: how can I treat the Uri as a File? imageUri.toFile() crashes the application.


Solution

  • how can I treat the Uri as a File?

    A Uri does not have to point to a file on the filesystem, let alone one that your app has direct filesystem access to.

    Instead of using putFile(), you could try using putStream(). You can use ContentResolver and its openInputStream() method to get an InputStream that you can use with putStream().