3

I'm using react-native-document-picker in order to pick files and send them to the server. After picking the file, I use RNFetchBlob.fs.stat(uri) from rn-fetch-blob package to get the real path from the URI that the picker gives me. It works fine with internal storage files but when I choose an image from "SD card" section the stat function throws an exception which says something like this:

failed to stat path null for it doesn't exist or it's not a folder

Surprisingly, when I choose "Images" section and go to the SD card folder and choose the very same image it works just fine!! I have the same problem with "Downloads" section, too.

enter image description here

The URI that the picker returns is this when I choose the image from "Images" section:

content://com.android.providers.media.documents/document/image%3A76431

and when I choose from "SD card" section: content://com.android.externalstorage.documents/document/F673-1818%3Abbb.png

Right now I'm using this code but it's not the right solution because it's somehow dirty and it doesn't work on all devices.

if(uri.substr(0,57) === "content://com.android.externalstorage.documents/document/"){
    let filePath = decodeURIComponent(uri.substr(57));
    let subUri = filePath.replace(/:\s*/g, "/");
    filePath = "/storage/" + subUri;
    return `file://${filePath}`
 }

Is there a nicer way to get the real path of a file in SD card from it's URI? I appreciate any idea.

OS: Android

Shashanth
  • 4,995
  • 7
  • 41
  • 51
Zeynab Rostami
  • 423
  • 4
  • 13
  • I think this is what you need `Environment.getExternalStorageDirectory()` – Vikas Acharya Feb 10 '20 at 09:46
  • plz check this answer https://stackoverflow.com/a/42160238/1992013. I think it's still valid despite various Android classes/packages updates. – Birender Singh Feb 10 '20 at 10:19
  • 1
    Do not use such things as get real path from uri. Use the uri as it is. There is no reason not to use the content scheme directly. So please tell why you want a 'real' path. Even if you get all to wortk its useless for Android Q and later. So adapt to modern times. – blackapps Feb 10 '20 at 13:28
  • check this link https://stackoverflow.com/questions/23123461/external-sdcard-file-path-for-android – Shivo'ham 0 Feb 10 '20 at 16:27
  • check this link https://stackoverflow.com/questions/23123461/external-sdcard-file-path-for-android – Shivo'ham 0 Feb 10 '20 at 16:31
  • @blackapps I want to upload the files to my server. Without the real path, it sends 0 bytes files ! You have a solution for that? – Zeynab Rostami Feb 24 '20 at 10:33
  • You can upload files without a `real path'. Use the uri to open an input stream and read the bytes from the file and then upload those bytes. – blackapps Feb 24 '20 at 10:52

0 Answers0