Android 从设备中选择文档但无法获取具有扩展名类型的文件名

Android selecting document from device but not able to get the file name with the extension type

我希望用户能够将 pdf 和图像文件上传到服务器,然后 选择文件我想显示文件名和类型是否为 .pdf 或.png

但是文件路径中没有包含文件扩展名

这就是我开始意图的方式

   btnUploadDocument.setOnClickListener(view -> {
            Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
            chooseFile.addCategory(Intent.CATEGORY_OPENABLE);
            chooseFile.setType("image/*|application/pdf");
            chooseFile = Intent.createChooser(chooseFile, "Choose a file");
            startActivityForResult(chooseFile, REQ_UPLOAD_DOCUMENT);
        });

这是我获取返回数据的方式

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

    if(requestCode == REQ_UPLOAD_DOCUMENT && resultCode == RESULT_OK && data != null){

        Uri path = data.getData();
        try {
            InputStream inputStream = FTLBookingActivity.this.getContentResolver().openInputStream(path);
            byte[] pdfInBytes = new byte[inputStream.available()];
            inputStream.read(pdfInBytes);
            String encodedPDF = Base64.encodeToString(pdfInBytes, Base64.DEFAULT);
            Toast.makeText(this, "Document Selected", Toast.LENGTH_SHORT).show();

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

    }
}

我尝试选择图像,但路径低于值

content://media/external/images/media/599

But the file extension is not included in the file path

没有“文件路径”,因为这不是文件。

I want to display the name of the file and the type wether it's .pdf or .png

使用 DocumentFile.fromSingleFile()Uri 包裹在 DocumentFile 中。然后,您可以 use getName() and getType() on the DocumentFile 分别获取显示名称和 MIME 类型。