在android 11(sdk 30)中,如何从下载文件夹上传pdf文件?我收到 EACCES 消息,但权限被拒绝

Dha*_*yas 6 sdk android file-permissions

它在 android 10 中运行良好,带有 requestLegacyExternalStorage="true" 标签。该应用程序就像whatsapp,以便用户可以选择文件/图像/位置并将其发送给另一个用户。图像和位置工作正常,但我在上传文档时遇到错误。我认为我的应用不符合 MANAGE_EXTERNAL_STORAGE 权限。所以如果您有任何解决方案,请分享。

获得 READ_EXTERNAL_STORAGE 和 WRITE_EXTERNAL_STORAGE 运行时权限后我的文件选择器。

    Intent intent = new Intent();
    intent.setType("*/*");
    intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(Intent.createChooser(intent, "Select File"), 1);
Run Code Online (Sandbox Code Playgroud)

在 OnActivityResult 中,我在“文件”中获取全局变量的文档。

       Uri uri = data.getData();
       // Log.e("cs","uri =>"+uri);

        file = new File(uri.getPath());

        final String[] split = file.getPath().split(":");//split the path.
        String filePath = split[1];//assign it to a string(your choice).

        //Log.e("cs","filepath=>"+filePath);

        file = new File(filePath);

       // Log.e("cs","file=>"+file.exists());
Run Code Online (Sandbox Code Playgroud)

当我上传文件时出现问题

    RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
    MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
Run Code Online (Sandbox Code Playgroud)

所以在改造中它会转到 onFailure 并且我收到错误 :: open failed: EACCES (Permission returned) 。

Abh*_*IBS 1

您需要添加的解决方案

<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
Run Code Online (Sandbox Code Playgroud)

在清单文件中,并尝试在 android 11 手机中获取文件访问权限。然后您将打开并从存储中读取该文件。