获取 URI 的路径始终为空?

Getting path to URI is always null?

所以我正在使用改装将图像上传到我们的服务器,并使用图库选择器来选择图像。我正在尝试获取图像的路径,因为 uri.getPath() returns file not found 异常。我几乎看过所有关于这个主题的 Whosebug 文章,但仍然没有答案。我拥有的以下代码与我在网上看到的所有代码都相似,它总是 returns null,我不知道为什么。请帮忙

        @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
        try {
            android.net.Uri selectedImage = data.getData();

            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
            // Log.d(TAG, String.valueOf(bitmap));
            ImageView imageView = (ImageView) findViewById(R.id.expandedProfilePic);
            imageView.setImageBitmap(bitmap);

            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            android.database.Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            if (cursor == null)
                return;

            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();

            // is always null
            System.out.println("FILE PATH " + filePath);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

I am trying to get the path of the image, because uri.getPath() returns file not found exception

假设 "gallery chooser",你的意思是 ACTION_GET_CONTENT 或者可能 ACTION_PICK,没有路径,因为 Uri 不是文件。

I have literally seen almost every Whosebug article on this subject

不,你没有。具体来说,我贡献的几十个,比如this one or this one or or or or or or or this one or this one or this one or this one or this one,你一个都没读过。这些都是 2017 年的数据。

The following code that I have is similar to everything I have seen online

并且该代码不适用于大多数 Uri 值。

使用 ContentResolveropenInputStream() 得到 InputStreamUri 识别的内容。理想情况下,您只需使用 InputStream。在 Retrofit 的情况下,虽然我没有尝试用它上传内容,但我的猜测是它坚持使用一个文件。在这种情况下,对您控制的某个文件使用 InputStreamFileOutputStream 来复制内容。然后,上传副本,完成后将其删除。