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
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.
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 => { ... }) .
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)
)
)
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With