4

我需要获取文件的路径以将其转换为输入流以进行上传。所以我选择pdf document使用文件选择器。我得到UrionActivityResult()使用 uri ,我得到文件的路径。但它没有返回正确的路径。绝对路径:

when choosing file from internal storage 
         /document/primary:pdf/HA License Plate.pdf

when choosing file from external storage
        /document/9016-4EF8:certificates/img002.pdf

所以我无法获得正确的文件路径来转换为输入流。所以请建议我在我的 android 应用程序中获取正确的文件路径?我正在使用的代码如下。

代码是:-

public void ChoosePDF(View v) {
    Intent intent = new Intent();
    // intent.setType("pdf/*");
    intent.setType("application/pdf");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Pdf"),
            REQUEST_CODE);
}

public void onActivityResult(int requestCode, int resultCode, Intent result) {
    if (resultCode == RESULT_OK) {
        if (requestCode == REQUEST_CODE) {
            Uri data = result.getData();


            if (data.getLastPathSegment().endsWith("pdf")) {
                String pdfPath = data.getPath();
                File myFile = new File(data.getPath());

                Log.i("FirstActivity", "pdfPath is " + pdfPath);
                Log.i("FirstActivity", "uri abs path is " + myFile.getAbsolutePath());

            } else {
                Toast.makeText(SplashScreenActivity.this,
                        "Invalid file type.Please choose valid file!",
                        Toast.LENGTH_LONG).show();
            }
        }
    }
}

获取文件路径时是否有任何特定于 android 版本的问题?我正在使用 android 棒棒糖设备进行测试?

4

1 回答 1

-2

使用 File file=new File(new URI(data.toString()));

于 2016-05-13T09:45:22.043 回答