0

I want a feature in my jetpack compose app that a file picker opens up and lets the user select a document file like a pdf. In my below implementation, I can get the URI of the selected file but I want to have the File object of the selected file to send it to my server. the problem is that the way I create the File, every time I get this error: open failed: ENOENT (No such file or directory) I think that the error is because of permissions. I have implemented a permissions check too but I think that MANAGE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE are not applicable anymore in api 33. I also declared them in the manifest too. I used to do such work when my projects were view and not jetpack compose with SAF.but it does not work here with compose. I have also tried a lot of solutions that in the end I got this final code. I also tested AI chatbots answers but no help.

here is the code

@Composable
fun FilePicker(){
    val coroutineScope = rememberCoroutineScope()
    val selectedFileUri = remember { mutableStateOf<Uri?>(null) }
    val filePickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.OpenDocument(),
        onResult = { uri ->
            if (uri != null) {
                selectedFileUri.value = uri
                coroutineScope.launch {
                    withContext(Dispatchers.IO) {
                        uploadFileToServer(file = File(selectedFileUri.value?.path))
                    }
                }
                onFileSelected(uri)
            }
        }
    )
    val resultLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestPermission(),
        onResult = { isGranted ->
            if(isGranted)
                filePickerLauncher.launch(arrayOf("*/*"))
        }
    )
    resultLauncher.launch(
        Manifest.permission.READ_EXTERNAL_STORAGE  // the MANAGE_EXTERNAL_STORAGE also not working
    )
}

please help me find the problem and have that feature in my app.

mas
  • 65
  • 5
  • "but I want to have the File object of the selected file to send it to my server" -- why? That is not an option with `OpenDocument`. It is also unnecessary if [you are using a well-written client library for sending the data to the server](https://stackoverflow.com/a/56308643/115145). – CommonsWare Aug 06 '23 at 13:29
  • I use Retrofit which uses MultipartBody for posting to server. That's why I need the file object. – mas Aug 06 '23 at 13:32
  • 1
    If you read [the Stack Overflow answer that I linked to](https://stackoverflow.com/a/56308643/115145), or [this blog post](https://commonsware.com/blog/2020/07/05/multipart-upload-okttp-uri.html), or [this blog post](https://cketti.de/2020/05/23/content-uris-and-okhttp/), you will see how to do this without a `File` object. – CommonsWare Aug 06 '23 at 13:43

0 Answers0