使用React-Native将content:// URI转换为Android的实际路径

时间:2016-03-28 09:19:50

标签: android react-native react-native-camera

我正在尝试从cameraRoll上传图片。事情是cameraRoll组件返回content:// URI而不是实际的文件路径。要上传图像,我需要一个文件路径,有没有办法将content:// URI转换为文件URI?感谢

3 个答案:

答案 0 :(得分:6)

我接受了 @Madhukar Hebbar 提交的功能,并将其变成了React Native Node Module。

您可以在此处找到它:react-native-get-real-path

因此,要实现您的目标,您可以将上述模块与react-native-fs

结合使用

当您想要从相机胶卷上传所选图像时,您可以执行以下操作:

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

答案 1 :(得分:1)

content:// URI传递给下面的方法,将文件路径作为字符串,然后使用文件对象进行任何操作。

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;
    }

答案 2 :(得分:1)

您可以使用react-native-fs的{​​{1}}方法将内容uri转换为文件uri。

copyFile

然后您可以按预期使用if (url.startsWith('content://')) { const uriComponents = url.split('/') const fileNameAndExtension = urlComponents[uriComponents.length - 1] const destPath = `${RNFS.TemporaryDirectoryPath}/${fileNameAndExtension}` await RNFS.copyFile(uri, destPath) }

相关问题