Android - 如何从文档中获取选定的文件名

时间:2014-06-20 08:08:35

标签: android android-intent android-file

我正在使用以下代码启动选择documnets的意图。

private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"), 1);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.",
                Toast.LENGTH_SHORT).show();
    }
}

在onActivity结果中,当我试图获取文件路径时,它会在文件名的位置给出一些其他数字。

    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case 1:
        if (resultCode == RESULT_OK) {
            // Get the Uri of the selected file
            Uri uri = data.getData();
            File myFile = new File(uri.toString());
            String path = myFile.getAbsolutePath();
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

我得到的路径值是这样的。 “内容://com.android.providers.downloads.documents/document/1433” 但我想要像doc1.pdf等真正的文件名。如何获得它?

4 个答案:

答案 0 :(得分:44)

当您获得内容:// uri时,您需要查询内容解析程序,然后获取显示名称。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case 1:
        if (resultCode == RESULT_OK) {
            // Get the Uri of the selected file
            Uri uri = data.getData();
            String uriString = uri.toString();
            File myFile = new File(uriString);
            String path = myFile.getAbsolutePath();
            String displayName = null;

            if (uriString.startsWith("content://")) {                   
                Cursor cursor = null;
                try {                           
                    cursor = getActivity().getContentResolver().query(uri, null, null, null, null);                         
                    if (cursor != null && cursor.moveToFirst()) {                               
                        displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                    }
                } finally {
                    cursor.close();
                }
            } else if (uriString.startsWith("file://")) {           
                displayName = myFile.getName();
            }
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

答案 1 :(得分:1)

以下是完整的解决方案:

将您的上下文和URI对象从onActivityResult传递到下面的函数以获取正确的路径:

它将路径设为/storage/emulated/0/APMC Mahuva/Report20-11-2017.pdf(我选择了此Report20-11-2017.pdf文件)

String getFilePath(Context cntx, Uri uri) {
    Cursor cursor = null;
    try {
        String[] arr = { MediaStore.Images.Media.DATA };
        cursor = cntx.getContentResolver().query(uri,  arr, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

答案 2 :(得分:0)

你可以试试这个,我希望它能帮助你:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("inside", "onActivityResult");
        if(requestCode == FILE_MANAGER_REQUEST_CODE)
        {
            // Check if the user actually selected an image:
            if(resultCode == Activity.RESULT_OK)
            {
                // This gets the URI of the image the user selected:
                Uri selectedFileURI = data.getData();
                File file = new File(getRealPathFromURI(selectedFileURI));



                // Create a new Intent to send to the next Activity:
            }
        }
    }


    private String getRealPathFromURI(Uri contentURI) {
            String result;
            Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
            if (cursor == null) { // Source is Dropbox or other similar local file path
                result = contentURI.getPath();
            } else { 
                cursor.moveToFirst(); 
                int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
                result = cursor.getString(idx);
                cursor.close();
            }
            return result;
        }

答案 3 :(得分:0)

首先检查是否为应用程序授予了权限。以下方法用于检查运行时权限'

 public void onClick(View v) {
            //Checks if the permission is Enabled or not...
            if (ContextCompat.checkSelfPermission(thisActivity,
                    Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(thisActivity,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_PERMISSION);
            } else {
                Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(galleryIntent, USER_IMG_REQUEST);
            }
        }

和below方法用于查找文件的uri路径名

private String getRealPathFromUri(Uri uri) {
    String[] projection = {MediaStore.Images.Media.DATA};
    CursorLoader cursorLoader = new CursorLoader(thisActivity, uri, projection, null, null, null);
    Cursor cursor = cursorLoader.loadInBackground();
    int column = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    String result = cursor.getString(column);
    cursor.close();
    return result;
}

以上方法可以用作

 if (requestCode == USER_IMG_REQUEST && resultCode == RESULT_OK && data != null) {
        Uri path = data.getData();
        try {
            String imagePath = getRealPathFromUri(path);
            File file = new File(imagePath);
            RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
            MultipartBody.Part imageFile = MultipartBody.Part.createFormData("userImage", file.getName(), reqFile);