Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to upload images from cameraRoll. Thing is the cameraRoll component returns content:// URI rather than an actual file path. For uploading the image I need a file path, is there any way to convert content:// URI to file URI? Thanks

like image 690
cubbuk Avatar asked Mar 28 '16 09:03

cubbuk


People also ask

How do I get the absolute file path in react native?

The most convenient way : Use react-native-document-picker, on selection it will give you a Relative path, something like this content://com.android...... . Pass that Relative path to Stat(filepath) function of the react-native-fetch-blob library. The object will return absolute path.

How do I read file content in react native?

below code is about how to read the file by react-native-fs on RN(React Native) project. ... // typescript style import * as RNFS from 'react-native-fs'; ... // readFile(filepath: string, encoding?: string) RNFS. readFile(filePath, 'ascii'). then(res => { ... }) .


3 Answers

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)
  )
)
like image 189
Antoni4 Avatar answered Oct 10 '22 08:10

Antoni4


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

like image 8
fujianjin6471 Avatar answered Oct 10 '22 07:10

fujianjin6471


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;
    }
like image 2
Madhukar Hebbar Avatar answered Oct 10 '22 07:10

Madhukar Hebbar