如何从视频文件的内容URI中获取文件路径? [英] How do I get the file path from the content URI for video files?

查看:356
本文介绍了如何从视频文件的内容URI中获取文件路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想附加来自Android存储设备的图像或视频文件.当我从图库中选择一个视频时,它会返回内容uri路径.

I want to attach images or video files from the Android storage. When I select a video from the gallery, it returns the content uri path.

如何从内容URI中获取带有扩展名的文件路径?

How do I get the file path with extension from the content URI?

我尝试了以下代码,但在棒棒糖中返回null:

I tried following code, but it returns null in lollipop:

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转换为文件路径的方法.

You don't. There is no requirement that the user select a piece of content that is saved as a file in a place that you have read access to. And there is no requirement that a ContentProvider offer some means of translating a Uri to a file path.

使用ContentResolveropenInputStream()读取由Uri标识的内容.

Use ContentResolver and openInputStream() to read in the content identified by the Uri.

这篇关于如何从视频文件的内容URI中获取文件路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