2

When trying to upload selected pdf it will show "open failed: EACCES (Permission denied)" error for that file. It is happening only in Android 11 (API 30). For other version its working fine.

I am using below code to pick pdf from device

`val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
            type = INTENT_TYPE_PDF
            addCategory(Intent.CATEGORY_OPENABLE)
            putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
            }
 startActivityForResult(intent, REQUEST_CODE_PDF_ATTACH)`

On Activity result extracting the file path from Uri

public static String getPath(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];
                String storageDefinition;

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                } else {
                    if (Environment.isExternalStorageRemovable()) {
                        storageDefinition = "EXTERNAL_STORAGE";
                    } else {
                        storageDefinition = "SECONDARY_STORAGE";
                    }
                    return System.getenv(storageDefinition) + "/" + split[1];
                }

            } else if (isDownloadsDocument(uri)) {

                // DownloadsProvider
                
                final String id = DocumentsContract.getDocumentId(uri);

                if (id != null && id.startsWith("raw:")) {
                    return id.substring(4);
                }

                String otherId = null;
                if (id != null && id.startsWith("msf:")) {
                    String[] split = id.split(":");
                    otherId = split[1];
                }

                String[] contentUriPrefixesToTry = new String[]{
                        "content://downloads/public_downloads",
                        "content://downloads/my_downloads",
                        "content://downloads/all_downloads"
                };

                for (String contentUriPrefix : contentUriPrefixesToTry) {
                   
                    Uri contentUri = null;
                    if (otherId == null) {
                        contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
                    } else {
                        contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.parseLong(otherId));
                    }
                    try {
                        String path = getDataColumn(context, contentUri, null, null);
                        if (path != null) {
                            return path;
                        } else {
                            DebugLog.e("Path is null for " + contentUri);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        DebugLog.e(e.getMessage());
                    }
                }

                DebugLog.e("File is not accessible");

                // return destinationPath;
                return null;
            } else if (isMediaDocument(uri)) {
                // MediaProvider
                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);
            }

        } else if ("content".equalsIgnoreCase(uri.getScheme())) {// MediaStore (and general)
            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);

        } else if ("file".equalsIgnoreCase(uri.getScheme())) {// File
            return uri.getPath();
        }

        return null;
    }

After getting the file path upload it to write URL of amazon s3 using

public static Response uploadFileSync(@Nullable String localFilePath, String urlToUploadTo,
                                          String contentTypeString) throws Exception {
        RequestBody requestBody;
        if (localFilePath == null) {
            requestBody = RequestBody.create(null, new byte[0]);
        } else {
            java.io.File file = new java.io.File(localFilePath);
            MediaType contentType = MediaType.parse(contentTypeString);
            requestBody = RequestBody.create(contentType, file);
            DebugLog.i("About to start upload of " + Utils.formatSize(file.length()));
        }

        DebugLog.d("Upload URL: " + urlToUploadTo);
        Request request = new Request.Builder()
                .url(urlToUploadTo)
                .put(requestBody)
                .build();

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(3, TimeUnit.MINUTES)
                .readTimeout(3, TimeUnit.MINUTES)
                .build();

        // the callback is run on the same background thread.
        // for more information, please read Jake's comment here
        // https://stackoverflow.com/questions/24246783/okhttp-response-callbacks-on-the-main-thread/24248963#24248963
        return okHttpClient.newCall(request).execute();
    }

Getting error while okHttpClient.newCall(request).execute()

  • 2
    Post your onActivityResult code with code where you use the obtained uri. Where you try to upload it or open a stream. You did not even post the statement that causes this error. – blackapps Jun 24 '21 at 09:46
  • Get rid of `Uri.fromFile(sourceFile)`. Use the `Uri` that you got back in `onActivityResult()`. – CommonsWare Jun 24 '21 at 11:21
  • @blackapps Updated the question with more details. – Sumit Ghawate Jun 24 '21 at 12:55
  • 1
    `On Activity result extracting the file path from Uri` You should not do such nasty things. Use the uri directly to upload the file. – blackapps Jun 24 '21 at 12:59
  • @blackapps we need file object to upload the file and to get file object we need actual file path. – Sumit Ghawate Jun 24 '21 at 14:39
  • 1
    No you do not need a File object. You have been sleeping as using an uri/input stream has been added. – blackapps Jun 24 '21 at 16:52
  • 1
    @SumitGhawate did you find any solution I am also getting error while uploading file to AWS bucket and the error only in Android 11, please let me know if you have any solution. – Akki Jangir Sep 03 '21 at 10:14
  • Same issue, not getting absolute file path only. so not able to uplaod – Arth Tilva Sep 16 '21 at 07:20

0 Answers0