【问题标题】:Android- Not able to select file from internal storageAndroid-无法从内部存储中选择文件
【发布时间】:2016-07-26 05:21:37
【问题描述】:

我必须从移动设备的内部存储中获取图像并上传到服务器。如果我从 sdcard 中选择图像,它工作正常,而如果我从内部存储中选择图像,它会显示错误,我无法收到此错误。 这是 logcat 输出 -

07-26 10:32:24.868: W/System.err(24051): java.io.FileNotFoundException: /document/primary:Pictures/Screenshots/Screenshot_20160712-172722.png:打开失败:ENOENT(没有这样的文件或目录)

我正在使用此代码获取图像

private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                1);
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(getActivity(), "Please install a File Manager.",
                Toast.LENGTH_SHORT).show();
    }
}

OnActivityResult 代码

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    // 1
    if (requestCode == 1) {
        if (resultCode == Activity.RESULT_OK) {
            try {
                // SDK < API11
                if (Build.VERSION.SDK_INT < 11)
                    realPath_1 = RealPathUtil
                            .getRealPathFromURI_BelowAPI11(getActivity(),
                                    data.getData());

                // SDK >= 11 && SDK < 19
                else if (Build.VERSION.SDK_INT < 19)
                    realPath_1 = RealPathUtil.getRealPathFromURI_API11to18(
                            getActivity(), data.getData());

                // SDK > 19 (Android 4.4)
                else
                    realPath_1 = RealPathUtil.getRealPathFromURI_API19(
                            getActivity(), data.getData());

                Log.e("", "Build Version     : " + Build.VERSION.SDK_INT);
                Log.e("", "Get Data Get Path : " + data.getData().getPath());
                if (realPath_1.equalsIgnoreCase("")) {
                    realPath_1 = data.getData().getPath().toString();
                }
                Log.e("", "Real Path 1       : " + realPath_1);

                file_1 = realPath_1.substring(
                        realPath_1.lastIndexOf('/') + 1,
                        realPath_1.length());
                Log.i("File Name 1 ", file_1);
                txt_file_name_1.setText(file_1);

            } catch (Exception e) {
                Uri selected = data.getData();
                realPath_1 = selected.getPath();
                file_1 = realPath_1.substring(
                        realPath_1.lastIndexOf('/') + 1,
                        realPath_1.length());
                Log.i("File Name 1 ", file_1);
                txt_file_name_1.setText(file_1);
            }
        }
    }}

这是一个名为 RealPathUtil 的类,用于获取图像的路径。 我的

android:minSdkVersion="14" android:targetSdkVersion="23"

并从类 RealPathUtil 中调用此方法

public static String getRealPathFromURI_API19(Context context, Uri uri) {
    String filePath = "";
    String wholeID = DocumentsContract.getDocumentId(uri);

    // Split at colon, use second item in the array
    String id = wholeID.split(":")[1];

    String[] column = { MediaStore.Images.Media.DATA };

    // where id is equal to
    String sel = MediaStore.Images.Media._ID + "=?";

    Cursor cursor = context.getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel,
            new String[] { id }, null);

    int columnIndex = cursor.getColumnIndex(column[0]);

    if (cursor.moveToFirst()) {
        filePath = cursor.getString(columnIndex);
    }

    cursor.close();

    return filePath;
}

请提前帮助和感谢。

【问题讨论】:

  • 目前使用哪个版本的安卓设备进行测试
  • 型号 - Moto G(第 3 代),Android 版本 - 6.0.1

标签: android android-sdcard android-internal-storage


【解决方案1】:

试试这个:

boolean isKitKat = false;
button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            showFileChooser();
        }
    });

显示文件选择器功能代码

private void showFileChooser() {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        isKitKat = true;
        startActivityForResult(Intent.createChooser(intent, "Select file"), 1);
    } else {
        isKitKat = false;
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select file"), 1);
    }
}

OnActivity 结果代码:

