How to access file from shared storage in Jetpack Compose?

Viewed 659

I have form where I need to attach a file from phone. I have been looking for file picker but it can only access images not files like pdf doc docx etc. How to achieve this all in jetpack compose?

1 Answers

According to documentation, it could be done with Intent.ACTION_OPEN_DOCUMENT.

In Compose it you need rememberLauncherForActivityResult to do it:

var pickedImageUri by remember { mutableStateOf<Uri?>(null) }
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
    println("selected file URI ${it.data?.data}")
    pickedImageUri = it.data?.data
}
pickedImageUri?.let {
    Text(it.toString())
}
Button(
    onClick = {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            .apply {
                addCategory(Intent.CATEGORY_OPENABLE)
            }
        launcher.launch(intent)
    }
) {
    Text("Select")
}
Related