david890ch
david890ch

Reputation: 197

React Native - Get file name from android content uri


I need to get file name from android content uri, for example:
content://com.android.providers.downloads.documents/document/15

I try to used react-native-fs stat but it return error of "File does not exist".

How can I do it?

Upvotes: 3

Views: 7565

Answers (2)

Asiel Alonso
Asiel Alonso

Reputation: 579

maybe:

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

Upvotes: 0

david890ch
david890ch

Reputation: 197

I not found pure solution in react native, so I created native package in android and created module in react native from so I can use it.
This the the android code:

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

This is how to module in react native from android native code: react-native-modules-android

Upvotes: 2

Related Questions