cubbuk
cubbuk

Reputation: 7920

Convert content:// URI to actual path for Android using React-Native

I am trying to upload images from cameraRoll. But the cameraRoll component returns a content:// URI, rather than an actual file path.

For uploading the image I need a file path, is there any way to convert a content:// URI to a file URI?

Example content URI:

content://com.miui.gallery.open/raw/%2Fstorage%2Femulated%2F0%2FAndroid%2Fdata%2Fcom.miui.gallery%2Fcache%2FSecurityShare%2L78963157412.jpg

Upvotes: 20

Views: 22452

Answers (3)

fujianjin6471
fujianjin6471

Reputation: 5248

You can use react-native-fs's copyFile method to convert content uri to file uri.

if (url.startsWith('content://')) {
    const urlComponents = url.split('/')
    const fileNameAndExtension = urlComponents[urlComponents.length - 1]
    const destPath = `${RNFS.TemporaryDirectoryPath}/${fileNameAndExtension}`
    await RNFS.copyFile(url, destPath)
}

Then you can use 'file://' + destPath as expected

Upvotes: 10

Antoni4
Antoni4

Reputation: 2693

I took the function submitted by @Madhukar Hebbar and made it into a React Native Node Module.

You can find it here: react-native-get-real-path

Thus to achieve what you want, you can use the above module in conjunction with react-native-fs

You can then do something like this when you want to upload the selected image from Camera Roll:

RNGRP.getRealPathFromURI(this.state.selectedImageUri).then(path =>
  RNFS.readFile(path, 'base64').then(imageBase64 =>
    this.props.actions.sendImageAsBase64(imageBase64)
  )
)

Upvotes: 12

Madhukar Hebbar
Madhukar Hebbar

Reputation: 3173

Pass the content:// URI to below method to get the file path as string and then use the file object to do any operation.

File file = new File(getURIPath(uriValue));

/**
 * URI Value
 * @return File Path.
 */
String getURIPath(Uri uriValue) 
    {
        String[] mediaStoreProjection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uriValue, mediaStoreProjection, null, null, null);
        if (cursor != null){ 
        int colIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String colIndexString=cursor.getString(colIndex);
        cursor.close();
        return colIndexString;
        }
        return null;
    }

Upvotes: 2

Related Questions