从Android中的Intent中选择时,文件返回空(“”)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从Android中的Intent中选择时,文件返回空(“”)相关的知识,希望对你有一定的参考价值。

我正在尝试上传视频。我所做的是,我已经下载了一个示例视频并尝试使用意图选择视频。我期待的是我选择的文件,我会得到它并传递给网络并上传。由于我之前没有任何经验,我很难有时间处理它。

private void getFile() {
    Intent intent = new Intent();
    intent.setType("video/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Video"), REQUEST_CODE_PICKER);
}

当我选择视频时,我收到了一个uri onActivityResult

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        Uri uri = data.getData();
        String uriPath = uri.getPath(); // uriPath = "/document/video:7876"
        File fileToUpload = new File(uriPath); // fileToUpload = ""
        String videoPath = getRealVideoPathFromURI(getContentResolver(),uri); // videoPath = "/storage/emulated/0/Download/testVideo.mp4"
        File videoFile = new File(videoPath); // videoFile = ""
        uploadFile(videoFile);
    }
}

我尝试了两个路径(realPath和uriPath),看看我是否得到任何文件。如果我调试我可以看到fileToUpload和videoFile都是“”。要添加,将给出所有权限读取和写入。

这是从uri获取真实视频路径的代码

String getRealVideoPathFromURI(ContentResolver contentResolver ,
                            Uri contentURI){
    Cursor cursor = contentResolver.query(contentURI, null, null, null, null);
    if (cursor == null)
        return contentURI.getPath();
    else {
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Video.VideoColumns.DATA);
        try {
            return cursor.getString(idx);
        } catch (Exception exception) {
            return null;
        }
    }
}

谁能帮我理解我做错了什么?我只需上传所选的视频文件。我这样做的方式是错的吗?如果是这样,那么这样做的正确方法是什么?由于我没有在没有搜索的情况下提出问题而没有找到答案,请尽量给我正确的答案,这可以帮助我解决这个问题。它可能是我的方法是错误的,它可能是一些设备问题等。谢谢

答案

使用以下代码获取Path。

你也应该在新文件中传递realpath(getPath(this,data.getData())。

 /**
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @author paulburke
 */
public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}


/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

以上是关于从Android中的Intent中选择时,文件返回空(“”)的主要内容,如果未能解决你的问题,请参考以下文章

android 文件选择

Android Intent Filter:无法从预览中打开音频文件?

android开发startActivityForResult从系统自带的文件管理器文件选择兼容各个版本

在 Android 4.4 中从图库中选择时裁剪

如何从 Uri xamarin android 获取实际路径

在没有安装任何文件管理器的 Android 中选择一个文件