使用React-Native将content:// URI转换为实际路径的方法(与Android相关的IT技术问题)

17

我正在尝试从相机胶卷上传图片。问题在于,相机胶卷组件返回的是content:// URI而不是实际的文件路径。为了上传图像,我需要一个文件路径,有没有办法将content:// URI转换为文件URI呢?谢谢。


为什么需要路径?难道你不能使用InputStream作为例子吗? - pskink
我正在开发一个React-Native应用程序,使用Java方法有点麻烦,因此我正在寻找一种React Native解决方案。谢谢。 - cubbuk
3个回答

12
我采用了@Madhukar Hebbar提交的函数,并把它制成了React Native节点模块。
您可以在此处找到它: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)
  )
)

你是个救星!只有一个问题 - 因为它只适用于安卓 - 需要将 require package 行放在平台检查逻辑内部。但与其提供的效用相比,我可以忽略这一点。 :-) - Himel Nag Rana
我使用了你的库,但是它没有起作用。我得到一个错误,undefined is not a function(reactNativeGetRealPath2.default.getRealPathFromUri(path)),而我提供的路径是content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F890/ORIGINAL/NONE/225703422 - P.Lorand
4
有没有一个库可以同时支持iOS和Android? - YLS

9

你可以使用react-native-fscopyFile方法将内容uri转换为文件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)
}

然后你可以按预期使用 'file://' + destPath


请注意:
  1. 代码中有几个变量名错误。
  2. 如果您的文件名中含有“%”符号,则无法上传。因此,请替换这些字符。
- Om Sao

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

1
我该如何修改这个函数,使其能够处理所有文件类型,例如文档和视频文件? - LordDraagon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接