首页 > 解决方案 > 无法从外部存储和其他文件夹(下载除外)上传/选择 Android 11 设备中的图像和文件附件

问题描述

你好呀,

这是我的应用程序的源代码供参考

MainActivity.java

public void addFiles() {
    if (AppUtils.storageInitialCheck(getActivity())) {
        AppUtils.storagePermisson(getActivity());
    } else {
        picupFile(AppUtils.intentSelect.ADD_HOME_WORK_FILE_UPLOAD);
    }
}

public void picupFile(int fileUpload) {

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setAction(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"), fileUpload);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        AppLog.LOGE("Exception");
    }

}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    AppLog.LOGE("onActivityResult() called with: requestCode = [" + requestCode + "], resultCode = [" + resultCode + "], data = [" + data + "]");

    if (requestCode == AppStrings.uploadPic.PROFILE_PIC_SELECTION_RESULT) {
        if (data != null) {
            String path = data.getExtras().getString(AppStrings.uploadPic.selected_image_path);

            SelectedPicModel model = new SelectedPicModel();
            model.setImage_id("0");
            model.setImage_path(path);
            selectedPicArrayList.add(model);
            AppLog.LOGE("selected_image_path--->" + path);
            AppLog.LOGE("onActivityResult:111--> " + AppUtils.getFilesize(path));

            adapter.notifyDataSetChanged();

            updateAddpicbutton();
        }
    }
    else if (resultCode == Activity.RESULT_OK && requestCode == AppUtils.intentSelect.ADD_HOME_WORK_FILE_UPLOAD) {
        String path = "";
        try {
            Uri uri = data.getData();

            if(uri==null)
            {
                Toast.makeText(getContext(),"URI is NULL",Toast.LENGTH_LONG).show();

            }
            else {
                AppLog.LOGE("URI-------------->"+uri);
            }

            path = AppUtils.getfilePath(getContext(), uri);
            AppLog.LOGE("FILE PATH ---->"+path);

            if (path != null) {

                SelectedPicModel model = new SelectedPicModel();
                model.setImage_id("0");
                model.setImage_path(path);
                selectedPicArrayList.add(model);
                AppLog.LOGE("selected_image_path--->" + path);
                AppLog.LOGE("onActivityResult:111--> " + AppUtils.getFilesize(path));

                adapter.notifyDataSetChanged();

                updateAddpicbutton();

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

    if (requestCode == Appintegers.NotbrdStudentsActivity) {
        sendstudeintIds = "";
        if (data != null) {
            student_array = (ArrayList<StudentsModel>) data.getSerializableExtra(AppStrings.intentData.student_array);
            getSelectedIds(student_array);
            if (getSelectedNames(student_array).equals("")){
                selected_student_tv.setText(getResources().getString(R.string.select_students));
            }else {
                selected_student_tv.setText(getSelectedNames(student_array));
            }
        }
    }
}

AppUtils.java

public static String getfilePath(final Context context, final Uri uri) {

    // DocumentProvider
    if (DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProviderString[] contentUriPrefixesToTry
        else if (isDownloadsDocument(uri)) {
            String fileName = getFilePath1(context, uri);
            if (fileName != null) {
                return Environment.getExternalStorageDirectory().toString()+"/Download/"+fileName;
            }

            final String id = DocumentsContract.getDocumentId(uri);

            String[] contentUriPrefixesToTry = new String[]{
                    "content://downloads/public_downloads",
                    "content://downloads/my_downloads",
                    "content://downloads/all_downloads"
            };
            for (String contentUriPrefix : contentUriPrefixesToTry) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
                AppLog.LOGV("contentUri---->" + contentUri);
                try {
                    String path = getDataColumn(context, contentUri, null, null);
                    AppLog.LOGV("1.contentUri path---->" + path);
                    if (path != null) {
                        AppLog.LOGV("2.contentUri matched path---->" + path);
                        return path;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[]{
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;

}

如果有人在这个问题上帮助我,那将是很大的帮助。

标签: javaandroidandroid-studio

解决方案


推荐阅读