@TargetApi(19)
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {

        if (data != null && data.getData() != null && resultCode == getActivity().RESULT_OK) {

            boolean isImageFromGoogleDrive = false;

            Uri uri = data.getData();

            if (isKitKat && DocumentsContract.isDocumentUri(getActivity(), uri)) {
                if ("com.android.externalstorage.documents".equals(uri.getAuthority())) {
                    String docId = DocumentsContract.getDocumentId(uri);
                    String[] split = docId.split(":");
                    String type = split[0];

                    if ("primary".equalsIgnoreCase(type)) {
                        realPath_1 = Environment.getExternalStorageDirectory() + "/" + split[1];
                    } else {
                        Pattern DIR_SEPORATOR = Pattern.compile("/");
                        Set<String> rv = new HashSet<>();
                        String rawExternalStorage = System.getenv("EXTERNAL_STORAGE");
                        String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE");
                        String rawEmulatedStorageTarget = System.getenv("EMULATED_STORAGE_TARGET");
                        if (TextUtils.isEmpty(rawEmulatedStorageTarget)) {
                            if (TextUtils.isEmpty(rawExternalStorage)) {
                                rv.add("/storage/sdcard0");
                            } else {
                                rv.add(rawExternalStorage);
                            }
                        } else {
                            String rawUserId;
                            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
                                rawUserId = "";
                            } else {
                                String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                                String[] folders = DIR_SEPORATOR.split(path);
                                String lastFolder = folders[folders.length - 1];
                                boolean isDigit = false;
                                try {
                                    Integer.valueOf(lastFolder);
                                    isDigit = true;
                                } catch (NumberFormatException ignored) {
                                }
                                rawUserId = isDigit ? lastFolder : "";
                            }
                            if (TextUtils.isEmpty(rawUserId)) {
                                rv.add(rawEmulatedStorageTarget);
                            } else {
                                rv.add(rawEmulatedStorageTarget + File.separator + rawUserId);
                            }
                        }
                        if (!TextUtils.isEmpty(rawSecondaryStoragesStr)) {
                            String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator);
                            Collections.addAll(rv, rawSecondaryStorages);
                        }
                        String[] temp = rv.toArray(new String[rv.size()]);
                        for (int i = 0; i < temp.length; i++) {
                            File tempf = new File(temp[i] + "/" + split[1]);
                            if (tempf.exists()) {
                                realPath_1 = temp[i] + "/" + split[1];
                            }
                        }
                    }
                } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                    String id = DocumentsContract.getDocumentId(uri);
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                    Cursor cursor = null;
                    String column = "_data";
                    String[] projection = {column};
                    try {
                        cursor = getActivity().getContentResolver().query(contentUri, projection, null, null,
                                null);
                        if (cursor != null && cursor.moveToFirst()) {
                            int column_index = cursor.getColumnIndexOrThrow(column);
                            realPath_1 = cursor.getString(column_index);
                        }
                    } finally {
                        if (cursor != null)
                            cursor.close();
                    }
                } else if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                    String docId = DocumentsContract.getDocumentId(uri);
                    String[] split = docId.split(":");
                    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;
                    }

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

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

                    try {
                        cursor = getActivity().getContentResolver().query(contentUri, projection, selection, selectionArgs, null);
                        if (cursor != null && cursor.moveToFirst()) {
                            int column_index = cursor.getColumnIndexOrThrow(column);
                            realPath_1 = cursor.getString(column_index);
                        }
                    } finally {
                        if (cursor != null)
                            cursor.close();
                    }
                } else if ("com.google.android.apps.docs.storage".equals(uri.getAuthority())) {
                    isImageFromGoogleDrive = true;
                }
            } else if ("content".equalsIgnoreCase(uri.getScheme())) {
                Cursor cursor = null;
                String column = "_data";
                String[] projection = {column};

                try {
                    cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
                    if (cursor != null && cursor.moveToFirst()) {
                        int column_index = cursor.getColumnIndexOrThrow(column);
                        realPath_1 = cursor.getString(column_index);
                    }
                } finally {
                    if (cursor != null)
                        cursor.close();
                }
            } else if ("file".equalsIgnoreCase(uri.getScheme())) {
                realPath_1 = uri.getPath();
            }

            try {
                Log.d(TAG, "Real Path 1 : " + realPath_1);
                file_1 = realPath_1.substring(realPath_1.lastIndexOf('/') + 1, realPath_1.length());
                Log.i("File Name 1 ", file_1);
              } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }}

这里 file_1 = 获取图像名称,realPath_1 显示来自内部或外部存储的图像的完整路径。

乐于助人:)

【讨论】:

    【解决方案2】:
    • 使用以下代码获取文件 URL。

       public static String getPath(final Context context, final Uri uri) {
      
      // check here to KITKAT or new version
      final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
      
      // DocumentProvider
      if (isKitKat && 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];
              }
          }
          // DownloadsProvider
          else if (isDownloadsDocument(uri)) {
      
              final String id = DocumentsContract.getDocumentId(uri);
              final Uri contentUri = ContentUris.withAppendedId(
                      Uri.parse("content://downloads/public_downloads"),
                      Long.valueOf(id));
      
              return getDataColumn(context, contentUri, null, null);
          }
          // 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 the remote address
          if (isGooglePhotosUri(uri))
              return uri.getLastPathSegment();
      
          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 index = cursor.getColumnIndexOrThrow(column);
              return cursor.getString(index);
          }
      } finally {
          if (cursor != null)
              cursor.close();
      }
      return null;
      }
      public static boolean isExternalStorageDocument(Uri uri) {
      return "com.android.externalstorage.documents".equals(uri
              .getAuthority());
      }
      public static boolean isDownloadsDocument(Uri uri) {
      return "com.android.providers.downloads.documents".equals(uri
              .getAuthority());
      }
      public static boolean isMediaDocument(Uri uri) {
      return "com.android.providers.media.documents".equals(uri
              .getAuthority());
      
      public static boolean isGooglePhotosUri(Uri uri) {
      return "com.google.android.apps.photos.content".equals(uri
              .getAuthority());
      }
      

    【讨论】:

    • 格栅作业。谢谢!
    【解决方案3】:

    您的代码看起来不错,您只需要从用户那里获得运行时权限。 Andorid 6.0 或更高版本在运行时需要用户的许可,仅声明它们是不够的。

    在这里查看我之前关于如何获得runtime permissions 的帖子。

    更新:

        private void showFileChooser() {
        try {
          // Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
          // startActivityForResult(i, RESULT_LOAD_IMAGE);
          Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
          intent.setType("file/*");
          startActivityForResult(intent, RESULT_LOAD_IMAGE);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(getActivity(), "Please install a File Manager.",
                    Toast.LENGTH_SHORT).show();
        }
    }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
                //Uri selectedImage = data.getData();
                txt_file_name_1.setText(data.getData().toString());
           }
      }
    

    【讨论】:

    • 如果我选择图像形式的 SD 卡它可以工作,但如果我从内部存储中选择图像,它会说 - 没有这样的文件或目录。
    • 您是否正在使用文件管理器从app 内部存储中获取文件?
    • 没有其他人可以访问您的应用程序内部存储,只有您的线程可以访问它。文件探索在单独的线程上运行。
    • 那么我知道什么,请指导我。
    • @MarkLoke 你知道你文件的保存路径吗?
    【解决方案4】:

    我有一个类似的打开文件管理器的代码,我试图打开文件管理器来保存文件,但我在任何地方都看不到内部存储,它只在下载文件夹中打开。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多