繁体   English   中英

React Native - 从 android 内容 uri 获取文件名

[英]React Native - Get file name from android content uri


我需要从 android 内容 uri 中获取文件名,例如:
内容://com.android.providers.downloads.documents/document/15

我尝试使用 react-native-fs stat 但它返回“文件不存在”的错误。

我该怎么做?

我没有在 react native 中找到纯粹的解决方案,所以我在 android 中创建了 native package 并在 react native 中创建了模块,所以我可以使用它。
这是 android 代码:

@ReactMethod
    public void getFileNameFromUri(String filepath, Promise promise) {
        Uri uri = Uri.parse(filepath);
        String fileName = "";

        if (uri.getScheme().equals("content")) {
            try {
                Cursor cursor = reactContext.getContentResolver().query(uri, null, null, null, null);

                if (cursor.moveToFirst()) {
                    fileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                    Log.d("FS", "Real File name: " + fileName);
                }
                cursor.close();
                promise.resolve(fileName);
            } catch (IllegalArgumentException ignored) {
                promise.reject("1", "Can not get cursor");
            }
        } else {
            promise.resolve(fileName);
        }
    }

这是如何从 android 本机代码模块化反应本机: react-native-modules-android

可能是:

let filename = uri.substring(uri.lastIndexOf('/') + 1, uri.length)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM