我需要从Android内容URI中获取文件名,例如:
content://com.android.providers.downloads.documents/document/15
我尝试使用React Native FS stat,但它返回“文件不存在”的错误。
我该怎么做呢?
我需要从Android内容URI中获取文件名,例如:
content://com.android.providers.downloads.documents/document/15
我尝试使用React Native FS stat,但它返回“文件不存在”的错误。
我该怎么做呢?
我在React Native中没有找到纯解决方案,因此我创建了一个Android原生包,并从中创建了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);
}
}
也许:
let filename = uri.substring(uri.lastIndexOf('/') + 1, uri.length)
DocumentFile.fromSingleUri()
和getName()
函数来获取与由Uri
标识的内容相关联的“显示名称”。我不知道是否有人为此创建了React Native包装器。 - CommonsWare