1

这是我活动课的一部分。通过调用下面的意图,我打开了一个文件选择器意图来选择图像或视频。到目前为止,这有效。

public class Activity extends AppCompatActivity {

    EditText et;
    private static final int PICKFILE_RESULT_CODE = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // EditText to show filepath after intent
        et = (EditText)findViewById(R.id.et);

        // Start intent to pick a file
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*|video/*");
        startActivityForResult(intent,PICKFILE_RESULT_CODE);
    }

在这里我检索文件的路径:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode)
        {
            case PICKFILE_RESULT_CODE:
                if(resultCode==RESULT_OK){

                    // Get path of selected file and set it to editText
                    String filePath = data.getData().getPath();
                    et_upload.setText(filePath);
                }
                break;
        }
    }
}

结果看起来像,

"/path/to/file/fileName".

但我想包括文件扩展名:

"/path/to/file/fileName.png"

我错过了什么?

预先感谢您的任何帮助。:)

4

2 回答 2

1

到目前为止,这有效。

setType() does not support the | operator.

Anything I missed?

First, the path alone is meaningless. ACTION_GET_CONTENT will typically return a content:// Uri, and the path is only meaningful to the ContentProvider. For example, this is not a path to a file on a filesystem.

Second, that Uri does not have to include a file extension.

If you want to know the MIME type of the content backed by that Uri, use a ContentResolver and its getType() method. If you want to convert that MIME type into a file extension, use MimeTypeMap.

于 2015-06-09T12:49:05.300 回答
0

这样你就可以实现这个..记住这不是一个完整的解决方案..

根据它调整您的代码

public String getImagePath(Uri uri){
   Cursor cursor = getContentResolver().query(uri, null, null, null, null);
   cursor.moveToFirst();
   String document_id = cursor.getString(0);
   document_id = document_id.substring(document_id.lastIndexOf(":")+1);
   cursor.close();

     cursor = getContentResolver().query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
   cursor.moveToFirst();
   String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
   cursor.close();

   return path;
}
于 2015-06-09T13:00:15.583 回答