Cannot create a file using the Uri of `ACTION_GET_

2020-03-31 08:28发布

问题:

I'm trying to select pdf file from the device and upload them to the server. ACTION_GET_CONTENT is used to select pdf from the device.

sel_book.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setType("application/pdf");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select PDF"), 1);
        }
    });

On activity result I get the Uri and save it as a String.

public void onActivityResult(int requestCode, int resultCode, Intent result) {
    if (resultCode == RESULT_OK) {
        if (requestCode == 1) {
            Uri uri = result.getData();
            String uriString = uri.toString();
            File myFile = new File(uriString);
            path = myFile.getAbsolutePath();
        }
    }
}

It results the path as, /document/primary:Download/Aptitude_2016_17.pdf. I need to use this to create a new file. File selectedFile = new File(selectedFilePath);. But it doesn't create File. selectedFile.isFile() returns false. I have no idea why is it. Please help me to solve this. Thanks in advance.

回答1:

ACTION_GET_CONTENT is used to select pdf from the device.

This allows the user to select a piece of content. It does not have to be a file.

On activity result I get the Uri and save it as a String.

That is not how you use a Uri.

It results the path as, /document/primary:Download/Aptitude_2016_17.pdf.

That is not a filesystem path. That is a part of a Uri that has a content scheme. You do not get a file from ACTION_GET_CONTENT. You get a Uri that points to a piece of content. That Uri could point to anything that the user and the other app choose:

  • A file that you can access, via a Uri with a file scheme
  • A file, but one that you cannot access (e.g., on internal storage of another app)
  • The contents of a BLOB column in the database
  • A piece of content that needs to be downloaded
  • And so on

Use ContentResovler and openInputStream() to get a stream on whatever the content is. Either use that directly (with whatever you are using to upload this content), or use that stream to make your own file with a copy of that content, so that you have a file that you can use.



标签: android pdf uri