Content URI to absolute path in React native ( ANDROID )
const isInternalStorage = res?.uri.startsWith('content://com.android.externalstorage.documents/tree/primary');
const isSdCardStorage = res?.uri.startsWith('content://com.android.externalstorage.documents/tree/') && !isInternalStorage;
to convert the path from content URI to absolute to read file or directory using react-native-fs library
For SD card reading ->
const convertExternalStoragePathToAbsolutePath = (path: string) => {
let dirToRead = path.split('tree')[1];
dirToRead = '/storage' + dirToRead.replace(/%3A/g, '%2F');
// console.log("prePath:",path ,"cov: ",dirToRead)
return decodeURIComponent(dirToRead);
}
For Internal Storage reading->
const convertInternalStoragePathToAbsolutePath = (path: string) => {
let dirToRead = path?.split('primary')[1];
const InternalStoragePath = RNFS.ExternalStorageDirectoryPath;
dirToRead = InternalStoragePath + dirToRead.replace(/%3A/g, '%2F');
// console.log("prePath:",path ,"cov: ",decodeURIComponent(dirToRead))
return decodeURIComponent(dirToRead);
}
Results
Sd card ->
From react-native-directory-picker we'll get -
ContentURI = content://com.android.externalstorage.documents/tree/777B-
D380%3ADownload
absolute path = /storage/777B-D380/Download
This absolute path can be used with react-native-fs to read files
Internal Storage ->
ContentURI= content://com.android.externalstorage.documents/tree/primary%3ADownload%2FMeet
absolute path = /storage/emulated/0/Download/Meet
example to read all the videos from a directory
const searchFiles = async (path: string) => {
const files = await RNFS.readDir(path);
const videoFiles = files.filter(file => {
const fileExtension = file.name.split('.').pop();
return ['mp4', 'avi', 'mov', 'mkv','ts'].includes(fileExtension ?? '');
});
setVideoList(videoFiles);
// save it inside storage
storage.save({
key: 'videoList',
data: videoFiles,
}).then(() => {
console.log("videoList saved successfully");
})
console.log("Directory changed ");
}