我想附加 Android 存储中的图像或视频文件。当我从图库中选择视频时,它会返回内容 uri 路径。
如何从内容 URI 中获取带有扩展名的文件路径?
我试过下面的代码,但它在 lollipop 中返回 null:
void pickVideo() {
Intent videoIntent = new Intent(Intent.ACTION_GET_CONTENT);
videoIntent.setType("video/*");
startActivityForResult(videoIntent, PICK_VIDEO_FILE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case PICK_VIDEO_FILE:
Uri videoUri = data.getData();
String path = getRealPathFromURI(getContext(), videoUri);
Log.d("Video uri path", "path" + path);
if (mChooseFileDialogListener != null) {
mChooseFileDialogListener.onVideoClick(videoUri, HealthRecordViewModel.FILE_TYPE_VIDEO);
}
break;
}
}
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Video.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
最佳答案
How to get the file path with extension?
你不知道。不要求用户选择在您具有读取权限的位置保存为文件的一段内容。并且不要求 ContentProvider
提供一些将 Uri
转换为文件路径的方法。
使用ContentResolver
和openInputStream()
读入Uri
标识的内容。
关于android - 如何从视频文件的内容 URI 获取文件路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41282041/